CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
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 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 | /**
* Block G1 — PWA (progressive web app) support.
*
* GET /manifest.webmanifest — app manifest (install prompt)
* GET /sw.js — service worker (cache-first for static, network-first for HTML)
* GET /icon.svg — monochrome logo used by the manifest
*
* The service worker deliberately keeps the cache small (static CSS-in-JS is
* inlined so there's nothing to cache beyond the manifest + icon). HTML pages
* fall through to the network; cached copies only serve offline fallback.
*
* Adding `<link rel="manifest" href="/manifest.webmanifest">` + a tiny SW
* registration snippet to `Layout` turns any repo page into an installable
* PWA on Chrome/Safari.
*/
import { Hono } from "hono";
import type { AuthEnv } from "../middleware/auth";
import { requireAuth } from "../middleware/auth";
import {
getVapidPublicKey,
sendPushToUser,
subscribeUser,
unsubscribeUser,
} from "../lib/push";
const pwa = new Hono<AuthEnv>();
export const MANIFEST = {
name: "Gluecron",
short_name: "Gluecron",
description: "AI-native code intelligence + git hosting",
start_url: "/",
scope: "/",
display: "standalone",
background_color: "#0d1117",
theme_color: "#0d1117",
icons: [
{
src: "/icon.svg",
sizes: "any",
type: "image/svg+xml",
purpose: "any maskable",
},
],
categories: ["developer", "productivity"],
} as const;
pwa.get("/manifest.webmanifest", (c) => {
c.header("content-type", "application/manifest+json");
c.header("cache-control", "public, max-age=3600");
return c.body(JSON.stringify(MANIFEST));
});
const ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
<rect width="128" height="128" rx="24" fill="#0d1117"/>
<g fill="#58a6ff" font-family="monospace" font-size="58" font-weight="700" text-anchor="middle">
<text x="64" y="82">gc</text>
</g>
<circle cx="28" cy="28" r="5" fill="#3fb950"/>
</svg>`;
pwa.get("/icon.svg", (c) => {
c.header("content-type", "image/svg+xml");
c.header("cache-control", "public, max-age=86400, immutable");
return c.body(ICON_SVG);
});
/**
* Bare-bones service worker — v4 NUKE EDITION.
*
* After repeated reports of stale HTML being served from old cache versions,
* this SW does ONE job: unregister itself and purge every cache. Browsers
* that previously installed v1/v2/v3 will load this v4, see the unregister
* call, and stop intercepting fetches. From now on EVERY page load goes
* straight to the network — no SW, no cache, instant fresh content on push.
*
* Once we trust the auto-deploy pipeline + want offline support back, ship
* a real SW with conservative network-first behaviour. Until then: instant
* deploys win.
*/
export const SERVICE_WORKER_SRC = `// gluecron service worker — v4 (self-nuke)
self.addEventListener('install', () => self.skipWaiting());
self.addEventListener('activate', (e) => {
e.waitUntil((async () => {
// Purge every cache from any prior SW version
const keys = await caches.keys();
await Promise.all(keys.map((k) => caches.delete(k)));
// Tell every client we're done so they reload onto clean network state
const clients = await self.clients.matchAll({ type: 'window' });
for (const c of clients) c.navigate(c.url).catch(() => {});
// Then unregister this SW so future loads skip the SW layer entirely
await self.registration.unregister();
})());
});
// No fetch handler — every request goes straight to the network.
`;
pwa.get("/sw.js", (c) => {
c.header("content-type", "application/javascript");
// No-cache: browser must check on every page load. Critical for the v4
// self-nuke SW to actually reach all returning visitors.
c.header("cache-control", "no-cache, no-store, must-revalidate");
c.header("pragma", "no-cache");
// Service-Worker-Allowed required for root-scope SW served from root
c.header("service-worker-allowed", "/");
return c.body(SERVICE_WORKER_SRC);
});
/**
* Inline script registering the SW. Loaded once at the bottom of every page.
* Kept tiny so we don't bloat TTI.
*/
export const PWA_REGISTER_SNIPPET = `
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/sw.js').catch(function() {});
});
}
`.trim();
// ---------------------------------------------------------------------------
// Block M2 — additive routes + a SECOND service worker dedicated to push +
// offline support. The original `/sw.js` keeps its v4 self-nuke behaviour
// (locked) so the install/activate/unregister contract is preserved. The new
// SW lives at `/sw-push.js` and is registered separately by the install
// banner / settings page when the user opts into push.
// ---------------------------------------------------------------------------
/**
* Push + offline service worker. Strictly additive to the v4 self-nuke SW.
* Handles three things:
* 1. `push` event → display a notification (title/body/url/tag).
* 2. `notificationclick` → focus an existing tab on `url` or open a new one.
* 3. `fetch` event → serve `/offline.html` as the fallback when the
* network fails on an HTML navigation. Non-HTML fetches passthrough.
*
* The cache name is unique so we don't collide with anything `/sw.js`
* historically touched.
*/
export const PUSH_SERVICE_WORKER_SRC = `// gluecron push + offline service worker (Block M2)
const CACHE = 'gluecron-offline-v1';
const OFFLINE_URL = '/offline.html';
self.addEventListener('install', (event) => {
event.waitUntil((async () => {
const cache = await caches.open(CACHE);
try { await cache.add(new Request(OFFLINE_URL, { cache: 'reload' })); } catch (_) {}
self.skipWaiting();
})());
});
self.addEventListener('activate', (event) => {
event.waitUntil((async () => {
// Drop any cache that isn't our current one.
const keys = await caches.keys();
await Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)));
await self.clients.claim();
})());
});
self.addEventListener('push', (event) => {
let data = { title: 'Gluecron', body: '', url: '/', tag: 'gluecron', icon: '/icon.svg' };
if (event.data) {
try { data = Object.assign(data, event.data.json()); }
catch (_) { try { data.body = event.data.text(); } catch (_) {} }
}
event.waitUntil(self.registration.showNotification(data.title, {
body: data.body,
icon: data.icon,
tag: data.tag,
data: { url: data.url },
}));
});
self.addEventListener('notificationclick', (event) => {
event.notification.close();
const target = (event.notification.data && event.notification.data.url) || '/';
event.waitUntil((async () => {
const all = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
for (const c of all) {
try {
const u = new URL(c.url);
if (u.pathname === target || c.url === target) {
await c.focus();
return;
}
} catch (_) {}
}
await self.clients.openWindow(target);
})());
});
self.addEventListener('fetch', (event) => {
const req = event.request;
if (req.method !== 'GET') return;
const accept = req.headers.get('accept') || '';
// Only intervene on top-level HTML navigations. Everything else (CSS,
// images, API, /api/*, /.git/*, login/logout) passes straight through.
if (req.mode !== 'navigate' && !accept.includes('text/html')) return;
event.respondWith((async () => {
try {
return await fetch(req);
} catch (_) {
const cache = await caches.open(CACHE);
const cached = await cache.match(OFFLINE_URL);
if (cached) return cached;
return new Response('Offline', { status: 503, headers: { 'content-type': 'text/plain' } });
}
})());
});
`;
pwa.get("/sw-push.js", (c) => {
c.header("content-type", "application/javascript");
// Same caching policy as /sw.js so updates propagate immediately.
c.header("cache-control", "no-cache, no-store, must-revalidate");
c.header("pragma", "no-cache");
c.header("service-worker-allowed", "/");
return c.body(PUSH_SERVICE_WORKER_SRC);
});
/** Offline fallback — minimal, theme-consistent. */
export const OFFLINE_HTML = `<!doctype html>
<html lang="en" data-theme="dark">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Offline — gluecron</title>
<style>
:root { --bg:#0d1117; --fg:#c9d1d9; --muted:#8b949e; --accent:#58a6ff; --border:#30363d; }
html, body { margin:0; padding:0; background:var(--bg); color:var(--fg);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }
main { max-width: 480px; margin: 12vh auto 0; padding: 24px; text-align:center; }
h1 { font-size: 22px; margin: 0 0 12px; }
p { color: var(--muted); line-height: 1.5; }
a.btn {
display:inline-block; margin-top:18px; padding:10px 18px;
background:transparent; border:1px solid var(--border); border-radius:6px;
color:var(--accent); text-decoration:none;
}
.pulse {
width:10px; height:10px; border-radius:50%;
background:#f85149; display:inline-block; margin-right:8px;
box-shadow:0 0 12px rgba(248,81,73,0.6);
}
</style>
</head>
<body>
<main>
<h1><span class="pulse"></span>You're offline</h1>
<p>We couldn't reach gluecron. Your last-known dashboard is still in cache — reconnect to refresh it.</p>
<a class="btn" href="/dashboard">Retry</a>
</main>
</body>
</html>
`;
pwa.get("/offline.html", (c) => {
c.header("content-type", "text/html; charset=utf-8");
c.header("cache-control", "public, max-age=300");
return c.body(OFFLINE_HTML);
});
// --- API: VAPID public key --------------------------------------------------
pwa.get("/pwa/vapid-public-key", async (c) => {
try {
const key = await getVapidPublicKey();
return c.json({ key });
} catch (err) {
console.error("[pwa] vapid public key failed:", err);
return c.json({ error: "vapid_unavailable" }, 500);
}
});
// --- API: subscribe ---------------------------------------------------------
pwa.post("/pwa/subscribe", requireAuth, async (c) => {
const user = c.get("user")!;
let body: any;
try {
body = await c.req.json();
} catch {
return c.json({ error: "invalid_json" }, 400);
}
const endpoint = typeof body?.endpoint === "string" ? body.endpoint : "";
const p256dh =
typeof body?.keys?.p256dh === "string" ? body.keys.p256dh : "";
const auth = typeof body?.keys?.auth === "string" ? body.keys.auth : "";
if (!endpoint || !p256dh || !auth) {
return c.json({ error: "invalid_subscription" }, 400);
}
const ua = c.req.header("user-agent") ?? null;
try {
await subscribeUser(
user.id,
{ endpoint, keys: { p256dh, auth } },
ua ?? undefined
);
} catch (_) {
return c.json({ error: "subscribe_failed" }, 500);
}
return c.json({ ok: true }, 201);
});
// --- API: unsubscribe -------------------------------------------------------
pwa.post("/pwa/unsubscribe", requireAuth, async (c) => {
const user = c.get("user")!;
let body: any;
try {
body = await c.req.json();
} catch {
return c.json({ error: "invalid_json" }, 400);
}
const endpoint = typeof body?.endpoint === "string" ? body.endpoint : "";
if (!endpoint) return c.json({ error: "missing_endpoint" }, 400);
await unsubscribeUser(user.id, endpoint);
return c.body(null, 204);
});
// --- API: send a test push to the calling user ------------------------------
pwa.post("/pwa/test", requireAuth, async (c) => {
const user = c.get("user")!;
const result = await sendPushToUser(user.id, {
title: "Gluecron test notification",
body: "If you can read this, push delivery is working on this device.",
url: "/notifications",
tag: "gluecron-test",
});
return c.json(result);
});
export default pwa;
|