|
| 1 | +// Solid notifications (legacy "solid-0.1" protocol) as a #206 loader plugin. |
| 2 | +// |
| 3 | +// plugins: [{ module: 'notifications/plugin.js', prefix: '/.notifications', |
| 4 | +// config: { podsRoot: './data', baseUrl: 'http://localhost:3000' } }] |
| 5 | +// |
| 6 | +// Out-of-tree port of JSS src/notifications/ (AGPL-3.0-only). This is the |
| 7 | +// deliberate seam-forcer of the experiment: core's version has two change |
| 8 | +// sources (in-process emitChange() calls from the LDP handlers, plus a |
| 9 | +// recursive fs watcher) and injects Updates-Via discovery headers into |
| 10 | +// every response. A plugin gets none of that — see README "Findings" for |
| 11 | +// the three seams this port demonstrates the need for (api.events, |
| 12 | +// api.serverInfo, response-header hooks). What it CAN do honestly: |
| 13 | +// |
| 14 | +// - watch the pod root via fs.watch (the operator passes the path in — |
| 15 | +// the plugin api has no way to learn it); |
| 16 | +// - speak the exact solid-0.1 protocol (protocol/sub/ack/err/pub, with |
| 17 | +// ancestor-container fan-out) so SolidOS clients work unchanged; |
| 18 | +// - authorize subscriptions WITHOUT internal WAC access by loopback: |
| 19 | +// a HEAD request to the resource carrying the subscriber's own |
| 20 | +// Authorization header — if the server would serve it, they may hear |
| 21 | +// about it. Slower than core's in-process checkAccess, but it can |
| 22 | +// never disagree with the server's real policy. |
| 23 | + |
| 24 | +import { watch } from 'node:fs'; |
| 25 | + |
| 26 | +const MAX_SUBSCRIPTIONS_PER_CONNECTION = 100; |
| 27 | +const MAX_URL_LENGTH = 2048; |
| 28 | +const DEBOUNCE_MS = 100; |
| 29 | + |
| 30 | +export async function activate(api) { |
| 31 | + const wsPath = api.prefix || '/.notifications'; |
| 32 | + const podsRoot = api.config.podsRoot; |
| 33 | + const baseUrl = (api.config.baseUrl || '').replace(/\/$/, ''); |
| 34 | + if (!podsRoot || !baseUrl) { |
| 35 | + throw new Error( |
| 36 | + 'notifications plugin requires config.podsRoot and config.baseUrl — ' + |
| 37 | + 'the plugin api exposes neither the data root nor the public origin (see README findings)', |
| 38 | + ); |
| 39 | + } |
| 40 | + const loopback = api.config.loopbackUrl || baseUrl; // where WE can reach the server |
| 41 | + |
| 42 | + const subscriptions = new Map(); // socket -> Set<url> |
| 43 | + const subscribers = new Map(); // url -> Set<socket> |
| 44 | + |
| 45 | + function subscribe(socket, url) { |
| 46 | + subscriptions.get(socket)?.add(url); |
| 47 | + if (!subscribers.has(url)) subscribers.set(url, new Set()); |
| 48 | + subscribers.get(url).add(socket); |
| 49 | + } |
| 50 | + |
| 51 | + function unsubscribe(socket, url) { |
| 52 | + subscriptions.get(socket)?.delete(url); |
| 53 | + subscribers.get(url)?.delete(socket); |
| 54 | + if (subscribers.get(url)?.size === 0) subscribers.delete(url); |
| 55 | + } |
| 56 | + |
| 57 | + function cleanup(socket) { |
| 58 | + for (const url of subscriptions.get(socket) ?? []) subscribers.get(url)?.delete(socket); |
| 59 | + subscriptions.delete(socket); |
| 60 | + } |
| 61 | + |
| 62 | + function notifySubscribers(url) { |
| 63 | + for (const socket of subscribers.get(url) ?? []) { |
| 64 | + try { |
| 65 | + socket.send(`pub ${url}`); |
| 66 | + } catch { /* closing; cleaned up on close */ } |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + function getParentContainer(url) { |
| 71 | + try { |
| 72 | + const u = new URL(url); |
| 73 | + if (u.pathname === '/' || u.pathname === '') return null; |
| 74 | + const trimmed = u.pathname.endsWith('/') ? u.pathname.slice(0, -1) : u.pathname; |
| 75 | + const parent = trimmed.slice(0, trimmed.lastIndexOf('/') + 1); |
| 76 | + return u.origin + parent; |
| 77 | + } catch { |
| 78 | + return null; |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + /** pub the resource and every ancestor container (solid-0.1 semantics). */ |
| 83 | + function broadcast(url) { |
| 84 | + notifySubscribers(url); |
| 85 | + const originRoot = new URL(url).origin + '/'; |
| 86 | + let current = url; |
| 87 | + let container = getParentContainer(current); |
| 88 | + while (container && container !== current && container.length >= originRoot.length) { |
| 89 | + notifySubscribers(container); |
| 90 | + current = container; |
| 91 | + container = getParentContainer(current); |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + /** |
| 96 | + * May this subscriber hear about this URL? No internal WAC access from a |
| 97 | + * plugin, so ask the server itself: HEAD with the subscriber's own |
| 98 | + * credentials. 2xx/3xx — including 304 — means readable. |
| 99 | + */ |
| 100 | + async function canSubscribe(url, authorization) { |
| 101 | + let parsed; |
| 102 | + try { |
| 103 | + parsed = new URL(url); |
| 104 | + } catch { |
| 105 | + return false; |
| 106 | + } |
| 107 | + if (parsed.origin !== new URL(baseUrl).origin) return false; // no proxy-probing other hosts |
| 108 | + try { |
| 109 | + const res = await fetch(new URL(parsed.pathname + parsed.search, loopback), { |
| 110 | + method: 'HEAD', |
| 111 | + redirect: 'manual', |
| 112 | + headers: authorization ? { authorization } : {}, |
| 113 | + }); |
| 114 | + // 404 subscribes fine (watching a resource that doesn't exist yet is |
| 115 | + // legitimate — core behaves the same for non-existent paths). |
| 116 | + return res.status < 400 || res.status === 404; |
| 117 | + } catch { |
| 118 | + return false; |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + // ------------------------------------------------------------ watcher |
| 123 | + const debounceMap = new Map(); |
| 124 | + const watcher = watch(podsRoot, { recursive: true }, (eventType, filename) => { |
| 125 | + if (!filename) return; |
| 126 | + const base = filename.split('/').pop(); |
| 127 | + if (base.startsWith('.') || filename.endsWith('~') || filename.endsWith('.swp')) return; |
| 128 | + if (filename.startsWith('.')) return; // .idp, .plugins, dot-guarded trees |
| 129 | + const now = Date.now(); |
| 130 | + if (now - (debounceMap.get(filename) ?? 0) < DEBOUNCE_MS) return; |
| 131 | + debounceMap.set(filename, now); |
| 132 | + if (debounceMap.size > 1000) { |
| 133 | + for (const [key, time] of debounceMap) { |
| 134 | + if (now - time > 5000) debounceMap.delete(key); |
| 135 | + } |
| 136 | + } |
| 137 | + broadcast(baseUrl + '/' + filename.replace(/\\/g, '/')); |
| 138 | + }); |
| 139 | + watcher.on('error', (err) => api.log.error(`notifications: watcher error: ${err.message}`)); |
| 140 | + |
| 141 | + // ------------------------------------------------------------ websocket |
| 142 | + await api.ws.route(wsPath, (socket, request) => { |
| 143 | + const authorization = request.headers?.authorization ?? null; |
| 144 | + socket.send('protocol solid-0.1'); |
| 145 | + subscriptions.set(socket, new Set()); |
| 146 | + |
| 147 | + socket.on('message', async (message) => { |
| 148 | + const msg = String(message).trim(); |
| 149 | + if (msg.startsWith('sub ')) { |
| 150 | + const url = msg.slice(4).trim(); |
| 151 | + if (!url) return; |
| 152 | + if (url.length > MAX_URL_LENGTH) return socket.send('error: URL too long'); |
| 153 | + if ((subscriptions.get(socket)?.size ?? 0) >= MAX_SUBSCRIPTIONS_PER_CONNECTION) { |
| 154 | + return socket.send('error: Subscription limit exceeded'); |
| 155 | + } |
| 156 | + if (!(await canSubscribe(url, authorization))) return socket.send(`err ${url} forbidden`); |
| 157 | + subscribe(socket, url); |
| 158 | + socket.send(`ack ${url}`); |
| 159 | + } else if (msg.startsWith('unsub ')) { |
| 160 | + const url = msg.slice(6).trim(); |
| 161 | + if (url) unsubscribe(socket, url); |
| 162 | + } |
| 163 | + }); |
| 164 | + socket.on('close', () => cleanup(socket)); |
| 165 | + socket.on('error', () => cleanup(socket)); |
| 166 | + }); |
| 167 | + |
| 168 | + // Status endpoint (core keeps this at /.well-known/solid/notifications — |
| 169 | + // outside any single prefix a plugin can own; ours lives under the mount). |
| 170 | + api.fastify.get(wsPath + '/status', async () => ({ |
| 171 | + connections: subscriptions.size, |
| 172 | + subscriptions: [...subscriptions.values()].reduce((n, s) => n + s.size, 0), |
| 173 | + protocol: 'solid-0.1', |
| 174 | + })); |
| 175 | + |
| 176 | + api.log.info(`notifications: solid-0.1 websocket at ${wsPath}, watching ${podsRoot}`); |
| 177 | + return { |
| 178 | + deactivate() { |
| 179 | + watcher.close(); |
| 180 | + for (const socket of subscriptions.keys()) { |
| 181 | + try { socket.close(); } catch { /* already gone */ } |
| 182 | + } |
| 183 | + }, |
| 184 | + }; |
| 185 | +} |
0 commit comments