@soffits/dsh-notify-inbox 0.0.0-stage → 0.1.0
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/CHANGELOG.md +5 -0
- package/LICENSE +21 -0
- package/README.md +96 -2
- package/client.js +582 -0
- package/cordis.patch.yml +9 -0
- package/icon.svg +6 -0
- package/index.js +90 -0
- package/locale/en.json +1 -0
- package/locale/zh.json +1 -0
- package/package.json +49 -4
- package/src/access.js +92 -0
- package/src/actions.js +89 -0
- package/src/push.js +211 -0
- package/src/routes.js +205 -0
- package/src/store.js +223 -0
- package/src/sw.js +77 -0
- package/src/webpush.js +101 -0
package/index.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DeepSeek Harness Host plugin: a notification inbox.
|
|
3
|
+
*
|
|
4
|
+
* A notification router outside DSH files each message as one JSON line per
|
|
5
|
+
* person (`<dataDir>/<person>/inbox.jsonl`). This plugin shows each signed-in
|
|
6
|
+
* person their own inbox with read and unread, sends Web Push to the browsers
|
|
7
|
+
* they subscribed, and turns presses on a notification's buttons into events.
|
|
8
|
+
* It holds no credentials but its own VAPID key and contacts nothing but the
|
|
9
|
+
* push services the subscribed browsers chose.
|
|
10
|
+
*/
|
|
11
|
+
import { readFileSync } from 'node:fs'
|
|
12
|
+
import { homedir } from 'node:os'
|
|
13
|
+
import { isAbsolute, join, resolve } from 'node:path'
|
|
14
|
+
import z from '@deepseek-ai/schemastery'
|
|
15
|
+
import { createPeople, expandHome } from './src/access.js'
|
|
16
|
+
import { createActions } from './src/actions.js'
|
|
17
|
+
import { createPush } from './src/push.js'
|
|
18
|
+
import { createRoutes } from './src/routes.js'
|
|
19
|
+
import { createStore } from './src/store.js'
|
|
20
|
+
|
|
21
|
+
export const name = 'dsh-notify-inbox'
|
|
22
|
+
export const inject = ['connection']
|
|
23
|
+
|
|
24
|
+
const serviceWorker = readFileSync(new URL('./src/sw.js', import.meta.url), 'utf8')
|
|
25
|
+
|
|
26
|
+
export const Config = z.object({
|
|
27
|
+
dataDir: z.string().required()
|
|
28
|
+
.description('The folder the notification router files into: <dataDir>/<person>/inbox.jsonl. Read marks, the action log and push subscriptions are kept in it too. A leading ~/ means the home folder.'),
|
|
29
|
+
people: z.dict(z.string()).default({})
|
|
30
|
+
.description('Verified user id (from the sign-in plugin, such as an OIDC sub) → person id (the inbox folder name). With any mapping configured, each person sees only their own inbox.'),
|
|
31
|
+
peopleFile: z.string().default('')
|
|
32
|
+
.description('A JSON file with more of the same mapping, re-read when it changes. Entries in people win.'),
|
|
33
|
+
peopleKey: z.string().default('')
|
|
34
|
+
.description('The top-level key in peopleFile that holds the mapping. Empty means the whole file is the mapping.'),
|
|
35
|
+
vapidFile: z.string().default('')
|
|
36
|
+
.description('Where the Web Push (VAPID) key pair is kept; made on first start, mode 600. Default: .push/vapid.json in dataDir.'),
|
|
37
|
+
vapidSubject: z.string().default('mailto:admin@example.invalid')
|
|
38
|
+
.description('A mailto: or https: contact that push services can reach about this server.'),
|
|
39
|
+
pollSeconds: z.natural().min(2).max(3600).default(5)
|
|
40
|
+
.description('How often new records are looked for (to push them), and how often an open page refreshes its count (at least 15 s).'),
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
45
|
+
* @param {{ dataDir: string, people: Record<string, string>, peopleFile: string, peopleKey: string, vapidFile: string, vapidSubject: string, pollSeconds: number }} config
|
|
46
|
+
*/
|
|
47
|
+
export function apply(ctx, config) {
|
|
48
|
+
const logger = ctx.logger('notify-inbox')
|
|
49
|
+
const home = homedir()
|
|
50
|
+
const absolute = path => {
|
|
51
|
+
const expanded = expandHome(path, home)
|
|
52
|
+
return isAbsolute(expanded) ? expanded : resolve(expanded)
|
|
53
|
+
}
|
|
54
|
+
const dataDir = absolute(config.dataDir)
|
|
55
|
+
const warn = message => logger.warn(message)
|
|
56
|
+
const people = createPeople({
|
|
57
|
+
people: config.people ?? {},
|
|
58
|
+
peopleFile: config.peopleFile ? absolute(config.peopleFile) : '',
|
|
59
|
+
peopleKey: config.peopleKey ?? '',
|
|
60
|
+
}, { warn })
|
|
61
|
+
const store = createStore(dataDir)
|
|
62
|
+
const push = createPush({
|
|
63
|
+
dataDir,
|
|
64
|
+
vapidFile: config.vapidFile ? absolute(config.vapidFile) : join(dataDir, '.push', 'vapid.json'),
|
|
65
|
+
subject: config.vapidSubject,
|
|
66
|
+
perPerson: () => people.enabled,
|
|
67
|
+
warn,
|
|
68
|
+
})
|
|
69
|
+
const actions = createActions({ dataDir, events: () => ctx.get('cronJobs'), warn })
|
|
70
|
+
const pollSeconds = config.pollSeconds ?? 5
|
|
71
|
+
const routes = createRoutes({ store, people, push, actions, identity: () => ctx.get('requestIdentity'), serviceWorker, pollSeconds: Math.max(pollSeconds, 15) })
|
|
72
|
+
for (const route of routes) ctx.connection.fetch.register(route)
|
|
73
|
+
|
|
74
|
+
let stopped = false
|
|
75
|
+
let timer
|
|
76
|
+
const scan = async () => {
|
|
77
|
+
try {
|
|
78
|
+
await push.scan(await store.persons())
|
|
79
|
+
} catch (error) {
|
|
80
|
+
warn(`push scan failed: ${error.message}`)
|
|
81
|
+
}
|
|
82
|
+
if (!stopped) timer = setTimeout(scan, pollSeconds * 1000)
|
|
83
|
+
}
|
|
84
|
+
push.vapid().then(() => scan(), error => logger.error(`Web Push keys unusable, push is off: ${error.message}`))
|
|
85
|
+
ctx.on('dispose', () => {
|
|
86
|
+
stopped = true
|
|
87
|
+
clearTimeout(timer)
|
|
88
|
+
})
|
|
89
|
+
logger.info(`inbox at ${dataDir} (${people.enabled ? 'per person' : 'single owner'})`)
|
|
90
|
+
}
|
package/locale/en.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{ "meta": { "title": "Notification Inbox", "description": "One inbox for the notifications your assistant and scripts send: read and unread per person, Web Push to phones and browsers, and buttons to act on each one." } }
|
package/locale/zh.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{ "meta": { "title": "通知收件箱", "description": "助手和脚本发出的通知都收在这里:每个人各看各的、分已读未读,推送到手机和浏览器,每条通知都能直接操作。" } }
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@soffits/dsh-notify-inbox",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
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
|
+
"./locale/*.json": "./locale/*.json",
|
|
22
|
+
"./icon": "./icon.svg",
|
|
23
|
+
"./package.json": "./package.json"
|
|
24
|
+
},
|
|
25
|
+
"files": ["src", "client.js", "index.js", "cordis.patch.yml", "locale/*.json", "icon.svg", "README.md", "CHANGELOG.md", "LICENSE"],
|
|
26
|
+
"dsh": {
|
|
27
|
+
"bundle": {
|
|
28
|
+
"patch": "./cordis.patch.yml"
|
|
29
|
+
},
|
|
30
|
+
"client": {
|
|
31
|
+
"platform": "web",
|
|
32
|
+
"immediately": true,
|
|
33
|
+
"inject": [
|
|
34
|
+
"@deepseek-ai/dsh-client-locale",
|
|
35
|
+
"@deepseek-ai/dsh-client-ui-layout",
|
|
36
|
+
"@deepseek-ai/dsh-client-ui-sidebar"
|
|
37
|
+
]
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
"scripts": {
|
|
41
|
+
"check": "for f in index.js client.js src/*.js test/*.js; do node --check \"$f\" || exit 1; done",
|
|
42
|
+
"test": "node --test test/*.test.js"
|
|
43
|
+
},
|
|
44
|
+
"dependencies": {
|
|
45
|
+
"@deepseek-ai/schemastery": "3.18.5"
|
|
46
|
+
},
|
|
47
|
+
"engines": {
|
|
48
|
+
"node": ">=22",
|
|
49
|
+
"dsh": ">=0.2.1-rc.2 <0.3.0"
|
|
50
|
+
}
|
|
51
|
+
}
|
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
|
+
}
|