@soffits/dsh-notify-inbox 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@soffits/dsh-notify-inbox",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "A notification inbox for DeepSeek Harness: each person sees their own notifications with read and unread, gets Web Push on their phone or browser, and can act on them.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Sakina",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/soffits/dsh-notify-inbox.git"
11
+ },
12
+ "homepage": "https://github.com/soffits/dsh-notify-inbox#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/soffits/dsh-notify-inbox/issues"
15
+ },
16
+ "keywords": ["dsh", "dsh-plugin", "deepseek-harness", "notifications", "inbox", "web-push", "pwa"],
17
+ "main": "./index.js",
18
+ "exports": {
19
+ ".": "./index.js",
20
+ "./client": "./client.js",
21
+ "./client.actions.js": "./client.actions.js",
22
+ "./locale/*.json": "./locale/*.json",
23
+ "./icon": "./icon.svg",
24
+ "./package.json": "./package.json"
25
+ },
26
+ "files": ["src", "client.js", "client.actions.js", "index.js", "cordis.patch.yml", "locale/*.json", "icon.svg", "README.md", "CHANGELOG.md", "LICENSE"],
27
+ "dsh": {
28
+ "bundle": {
29
+ "patch": "./cordis.patch.yml"
30
+ },
31
+ "client": {
32
+ "platform": "web",
33
+ "immediately": true,
34
+ "inject": [
35
+ "@deepseek-ai/dsh-client-locale",
36
+ "@deepseek-ai/dsh-client-ui-layout",
37
+ "@deepseek-ai/dsh-client-ui-sidebar"
38
+ ]
39
+ }
40
+ },
41
+ "scripts": {
42
+ "check": "for f in index.js client.js client.actions.js src/*.js test/*.js; do node --check \"$f\" || exit 1; done",
43
+ "test": "node --test test/*.test.js"
44
+ },
45
+ "dependencies": {
46
+ "@deepseek-ai/schemastery": "3.18.5"
47
+ },
48
+ "engines": {
49
+ "node": ">=22",
50
+ "dsh": ">=0.2.1-rc.2 <0.3.0"
51
+ }
52
+ }
package/src/access.js ADDED
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Who may see which board.
3
+ *
4
+ * The caller comes from a `requestIdentity` service, if one is installed: any
5
+ * plugin that verifies the person behind an `/api` request can provide it
6
+ * (`current()` returns `{ id, ... }` or null). The verified user id maps to a
7
+ * person id through the configured mapping, and a board lists the person ids
8
+ * that may see it in `viewers`.
9
+ *
10
+ * Two modes:
11
+ * - people: a mapping is configured. A request needs a verified identity that
12
+ * maps to a person, and sees only boards that list that person. Without an
13
+ * identity provider nothing is shown.
14
+ * - owner: no mapping. Everyone DSH lets in is its owner and sees every board,
15
+ * which is what a single-person DSH wants.
16
+ */
17
+ import { readFile, stat } from 'node:fs/promises'
18
+
19
+ /** Person ids compare without regard to case or surrounding space. */
20
+ export function personKey(value) {
21
+ return typeof value === 'string' ? value.trim().normalize('NFKC').toLowerCase() : ''
22
+ }
23
+
24
+ /** Expand a leading `~/` to the home folder. */
25
+ export function expandHome(path, home) {
26
+ return typeof path === 'string' && (path === '~' || path.startsWith('~/')) ? home + path.slice(1) : path
27
+ }
28
+
29
+ /**
30
+ * The configured user id → person id mapping, re-read from `peopleFile`
31
+ * whenever that file changes. A file that can't be read or parsed maps nobody
32
+ * (and is reported once per change), so a broken file never widens access.
33
+ */
34
+ export function createPeople({ people = {}, peopleFile = '', peopleKey = '' }, { warn = () => {} } = {}) {
35
+ const inline = Object.entries(people)
36
+ const enabled = inline.length > 0 || peopleFile !== ''
37
+ let cached = { tag: undefined, entries: [] }
38
+
39
+ async function fromFile() {
40
+ if (peopleFile === '') return []
41
+ let tag
42
+ try {
43
+ const info = await stat(peopleFile)
44
+ tag = `${info.size}:${info.mtimeMs}`
45
+ } catch (error) {
46
+ tag = `error:${error.code}`
47
+ }
48
+ if (tag === cached.tag) return cached.entries
49
+ let entries = []
50
+ try {
51
+ let value = JSON.parse(await readFile(peopleFile, 'utf8'))
52
+ if (peopleKey !== '') value = value?.[peopleKey]
53
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error(peopleKey ? `no object at key ${peopleKey}` : 'not a JSON object')
54
+ entries = Object.entries(value).filter(([, person]) => typeof person === 'string')
55
+ } catch (error) {
56
+ warn(`people file ${peopleFile}: ${error.message}; nobody is mapped from it`)
57
+ }
58
+ cached = { tag, entries }
59
+ return entries
60
+ }
61
+
62
+ return {
63
+ enabled,
64
+ /** The person id for a verified user id, or undefined. Inline entries win over the file. */
65
+ async personFor(userId) {
66
+ if (typeof userId !== 'string' || userId === '') return undefined
67
+ const map = new Map([...(await fromFile()), ...inline])
68
+ const person = map.get(userId)
69
+ return person === undefined ? undefined : personKey(person)
70
+ },
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Decide who the current request is. Returns `{ mode: 'owner' }`,
76
+ * `{ mode: 'people', person }` (person may be undefined: sees nothing) or
77
+ * `{ mode: 'people', unavailable: true }` when a mapping is configured but no
78
+ * identity provider is installed.
79
+ */
80
+ export async function viewerOf(people, identityService) {
81
+ if (!people.enabled) return { mode: 'owner' }
82
+ if (identityService === undefined || typeof identityService?.current !== 'function') return { mode: 'people', unavailable: true }
83
+ const identity = identityService.current()
84
+ return { mode: 'people', person: await people.personFor(identity?.id) }
85
+ }
86
+
87
+ /** Whether a viewer may see a board (its board.json already validated). */
88
+ export function maySee(viewer, board) {
89
+ if (viewer.mode === 'owner') return true
90
+ if (viewer.person === undefined || board === undefined) return false
91
+ return (board.viewers ?? []).some(person => personKey(person) === viewer.person)
92
+ }
package/src/actions.js ADDED
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Presses on a record's buttons.
3
+ *
4
+ * `chat` and `link` act in the page. `done`, `snooze` and `event` become an
5
+ * action event: appended to `<dataDir>/<person>/actions.jsonl` (the log this
6
+ * plugin owns) and published on the channel `ui.action.<kind>` through an
7
+ * event service when one is installed (dsh-cron-jobs provides `cronJobs`).
8
+ * Whatever owns the notification reacts and writes a `handled` line into the
9
+ * inbox; until then the page shows the press as pending.
10
+ */
11
+ import { appendFile, mkdir, readFile } from 'node:fs/promises'
12
+ import { randomBytes } from 'node:crypto'
13
+ import { join } from 'node:path'
14
+
15
+ export const EMITTING = ['done', 'snooze', 'event']
16
+ const ACTIONS_LOG = 'actions.jsonl'
17
+
18
+ /** The event a press becomes (same shape as the practice's actions spec). */
19
+ export function actionEvent(action, { person, record, payload = {}, at = new Date(), press = randomBytes(6).toString('hex') }) {
20
+ return {
21
+ action: action.kind,
22
+ id: action.id,
23
+ payload: { ...(action.payload ?? {}), ...payload },
24
+ person,
25
+ at: at.toISOString().replace(/\.\d{3}Z$/, 'Z'),
26
+ source: { plugin: 'notify-inbox', record: record.id, key: record.key || undefined, domain: record.domain || undefined },
27
+ press,
28
+ }
29
+ }
30
+
31
+ /** What a page may add to a press: only a snooze time. */
32
+ export function pressPayload(kind, value) {
33
+ if (kind !== 'snooze' || typeof value?.until !== 'string') return {}
34
+ const time = Date.parse(value.until)
35
+ return Number.isNaN(time) ? {} : { until: value.until }
36
+ }
37
+
38
+ /**
39
+ * @param {object} options
40
+ * @param {string} options.dataDir
41
+ * @param {() => object | undefined} options.events - the event service right now (`cronJobs`), if any
42
+ * @param {(message: string) => void} options.warn
43
+ */
44
+ export function createActions({ dataDir, events, warn }) {
45
+ function publish(event) {
46
+ const controller = events()?.controller?.()
47
+ if (controller === undefined) return { published: false }
48
+ try {
49
+ const result = controller.emit({ channel: `ui.action.${event.action}`, data: event, key: event.press, source: 'notify-inbox' })
50
+ return { published: true, matched: result?.matched?.length ?? 0 }
51
+ } catch (error) {
52
+ warn(`action event not published: ${error.message}`)
53
+ return { published: false }
54
+ }
55
+ }
56
+
57
+ async function press(person, record, action, extra) {
58
+ if (!EMITTING.includes(action.kind)) throw new Error('This button acts in the page.')
59
+ const event = actionEvent(action, { person, record, payload: pressPayload(action.kind, extra) })
60
+ await mkdir(join(dataDir, person), { recursive: true })
61
+ await appendFile(join(dataDir, person, ACTIONS_LOG), `${JSON.stringify(event)}\n`, { mode: 0o600 })
62
+ return { event, ...publish(event) }
63
+ }
64
+
65
+ /** This person's presses by record id: `[{ press, action, at }]`. */
66
+ async function presses(person) {
67
+ let lines
68
+ try {
69
+ lines = (await readFile(join(dataDir, person, ACTIONS_LOG), 'utf8')).split('\n')
70
+ } catch {
71
+ return new Map()
72
+ }
73
+ const out = new Map()
74
+ for (const line of lines) {
75
+ if (line.trim() === '') continue
76
+ try {
77
+ const event = JSON.parse(line)
78
+ const id = event?.source?.record
79
+ if (typeof id !== 'string') continue
80
+ out.set(id, [...(out.get(id) ?? []), { press: event.press, action: event.action, at: event.at, until: event.payload?.until }])
81
+ } catch {
82
+ // A torn line is skipped.
83
+ }
84
+ }
85
+ return out
86
+ }
87
+
88
+ return { press, presses }
89
+ }
package/src/push.js ADDED
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Web Push to each person's subscribed browsers.
3
+ *
4
+ * <dataDir>/.push/subscriptions.json [{ endpoint, keys, person, label, createdAt }]
5
+ * <dataDir>/.push/cursor.json { <person>: { ino, offset } }: how far each inbox was pushed
6
+ * vapidFile (config) { publicKey, privateKey }, made on first start, mode 600
7
+ *
8
+ * A subscription belongs to the person who made it (`person`), or to the
9
+ * owner of a single-owner DSH (`person: null`), who gets every person's
10
+ * records. A fresh install starts its cursor at the end of each inbox, so it
11
+ * never pushes old records; after a restart it pushes what arrived meanwhile.
12
+ */
13
+ import { chmod, mkdir, readFile, rename, stat, writeFile } from 'node:fs/promises'
14
+ import { dirname, join } from 'node:path'
15
+ import { isIP } from 'node:net'
16
+ import { parseLines, readFrom } from './store.js'
17
+ import { generateVapidKeys, loadVapidKeys, sendPush } from './webpush.js'
18
+
19
+ const MAX_ENDPOINT = 2048
20
+ const MAX_SUBSCRIPTIONS = 50
21
+ const BODY_LIMIT = 280
22
+
23
+ async function readJson(path, fallback) {
24
+ try {
25
+ return JSON.parse(await readFile(path, 'utf8'))
26
+ } catch {
27
+ return fallback
28
+ }
29
+ }
30
+
31
+ async function writeJson(path, value, mode = 0o600) {
32
+ await mkdir(dirname(path), { recursive: true })
33
+ const tmp = `${path}.${process.pid}.${Date.now()}.tmp`
34
+ await writeFile(tmp, JSON.stringify(value, null, 1), { mode })
35
+ await rename(tmp, path)
36
+ }
37
+
38
+ /** The stored VAPID keys, made on first use. The private key never leaves this function's result. */
39
+ export async function vapidKeys(path) {
40
+ let stored = await readJson(path, undefined)
41
+ if (stored === undefined) {
42
+ stored = generateVapidKeys()
43
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 })
44
+ await writeFile(path, JSON.stringify(stored), { mode: 0o600, flag: 'wx' }).catch(async error => {
45
+ if (error.code !== 'EEXIST') throw error
46
+ stored = JSON.parse(await readFile(path, 'utf8'))
47
+ })
48
+ }
49
+ await chmod(path, 0o600)
50
+ return loadVapidKeys(stored)
51
+ }
52
+
53
+ function privateHost(hostname) {
54
+ const host = hostname.replace(/^\[|\]$/g, '').toLowerCase()
55
+ if (host === 'localhost' || host.endsWith('.localhost') || host.endsWith('.local') || host.endsWith('.internal')) return true
56
+ const kind = isIP(host)
57
+ if (kind === 4) {
58
+ const [a, b] = host.split('.').map(Number)
59
+ return a === 10 || a === 127 || a === 0 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127)
60
+ }
61
+ if (kind === 6) return host === '::1' || host === '::' || /^f[cd]/.test(host) || /^fe[89ab]/.test(host) || host.startsWith('::ffff:')
62
+ return false
63
+ }
64
+
65
+ /** A browser's subscription as sent by the page, checked, or an Error saying why not. */
66
+ export function checkSubscription(value) {
67
+ const endpoint = value?.endpoint
68
+ if (typeof endpoint !== 'string' || endpoint.length > MAX_ENDPOINT) return new Error('No endpoint.')
69
+ let url
70
+ try {
71
+ url = new URL(endpoint)
72
+ } catch {
73
+ return new Error('The endpoint is not a URL.')
74
+ }
75
+ if (url.protocol !== 'https:' || url.username !== '' || url.password !== '' || privateHost(url.hostname)) {
76
+ return new Error('The endpoint must be a public HTTPS address.')
77
+ }
78
+ const p256dh = value?.keys?.p256dh
79
+ const auth = value?.keys?.auth
80
+ if (typeof p256dh !== 'string' || typeof auth !== 'string' || p256dh.length > 200 || auth.length > 100) return new Error('Missing keys.')
81
+ return { endpoint: url.href, keys: { p256dh, auth } }
82
+ }
83
+
84
+ /** The notification a record becomes: what the push service carries (encrypted) and the service worker shows. */
85
+ export function payloadOf(record) {
86
+ const title = record.title || record.spoken.slice(0, 60) || 'Notification'
87
+ const body = record.spoken && record.spoken !== record.title ? record.spoken : record.text
88
+ return {
89
+ title: record.test ? `[test] ${title}` : title,
90
+ body: body.length > BODY_LIMIT ? `${body.slice(0, BODY_LIMIT - 1)}…` : body,
91
+ tag: record.id,
92
+ url: `./?notify-inbox=${encodeURIComponent(record.id)}`,
93
+ urgent: record.lane === 'interrupt',
94
+ }
95
+ }
96
+
97
+ /**
98
+ * @param {object} options
99
+ * @param {string} options.dataDir
100
+ * @param {string} options.vapidFile
101
+ * @param {string} options.subject - mailto: or https: contact for push services
102
+ * @param {() => boolean} options.perPerson - whether a person mapping is configured right now
103
+ * @param {(message: string) => void} options.warn
104
+ * @param {typeof fetch} [options.fetchImpl]
105
+ */
106
+ export function createPush({ dataDir, vapidFile, subject, perPerson, warn, fetchImpl = fetch }) {
107
+ const subsPath = join(dataDir, '.push', 'subscriptions.json')
108
+ const cursorPath = join(dataDir, '.push', 'cursor.json')
109
+ let keys
110
+ let chain = Promise.resolve()
111
+ const serial = task => (chain = chain.then(task, task))
112
+
113
+ async function vapid() {
114
+ keys ??= await vapidKeys(vapidFile)
115
+ return keys
116
+ }
117
+
118
+ const subscriptions = async () => (await readJson(subsPath, [])).filter(sub => typeof sub?.endpoint === 'string')
119
+
120
+ /** Whether a subscription gets a person's records. */
121
+ function reaches(sub, person) {
122
+ if (sub.person === null || sub.person === undefined) return !perPerson()
123
+ return sub.person === person
124
+ }
125
+
126
+ function subscribe(person, value, label) {
127
+ return serial(async () => {
128
+ const checked = checkSubscription(value)
129
+ if (checked instanceof Error) throw checked
130
+ const all = (await subscriptions()).filter(sub => sub.endpoint !== checked.endpoint)
131
+ if (all.length >= MAX_SUBSCRIPTIONS) throw new Error('Too many devices are subscribed; turn one off first.')
132
+ all.push({ ...checked, person: person ?? null, label: String(label ?? '').slice(0, 80), createdAt: new Date().toISOString() })
133
+ await writeJson(subsPath, all)
134
+ })
135
+ }
136
+
137
+ function unsubscribe(person, endpoint) {
138
+ return serial(async () => {
139
+ const all = await subscriptions()
140
+ const kept = all.filter(sub => !(sub.endpoint === endpoint && (sub.person ?? null) === (person ?? null)))
141
+ if (kept.length !== all.length) await writeJson(subsPath, kept)
142
+ })
143
+ }
144
+
145
+ /** Whether this browser (by endpoint) is subscribed for this person. */
146
+ async function has(person, endpoint) {
147
+ return (await subscriptions()).some(sub => sub.endpoint === endpoint && (sub.person ?? null) === (person ?? null))
148
+ }
149
+
150
+ async function deliver(subs, payload, urgent) {
151
+ const gone = []
152
+ let sent = 0
153
+ for (const sub of subs) {
154
+ try {
155
+ const result = await sendPush(sub, payload, { vapid: await vapid(), subject, urgency: urgent ? 'high' : 'normal', fetchImpl })
156
+ if (result.ok) sent += 1
157
+ else if (result.gone) gone.push(sub.endpoint)
158
+ else warn(`push to ${new URL(sub.endpoint).host} answered ${result.status}`)
159
+ } catch (error) {
160
+ warn(`push to ${new URL(sub.endpoint).host} failed: ${error.message}`)
161
+ }
162
+ }
163
+ if (gone.length > 0) {
164
+ const all = await subscriptions()
165
+ await writeJson(subsPath, all.filter(sub => !gone.includes(sub.endpoint)))
166
+ }
167
+ return { sent, removed: gone.length }
168
+ }
169
+
170
+ /** Push a test to the asking person's devices. */
171
+ function test(person) {
172
+ return serial(async () => {
173
+ const subs = (await subscriptions()).filter(sub => (sub.person ?? null) === (person ?? null))
174
+ return deliver(subs, { title: 'Inbox', body: 'Notifications reach this device.', tag: 'notify-inbox-test', url: './?notify-inbox=', urgent: false }, false)
175
+ })
176
+ }
177
+
178
+ /** Push what was appended to each person's inbox since the last scan. */
179
+ function scan(people) {
180
+ return serial(async () => {
181
+ const cursor = await readJson(cursorPath, {})
182
+ let changed = false
183
+ for (const person of people) {
184
+ const path = join(dataDir, person, 'inbox.jsonl')
185
+ let info
186
+ try {
187
+ info = await stat(path)
188
+ } catch {
189
+ continue
190
+ }
191
+ const seen = cursor[person]
192
+ if (seen === undefined || seen.ino !== info.ino || info.size < seen.offset) {
193
+ cursor[person] = { ino: info.ino, offset: info.size }
194
+ changed = true
195
+ continue
196
+ }
197
+ if (info.size === seen.offset) continue
198
+ const parsed = parseLines(await readFrom(path, seen.offset), person)
199
+ cursor[person] = { ino: info.ino, offset: seen.offset + parsed.used }
200
+ changed = true
201
+ const fresh = parsed.records.filter(record => record.push)
202
+ if (fresh.length === 0) continue
203
+ const subs = (await subscriptions()).filter(sub => reaches(sub, person))
204
+ for (const record of fresh) await deliver(subs, payloadOf(record), record.lane === 'interrupt')
205
+ }
206
+ if (changed) await writeJson(cursorPath, cursor)
207
+ })
208
+ }
209
+
210
+ return { vapid, subscribe, unsubscribe, has, test, scan }
211
+ }
package/src/routes.js ADDED
@@ -0,0 +1,205 @@
1
+ /**
2
+ * The inbox API. Exact Fetch routes under DSH's `/api`, so DSH admits the
3
+ * browser first and a `requestIdentity` provider sees the request; every
4
+ * answer is decided here, per request, from who is asking.
5
+ *
6
+ * GET /api/notify-inbox/summary unread count and newest time (badge)
7
+ * GET /api/notify-inbox/items?unread=1&before=&limit=
8
+ * POST /api/notify-inbox/read { ids: [...] } or { all: true }
9
+ * POST /api/notify-inbox/action { record, action, until? } a done/snooze/event press
10
+ * GET /api/notify-inbox/file?id=&name= a stored attachment
11
+ * GET /api/notify-inbox/push/config { publicKey }
12
+ * POST /api/notify-inbox/push/state { endpoint } → { subscribed }
13
+ * POST /api/notify-inbox/push/subscribe { subscription, label }
14
+ * POST /api/notify-inbox/push/unsubscribe { endpoint }
15
+ * POST /api/notify-inbox/push/test
16
+ * GET /api/notify-inbox/sw.js the service worker (scope /api/notify-inbox/)
17
+ */
18
+ import { readFile } from 'node:fs/promises'
19
+ import { extname } from 'node:path'
20
+ import { viewerOf } from './access.js'
21
+ import { PERSON_PATTERN, RECORD_ID_PATTERN } from './store.js'
22
+
23
+ export const PREFIX = '/api/notify-inbox'
24
+ const MAX_BODY = 16 * 1024
25
+ const PAGE = 50
26
+
27
+ const HEADERS = {
28
+ 'content-type': 'application/json; charset=utf-8',
29
+ 'cache-control': 'private, no-store',
30
+ 'x-content-type-options': 'nosniff',
31
+ }
32
+
33
+ const json = (status, body, extra = {}) => new Response(JSON.stringify(body), { status, headers: { ...HEADERS, ...extra } })
34
+ const NO_PROVIDER = 'This inbox needs a sign-in plugin that provides requestIdentity, and none is running.'
35
+
36
+ const FILE_TYPES = {
37
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp',
38
+ '.pdf': 'application/pdf', '.txt': 'text/plain; charset=utf-8', '.mp3': 'audio/mpeg', '.m4a': 'audio/mp4', '.mp4': 'video/mp4',
39
+ }
40
+
41
+ async function body(request) {
42
+ const text = await request.text()
43
+ if (text.length > MAX_BODY) throw Object.assign(new Error('Request too large.'), { status: 413 })
44
+ try {
45
+ const value = JSON.parse(text || '{}')
46
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error('not an object')
47
+ return value
48
+ } catch {
49
+ throw Object.assign(new Error('Send a JSON object.'), { status: 400 })
50
+ }
51
+ }
52
+
53
+ /**
54
+ * @param {object} options
55
+ * @param {ReturnType<import('./store.js').createStore>} options.store
56
+ * @param {ReturnType<import('./access.js').createPeople>} options.people
57
+ * @param {ReturnType<import('./push.js').createPush>} options.push
58
+ * @param {ReturnType<import('./actions.js').createActions>} options.actions
59
+ * @param {() => object | undefined} options.identity - the requestIdentity service right now, if any
60
+ * @param {string} options.serviceWorker - the service worker's source
61
+ * @param {number} options.pollSeconds
62
+ */
63
+ export function createRoutes({ store, people, push, actions, identity, serviceWorker, pollSeconds }) {
64
+ /** Who is asking, as the inbox folders they may read; undefined with the response to send instead. */
65
+ async function caller() {
66
+ const viewer = await viewerOf(people, identity())
67
+ if (viewer.unavailable) return { response: json(503, { error: NO_PROVIDER }) }
68
+ if (viewer.mode === 'owner') return { mode: 'owner', person: null, folders: await store.persons() }
69
+ const person = viewer.person !== undefined && PERSON_PATTERN.test(viewer.person) ? viewer.person : undefined
70
+ return { mode: 'people', person, folders: person === undefined ? [] : [person] }
71
+ }
72
+
73
+ const handle = fn => async request => {
74
+ try {
75
+ const who = await caller()
76
+ if (who.response !== undefined) return who.response
77
+ return await fn(request, who)
78
+ } catch (error) {
79
+ return json(error.status ?? 500, { error: error.status ? error.message : 'Something went wrong.' })
80
+ }
81
+ }
82
+
83
+ async function withPresses(who, items) {
84
+ const byPerson = new Map()
85
+ for (const person of new Set(items.map(item => item.person))) byPerson.set(person, await actions.presses(person))
86
+ return items.map(item => ({ ...item, presses: byPerson.get(item.person)?.get(item.id) ?? [] }))
87
+ }
88
+
89
+ const summary = handle(async (_request, who) => {
90
+ const { items, bad } = await store.view(who.folders)
91
+ const unread = items.filter(item => !item.read).length
92
+ return json(200, { mode: who.mode, person: who.person, unread, total: items.length, latest: items[0]?.time ?? null, problems: { badLines: bad }, pollSeconds })
93
+ })
94
+
95
+ const list = handle(async (request, who) => {
96
+ const params = new URL(request.url).searchParams
97
+ const limit = Math.min(Math.max(Number(params.get('limit')) || PAGE, 1), 200)
98
+ let { items } = await store.view(who.folders)
99
+ if (params.get('unread') === '1') items = items.filter(item => !item.read)
100
+ const before = params.get('before')
101
+ if (before) {
102
+ const at = items.findIndex(item => item.id === before)
103
+ items = at < 0 ? [] : items.slice(at + 1)
104
+ }
105
+ const page = items.slice(0, limit)
106
+ return json(200, { items: await withPresses(who, page), more: items.length > limit })
107
+ })
108
+
109
+ /** The record with this id the caller may see, or undefined. */
110
+ async function recordOf(who, id) {
111
+ if (typeof id !== 'string' || !RECORD_ID_PATTERN.test(id)) return undefined
112
+ for (const person of who.folders) {
113
+ const record = (await store.records(person)).records.find(row => row.id === id)
114
+ if (record !== undefined) return record
115
+ }
116
+ return undefined
117
+ }
118
+
119
+ const read = handle(async (request, who) => {
120
+ const value = await body(request)
121
+ if (value.all === true) {
122
+ for (const person of who.folders) await store.markAllRead(person)
123
+ } else if (Array.isArray(value.ids)) {
124
+ const ids = value.ids.filter(id => typeof id === 'string').slice(0, 500)
125
+ for (const person of who.folders) await store.markRead(person, ids)
126
+ } else {
127
+ return json(400, { error: 'Send ids or all.' })
128
+ }
129
+ return json(200, { ok: true })
130
+ })
131
+
132
+ const action = handle(async (request, who) => {
133
+ const value = await body(request)
134
+ const record = await recordOf(who, value.record)
135
+ if (record === undefined) return json(404, { error: 'No such notification.' })
136
+ const declared = record.actions.find(row => row.id === value.action)
137
+ if (declared === undefined) return json(400, { error: 'This notification has no such button.' })
138
+ if (!['done', 'snooze', 'event'].includes(declared.kind)) return json(400, { error: 'This button acts in the page.' })
139
+ const result = await actions.press(record.person, record, declared, { until: value.until })
140
+ await store.markRead(record.person, [record.id])
141
+ return json(200, { press: result.event.press, published: result.published, matched: result.matched ?? 0 })
142
+ })
143
+
144
+ const file = handle(async (request, who) => {
145
+ const params = new URL(request.url).searchParams
146
+ const found = await store.file(who.folders, params.get('id') ?? '', params.get('name') ?? '')
147
+ if (found === undefined) return json(404, { error: 'No such file.' })
148
+ const type = FILE_TYPES[extname(found.name).toLowerCase()] ?? 'application/octet-stream'
149
+ const inline = type !== 'application/octet-stream' && !type.startsWith('text/html')
150
+ return new Response(await readFile(found.path), {
151
+ status: 200,
152
+ headers: {
153
+ 'content-type': type,
154
+ 'content-disposition': `${inline ? 'inline' : 'attachment'}; filename*=UTF-8''${encodeURIComponent(found.name)}`,
155
+ 'cache-control': 'private, max-age=3600',
156
+ 'x-content-type-options': 'nosniff',
157
+ 'content-security-policy': "default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'; sandbox",
158
+ },
159
+ })
160
+ })
161
+
162
+ const pushConfig = handle(async () => json(200, { publicKey: (await push.vapid()).publicKey }))
163
+ const pushState = handle(async (request, who) => {
164
+ const value = await body(request)
165
+ return json(200, { subscribed: typeof value.endpoint === 'string' && (await push.has(who.person, value.endpoint)) })
166
+ })
167
+ const subscribe = handle(async (request, who) => {
168
+ if (who.mode === 'people' && who.person === undefined) return json(403, { error: 'You have no inbox here.' })
169
+ const value = await body(request)
170
+ try {
171
+ await push.subscribe(who.person, value.subscription, value.label)
172
+ } catch (error) {
173
+ return json(400, { error: error.message })
174
+ }
175
+ return json(200, { ok: true })
176
+ })
177
+ const unsubscribe = handle(async (request, who) => {
178
+ const value = await body(request)
179
+ if (typeof value.endpoint !== 'string') return json(400, { error: 'Send the endpoint.' })
180
+ await push.unsubscribe(who.person, value.endpoint)
181
+ return json(200, { ok: true })
182
+ })
183
+ const pushTest = handle(async (_request, who) => json(200, await push.test(who.person)))
184
+
185
+ const worker = async () => new Response(serviceWorker, {
186
+ status: 200,
187
+ headers: { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-cache', 'x-content-type-options': 'nosniff' },
188
+ })
189
+
190
+ const get = (path, fetch) => ({ path: `${PREFIX}${path}`, methods: ['GET'], requestBody: 'buffered', fetch })
191
+ const post = (path, fetch) => ({ path: `${PREFIX}${path}`, methods: ['POST'], requestBody: 'buffered', fetch })
192
+ return [
193
+ get('/summary', summary),
194
+ get('/items', list),
195
+ post('/read', read),
196
+ post('/action', action),
197
+ get('/file', file),
198
+ get('/push/config', pushConfig),
199
+ post('/push/state', pushState),
200
+ post('/push/subscribe', subscribe),
201
+ post('/push/unsubscribe', unsubscribe),
202
+ post('/push/test', pushTest),
203
+ get('/sw.js', worker),
204
+ ]
205
+ }