Repository navigation
Expand file tree
/
Copy pathauth.js
More file actions
303 lines (286 loc) · 16.3 KB
/
Copy pathauth.js
File metadata and controls
303 lines (286 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
/* HVTracker accounts widget: sign-in / account menu, notifications bell, and
tracked-projects sync. Progressive enhancement — if the API is unavailable
(e.g. no DB locally) it silently no-ops and the public site is unaffected. */
(function () {
"use strict";
var WATCHLIST_KEY = "hvtracker_watchlist_v1";
function api(path, opts) {
return fetch(path, Object.assign({ credentials: "same-origin" }, opts || {}))
.then(function (r) { return r.ok ? r.json() : Promise.reject(r); });
}
function postJSON(path, body) {
return api(path, { method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify(body || {}) });
}
// Exposed so the inline tracked-projects toggles (homepage + agent pages) can
// sync add/remove to the signed-in account. Harmless when logged out (401).
window.hvtSyncWatch = function (action, slug) {
if (!action || !slug) return;
postJSON("/api/watchlist", { action: action, slug: slug }).catch(function () {});
};
// Compare list — a SEPARATE local list (max 3) from the tracked-projects list.
// Used by the "Add to compare" buttons and read by the compare tool.
window.hvtCompare = {
KEY: "hvtracker_compare_v1",
MAX: 3,
get: function () { try { return JSON.parse(localStorage.getItem(this.KEY) || "[]") || []; } catch (e) { return []; } },
set: function (list) { localStorage.setItem(this.KEY, JSON.stringify(list.slice(0, this.MAX))); },
slugs: function () { return this.get().map(function (i) { return i.slug || i; }); },
has: function (slug) { return this.slugs().indexOf(slug) >= 0; },
full: function () { return this.get().length >= this.MAX; },
toggle: function (item) {
var list = this.get(), s = item.slug;
if (this.has(s)) list = list.filter(function (i) { return (i.slug || i) !== s; });
else if (list.length < this.MAX) list = list.concat([{ slug: s, name: item.name, repo: item.repo }]);
this.set(list);
renderCompareTray();
return this.get();
},
url: function () { var s = this.slugs(); return s.length ? "/compare/?a=" + s.join(",") : "/compare/"; }
};
// Floating "Compare (N)" tray — appears on any page (except the compare tool
// itself) whenever the compare list is non-empty.
function renderCompareTray() {
if (/^\/compare\//.test(location.pathname)) return;
var n = window.hvtCompare.slugs().length;
var tray = document.getElementById("hvt-compare-tray");
if (!tray) {
tray = document.createElement("a");
tray.id = "hvt-compare-tray";
document.body.appendChild(tray);
}
tray.href = window.hvtCompare.url();
tray.innerHTML = "⇄ Compare <strong>" + n + "</strong> →";
tray.hidden = n === 0;
}
function nextDest() {
// On /login itself, reuse its ?next= target instead of wrapping the current
// URL again — otherwise each hop nests another /login?next=… level.
if (location.pathname === "/login" || location.pathname === "/login/") {
var m = /[?&]next=([^&]*)/.exec(location.search);
if (m) { try { return decodeURIComponent(m[1]); } catch (e) { /* malformed */ } }
return "/";
}
return location.pathname + location.search;
}
function loginUrl(provider) {
return "/auth/" + provider + "/login?next=" + encodeURIComponent(nextDest());
}
var POP_IDS = ["hvtAcctPop", "hvtNotifPop"];
var POP_TRIGGERS = { hvtAcctPop: "hvtAcct", hvtNotifPop: "hvtBell" };
function closePops(exceptId) {
POP_IDS.forEach(function (id) {
if (id === exceptId) return;
var o = document.getElementById(id);
if (o) o.hidden = true;
var t = document.getElementById(POP_TRIGGERS[id]);
if (t) t.setAttribute("aria-expanded", "false");
});
}
function togglePop(id) {
var e = document.getElementById(id);
if (!e) return;
var open = e.hidden;
closePops(id);
e.hidden = !open;
var t = document.getElementById(POP_TRIGGERS[id]);
if (t) t.setAttribute("aria-expanded", open ? "true" : "false");
}
document.addEventListener("keydown", function (e) { if (e.key === "Escape") closePops(); });
document.addEventListener("click", function (e) {
if (!(e.target.closest && e.target.closest(".hvt-auth"))) closePops();
});
function esc(s) { return (s == null ? "" : String(s)).replace(/[&<>"]/g, function (c) {
return { "&": "&", "<": "<", ">": ">", '"': """ }[c]; }); }
injectStyles();
var slot = document.getElementById("hvt-auth-slot");
// Only a browser with a session carries the hvt_signed_in hint (set beside
// the HttpOnly session cookie, cleared at sign-out). Everyone else gets the
// Sign in link without an uncached round trip to /api/me.
if (/(?:^|;\s*)hvt_signed_in=1(?:;|$)/.test(document.cookie)) {
api("/api/me").then(function (me) {
if (me.logged_in) renderLoggedIn(me.user); else renderLoggedOut(me);
}).catch(function () { /* auth disabled — leave the public UI untouched */ });
} else {
renderLoggedOut({ providers: ["github"] });
initTrackNudge();
}
initAccountPage();
renderCompareTray();
// ---- /account page: remove-from-watchlist buttons ----
function initAccountPage() {
var btns = document.querySelectorAll(".account-remove");
if (!btns.length) return;
[].forEach.call(btns, function (btn) {
btn.addEventListener("click", function () {
var slug = btn.getAttribute("data-remove-slug");
btn.disabled = true; btn.textContent = "Removing…";
postJSON("/api/watchlist", { action: "remove", slug: slug }).then(function () {
// Drop this browser's copy too, or the next session's sync re-adds it.
saveLocalWatch(localWatch().filter(function (i) { return (i && i.slug ? i.slug : i) !== slug; }));
var li = btn.closest("li"); if (li && li.parentNode) li.parentNode.removeChild(li);
var cnt = document.querySelector("#watchlist .account-count");
if (cnt) cnt.textContent = Math.max(0, (parseInt(cnt.textContent, 10) || 1) - 1);
}).catch(function () { btn.disabled = false; btn.textContent = "Remove"; });
});
});
}
// ---- header: signed out ----
function renderLoggedOut(me) {
if (!slot) return;
var providers = (me && me.providers) || [];
var canSignIn = providers.length || (me && me.dev_login);
if (!canSignIn) { slot.innerHTML = ""; return; } // no sign-in method -> show nothing publicly
// Link to the real /login page rather than a cramped dropdown.
slot.innerHTML = '<a class="hvt-auth-btn hvt-auth-signin" href="/login?next=' +
encodeURIComponent(nextDest()) + '">Sign in</a>';
}
// ---- header: signed in ----
function renderLoggedIn(user) {
if (!slot) return;
var avatar = user.avatar_url ? '<img class="hvt-auth-avatar" src="' + esc(user.avatar_url) + '" alt="">' : "";
slot.innerHTML = '<div class="hvt-auth">' +
'<button class="hvt-bell" id="hvtBell" title="Notifications" aria-label="Notifications" aria-haspopup="true" aria-expanded="false" aria-controls="hvtNotifPop">◉' +
'<span class="hvt-bell-count" id="hvtBellCount" hidden>0</span></button>' +
'<button class="hvt-auth-btn" id="hvtAcct" aria-haspopup="true" aria-expanded="false" aria-controls="hvtAcctPop">' + avatar + "<span>" + esc(user.login || user.name || "Account") + "</span></button>" +
'<div class="hvt-auth-pop" id="hvtAcctPop" hidden>' +
'<a class="hvt-auth-item" href="/account/">Your account</a>' +
'<a class="hvt-auth-item" href="/account/#watchlist">Tracked projects</a>' +
'<button class="hvt-auth-item" id="hvtLogout">Sign out</button></div>' +
'<div class="hvt-auth-pop hvt-notif" id="hvtNotifPop" hidden>' +
'<div class="hvt-notif-head">Trust activity on your tracked projects</div>' +
'<div id="hvtNotifList" class="hvt-notif-list"><div class="hvt-notif-empty">Loading…</div></div></div>' +
"</div>";
document.getElementById("hvtAcct").addEventListener("click", function (ev) { ev.stopPropagation(); togglePop("hvtAcctPop"); });
document.getElementById("hvtLogout").addEventListener("click", logout);
document.getElementById("hvtBell").addEventListener("click", function (ev) { ev.stopPropagation(); togglePop("hvtNotifPop"); markRead(); });
syncWatchlist();
showServerTrackState();
loadNotifications();
}
function logout() {
// Real form POST -> server clears the cookie and 303-redirects home.
var f = document.createElement("form");
f.method = "post"; f.action = "/auth/logout";
var n = document.createElement("input");
n.type = "hidden"; n.name = "next"; n.value = "/";
f.appendChild(n); document.body.appendChild(f); f.submit();
}
// ---- watchlist: this browser's list (the profile Track button and homepage use it) ----
function localWatch() {
try { var raw = JSON.parse(localStorage.getItem(WATCHLIST_KEY) || "[]"); return Array.isArray(raw) ? raw : []; }
catch (e) { return []; }
}
function saveLocalWatch(items) {
try { localStorage.setItem(WATCHLIST_KEY, JSON.stringify(items)); } catch (e) { /* storage blocked */ }
}
// Merge the anonymous localStorage list into the account once per session.
function syncWatchlist() {
if (sessionStorage.getItem("hvt_wl_synced")) return;
var slugs = localWatch().map(function (i) { return i && i.slug ? i.slug : i; }).filter(Boolean);
sessionStorage.setItem("hvt_wl_synced", "1");
if (slugs.length) postJSON("/api/watchlist", { action: "sync", slugs: slugs }).catch(function () {});
}
// A project tracked on another device (or via /track/ or /scan/) is in the
// account but not in this browser's list: show it as tracked here too.
function showServerTrackState() {
var btn = document.getElementById("watchToggle");
if (!btn) return;
var slug = btn.getAttribute("data-watch-slug");
api("/api/watchlist").then(function (d) {
if ((d.slugs || []).indexOf(slug) < 0) return;
var items = localWatch();
if (!items.some(function (i) { return i && i.slug === slug; })) {
saveLocalWatch(items.concat([{ slug: slug, name: btn.getAttribute("data-watch-name"),
repo: btn.getAttribute("data-watch-repo") }]));
}
btn.classList.add("is-saved");
btn.textContent = "Tracking ✓";
}).catch(function () {});
}
// Signed out, Track saves to this browser only. Say what signing in adds.
function initTrackNudge() {
var btn = document.getElementById("watchToggle");
if (!btn) return;
btn.addEventListener("click", function () {
var old = document.getElementById("hvtTrackNudge");
if (old) old.parentNode.removeChild(old);
if (!btn.classList.contains("is-saved")) return; // just untracked
var slug = btn.getAttribute("data-watch-slug");
var p = document.createElement("p");
p.id = "hvtTrackNudge";
p.className = "hvt-track-nudge";
p.innerHTML = "Saved in this browser. <a rel=\"nofollow\" href=\"/login?next=" + encodeURIComponent("/track/" + slug + "/") +
"\">Sign in</a> to be notified when " + esc(btn.getAttribute("data-watch-name") || "it") +
"’s trust changes, on any device.";
var row = btn.closest(".hero-actions") || btn;
row.parentNode.insertBefore(p, row.nextSibling);
if (typeof window.hvtTrack === "function") window.hvtTrack("track_signin_nudge", { slug: slug });
});
}
// ---- notifications ----
function loadNotifications() {
api("/api/notifications").then(function (data) {
var c = document.getElementById("hvtBellCount");
if (c) { if (data.unread > 0) { c.textContent = data.unread > 9 ? "9+" : data.unread; c.hidden = false; } else c.hidden = true; }
var list = document.getElementById("hvtNotifList");
if (!list) return;
if (!data.items || !data.items.length) {
list.innerHTML = '<div class="hvt-notif-empty">' +
(data.watching ? "No recent changes on your watched agents." :
'Track agents to get trust-change alerts here.') + "</div>";
return;
}
list.innerHTML = data.items.map(function (n) {
return '<a class="hvt-notif-item' + (n.unread ? " is-unread" : "") + '" href="/agents/' + esc(n.slug) + '/">' +
'<span class="hvt-notif-name">' + esc(n.name) + "</span>" +
'<span class="hvt-notif-detail">' + esc(n.detail || n.label || "") + "</span>" +
'<span class="hvt-notif-date">' + esc(n.date) + "</span></a>";
}).join("");
}).catch(function () {});
}
function markRead() {
postJSON("/api/notifications/read").then(function () {
var c = document.getElementById("hvtBellCount"); if (c) c.hidden = true;
}).catch(function () {});
}
// ---- styles (scoped, theme-matched) ----
function injectStyles() {
if (document.getElementById("hvt-auth-style")) return;
var s = document.createElement("style");
s.id = "hvt-auth-style";
s.textContent =
".hvt-auth-slot{display:inline-flex;align-items:center}.hvt-auth-slot:empty{display:none}" +
"#hvt-compare-tray{position:fixed;bottom:18px;right:18px;z-index:1200;background:var(--accent,#26405e);color:#fff;border:1px solid var(--accent,#26405e);padding:10px 16px;font-family:var(--font-mono,ui-monospace,Menlo,monospace);font-size:13px;box-shadow:0 10px 30px rgba(34,28,22,.25);text-decoration:none}" +
"#hvt-compare-tray[hidden]{display:none}#hvt-compare-tray:hover{filter:brightness(1.08);text-decoration:none}#hvt-compare-tray strong{font-weight:700}" +
".hvt-auth{position:relative;display:inline-flex;align-items:center;gap:8px;font-family:var(--font-mono,ui-monospace,Menlo,monospace);font-size:12px}" +
".hvt-auth-btn,.hvt-bell{display:inline-flex;align-items:center;gap:6px;cursor:pointer;background:#fff;border:1px solid var(--border,#d5cbbc);color:var(--text,#1f1b17);padding:5px 10px;border-radius:0;font:inherit}" +
".hvt-auth-btn:hover,.hvt-bell:hover{border-color:var(--accent-warm,#c67c6d);color:var(--accent-warm,#c67c6d)}" +
".hvt-auth-avatar{width:18px;height:18px;border-radius:50%;object-fit:cover}" +
".hvt-bell{position:relative;padding:5px 8px}" +
".hvt-bell-count{position:absolute;top:-6px;right:-6px;background:var(--accent-warm,#c67c6d);color:#fff;border-radius:9px;padding:0 5px;font-size:10px;line-height:16px;min-width:16px;text-align:center}" +
".hvt-auth-pop{position:absolute;top:calc(100% + 6px);right:0;min-width:220px;background:#fff;border:1px solid var(--border,#d5cbbc);box-shadow:0 18px 50px rgba(34,28,22,.16);z-index:1100;display:flex;flex-direction:column}" +
".hvt-auth-pop[hidden]{display:none}" +
".hvt-auth-item{display:block;padding:10px 12px;color:var(--text,#1f1b17);text-decoration:none;border:0;background:none;text-align:left;cursor:pointer;font:inherit;border-bottom:1px solid var(--border,#eee)}" +
".hvt-auth-item:last-child{border-bottom:0}.hvt-auth-item:hover{background:#f4f1eb;color:var(--accent-warm,#a34e30)}" +
".hvt-auth-muted{color:#6f665d;cursor:default}" +
".hvt-notif{min-width:320px;max-width:380px}" +
".hvt-notif-head{padding:10px 12px;border-bottom:1px solid var(--border,#eee);color:#6f665d;text-transform:uppercase;letter-spacing:.06em;font-size:10px}" +
".hvt-notif-list{max-height:340px;overflow:auto}" +
".hvt-notif-empty{padding:14px 12px;color:#6f665d}" +
".hvt-notif-item{display:grid;gap:2px;padding:10px 12px;border-bottom:1px solid var(--border,#eee);text-decoration:none;color:var(--text,#1f1b17)}" +
".hvt-notif-item:hover{background:#f4f1eb}.hvt-notif-item.is-unread{background:#fbf6ee}" +
".hvt-notif-name{font-weight:700}.hvt-notif-detail{color:#4a443d}.hvt-notif-date{color:#6f665d;font-size:10px}" +
".hvt-track-nudge{margin:10px 0 0;font-size:13px;color:var(--muted,#6f665d)}.hvt-track-nudge a{color:var(--accent,#26405e);text-decoration:underline}" +
// Dark mode (site.css tokens): the light values above are literal, so
// override only under a dark system setting and leave light untouched.
"@media (prefers-color-scheme:dark){" +
".hvt-auth-btn,.hvt-bell,.hvt-auth-pop{background:var(--card)}" +
".hvt-auth-item:hover,.hvt-notif-item:hover{background:var(--surface)}.hvt-notif-item.is-unread{background:var(--row-hover)}" +
".hvt-auth-muted,.hvt-notif-head,.hvt-notif-empty,.hvt-notif-date{color:var(--muted)}.hvt-notif-detail{color:var(--text)}" +
"#hvt-compare-tray,.hvt-bell-count{color:var(--on-accent)}" +
"}" +
"";
document.head.appendChild(s);
}
})();