@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/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
+ }
package/src/store.js ADDED
@@ -0,0 +1,223 @@
1
+ /**
2
+ * The inbox store: what the notification router files, and the read marks
3
+ * this plugin keeps beside it.
4
+ *
5
+ * <dataDir>/<person>/inbox.jsonl one record per line; written by the router only
6
+ * <dataDir>/<person>/files/<id>/<name> attachments the router copied in
7
+ * <dataDir>/<person>/read.json read marks; written by this plugin only
8
+ *
9
+ * Records are re-read incrementally: only the bytes appended since the last
10
+ * look are parsed, and the whole file again when it shrank or was replaced
11
+ * (someone removed a test entry). A line that isn't a valid record is skipped
12
+ * and counted, never fatal.
13
+ */
14
+ import { open, readFile, readdir, rename, stat, writeFile, mkdir } from 'node:fs/promises'
15
+ import { join } from 'node:path'
16
+
17
+ export const PERSON_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/
18
+ export const RECORD_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,79}$/
19
+ const INBOX = 'inbox.jsonl'
20
+ const READ = 'read.json'
21
+
22
+ const text = value => (typeof value === 'string' ? value : '')
23
+ const list = value => (Array.isArray(value) ? value : [])
24
+
25
+ /** A record as the page gets it, or undefined when the line is not one. */
26
+ export function normalize(raw, person) {
27
+ if (typeof raw !== 'object' || raw === null || !RECORD_ID_PATTERN.test(text(raw.id))) return undefined
28
+ const time = Date.parse(text(raw.time))
29
+ if (Number.isNaN(time)) return undefined
30
+ return {
31
+ id: raw.id,
32
+ person,
33
+ time: new Date(time).toISOString(),
34
+ lane: text(raw.lane) || 'next-moment',
35
+ domain: text(raw.domain),
36
+ title: text(raw.title),
37
+ spoken: text(raw.spoken),
38
+ text: text(raw.text),
39
+ links: list(raw.links).filter(link => typeof link === 'string' && /^https?:\/\//i.test(link)),
40
+ files: list(raw.files).filter(file => typeof file?.name === 'string').map(file => ({
41
+ name: file.name,
42
+ size: typeof file.size === 'number' ? file.size : undefined,
43
+ stored: file.stored === true,
44
+ reason: text(file.reason) || undefined,
45
+ })),
46
+ source: text(raw.source),
47
+ key: text(raw.key),
48
+ actions: list(raw.actions).filter(action => typeof action?.kind === 'string' && typeof action?.id === 'string').map(action => ({
49
+ kind: action.kind,
50
+ id: action.id,
51
+ label: text(action.label),
52
+ payload: typeof action.payload === 'object' && action.payload !== null && !Array.isArray(action.payload) ? action.payload : {},
53
+ })),
54
+ test: raw.test === true,
55
+ push: raw.push !== false,
56
+ routed: list(raw.routed).filter(row => typeof row?.destination === 'string').map(row => ({
57
+ destination: row.destination,
58
+ type: text(row.type),
59
+ ok: row.ok === true,
60
+ detail: text(row.detail) || undefined,
61
+ })),
62
+ }
63
+ }
64
+
65
+ /** A "this press was handled" line the router appends after acting on a press, or undefined. */
66
+ export function normalizeHandled(raw) {
67
+ if (raw?.type !== 'handled' || typeof raw.record !== 'string') return undefined
68
+ return { record: raw.record, press: text(raw.press), action: text(raw.action), result: text(raw.result), until: text(raw.until) || undefined, time: text(raw.time) }
69
+ }
70
+
71
+ /**
72
+ * Complete lines in `chunk`, parsed; the unfinished tail (a write in progress) is left for next time.
73
+ * Lines with a `type` are status lines, not records.
74
+ */
75
+ export function parseLines(chunk, person) {
76
+ const end = chunk.lastIndexOf(0x0a)
77
+ if (end < 0) return { records: [], handled: [], bad: 0, used: 0 }
78
+ const records = []
79
+ const handled = []
80
+ let bad = 0
81
+ for (const line of chunk.subarray(0, end).toString('utf8').split('\n')) {
82
+ if (line.trim() === '') continue
83
+ let value
84
+ try {
85
+ value = JSON.parse(line)
86
+ } catch {
87
+ bad += 1
88
+ continue
89
+ }
90
+ if (value?.type !== undefined) {
91
+ const status = normalizeHandled(value)
92
+ if (status !== undefined) handled.push(status)
93
+ continue
94
+ }
95
+ const record = normalize(value, person)
96
+ if (record === undefined) bad += 1
97
+ else records.push(record)
98
+ }
99
+ return { records, handled, bad, used: end + 1 }
100
+ }
101
+
102
+ export async function readFrom(path, offset) {
103
+ const handle = await open(path, 'r')
104
+ try {
105
+ const { size } = await handle.stat()
106
+ const length = Math.max(0, size - offset)
107
+ const buffer = Buffer.alloc(length)
108
+ if (length > 0) await handle.read(buffer, 0, length, offset)
109
+ return buffer
110
+ } finally {
111
+ await handle.close()
112
+ }
113
+ }
114
+
115
+ async function atomicWrite(path, value) {
116
+ const tmp = `${path}.${process.pid}.${Date.now()}.tmp`
117
+ await writeFile(tmp, JSON.stringify(value), { mode: 0o600 })
118
+ await rename(tmp, path)
119
+ }
120
+
121
+ /** Read marks: everything up to `readBefore` (ISO time) is read, plus the ids in `read`. */
122
+ export function isRead(marks, record) {
123
+ return (marks.readBefore !== '' && record.time <= marks.readBefore) || marks.read.includes(record.id)
124
+ }
125
+
126
+ export function createStore(dataDir) {
127
+ const cache = new Map() // person -> { ino, offset, records, bad }
128
+
129
+ async function persons() {
130
+ let entries
131
+ try {
132
+ entries = await readdir(dataDir, { withFileTypes: true })
133
+ } catch {
134
+ return []
135
+ }
136
+ return entries.filter(entry => entry.isDirectory() && PERSON_PATTERN.test(entry.name)).map(entry => entry.name).sort()
137
+ }
138
+
139
+ /** Every record of one person, oldest first. */
140
+ async function records(person) {
141
+ const path = join(dataDir, person, INBOX)
142
+ let info
143
+ try {
144
+ info = await stat(path)
145
+ } catch {
146
+ cache.delete(person)
147
+ return { records: [], handled: [], bad: 0 }
148
+ }
149
+ let entry = cache.get(person)
150
+ if (entry === undefined || entry.ino !== info.ino || info.size < entry.offset) {
151
+ entry = { ino: info.ino, offset: 0, records: [], handled: [], bad: 0 }
152
+ cache.set(person, entry)
153
+ }
154
+ if (info.size > entry.offset) {
155
+ const parsed = parseLines(await readFrom(path, entry.offset), person)
156
+ entry.records.push(...parsed.records)
157
+ entry.handled.push(...parsed.handled)
158
+ entry.bad += parsed.bad
159
+ entry.offset += parsed.used
160
+ }
161
+ return { records: entry.records, handled: entry.handled, bad: entry.bad }
162
+ }
163
+
164
+ async function marks(person) {
165
+ try {
166
+ const value = JSON.parse(await readFile(join(dataDir, person, READ), 'utf8'))
167
+ return { readBefore: text(value.readBefore), read: list(value.read).filter(id => typeof id === 'string') }
168
+ } catch {
169
+ return { readBefore: '', read: [] }
170
+ }
171
+ }
172
+
173
+ async function saveMarks(person, value) {
174
+ await mkdir(join(dataDir, person), { recursive: true })
175
+ await atomicWrite(join(dataDir, person, READ), value)
176
+ }
177
+
178
+ /** Mark some records read; ids that aren't this person's are ignored. */
179
+ async function markRead(person, ids) {
180
+ const known = new Set((await records(person)).records.map(record => record.id))
181
+ const current = await marks(person)
182
+ const read = [...new Set([...current.read, ...ids.filter(id => known.has(id))])]
183
+ await saveMarks(person, { readBefore: current.readBefore, read })
184
+ }
185
+
186
+ /** Mark everything up to the newest record read; the per-id list drops what the watermark covers. */
187
+ async function markAllRead(person) {
188
+ const all = (await records(person)).records
189
+ if (all.length === 0) return
190
+ const readBefore = all.reduce((latest, record) => (record.time > latest ? record.time : latest), '')
191
+ const current = await marks(person)
192
+ const byId = new Map(all.map(record => [record.id, record]))
193
+ await saveMarks(person, { readBefore, read: current.read.filter(id => byId.has(id) && byId.get(id).time > readBefore) })
194
+ }
195
+
196
+ /** The records of these people, newest first, each with `read`. */
197
+ async function view(people) {
198
+ const out = []
199
+ let bad = 0
200
+ for (const person of people) {
201
+ const [{ records: rows, handled, bad: skipped }, marked] = await Promise.all([records(person), marks(person)])
202
+ bad += skipped
203
+ const byRecord = new Map()
204
+ for (const status of handled) byRecord.set(status.record, [...(byRecord.get(status.record) ?? []), status])
205
+ for (const record of rows) out.push({ ...record, read: isRead(marked, record), handled: byRecord.get(record.id) ?? [] })
206
+ }
207
+ out.sort((a, b) => (a.time === b.time ? 0 : a.time < b.time ? 1 : -1))
208
+ return { items: out, bad }
209
+ }
210
+
211
+ /** Where a stored attachment lives, or undefined. */
212
+ async function file(people, id, name) {
213
+ if (!RECORD_ID_PATTERN.test(id) || typeof name !== 'string' || name === '' || name.includes('/') || name.includes('\\') || name.startsWith('.')) return undefined
214
+ for (const person of people) {
215
+ const record = (await records(person)).records.find(row => row.id === id)
216
+ const entry = record?.files.find(row => row.name === name && row.stored)
217
+ if (entry !== undefined) return { path: join(dataDir, person, 'files', id, name), name }
218
+ }
219
+ return undefined
220
+ }
221
+
222
+ return { persons, records, marks, markRead, markAllRead, view, file }
223
+ }
package/src/sw.js ADDED
@@ -0,0 +1,77 @@
1
+ /*
2
+ * Service worker of dsh-notify-inbox, served at /api/notify-inbox/sw.js with
3
+ * the scope /api/notify-inbox/, so it controls no page of the app. It only
4
+ * shows pushed notifications and opens the inbox when one is tapped.
5
+ */
6
+ const root = new URL('../../', self.location.href)
7
+
8
+ self.addEventListener('install', () => self.skipWaiting())
9
+ self.addEventListener('activate', event => event.waitUntil(self.clients.claim()))
10
+
11
+ function payloadOf(event) {
12
+ try {
13
+ const value = event.data?.json()
14
+ if (value && typeof value === 'object') return value
15
+ } catch {
16
+ // An unreadable payload still shows something.
17
+ }
18
+ return { title: 'Inbox', body: 'You have a new notification.' }
19
+ }
20
+
21
+ self.addEventListener('push', event => {
22
+ const value = payloadOf(event)
23
+ const options = {
24
+ body: typeof value.body === 'string' ? value.body : '',
25
+ data: { url: typeof value.url === 'string' ? value.url : './?notify-inbox=' },
26
+ icon: new URL('icon-192.png', root).href,
27
+ badge: new URL('icon-192.png', root).href,
28
+ requireInteraction: value.urgent === true,
29
+ }
30
+ if (typeof value.tag === 'string' && value.tag !== '') {
31
+ options.tag = value.tag
32
+ options.renotify = true
33
+ }
34
+ event.waitUntil(self.registration.showNotification(typeof value.title === 'string' && value.title ? value.title : 'Inbox', options))
35
+ })
36
+
37
+ self.addEventListener('notificationclick', event => {
38
+ event.notification.close()
39
+ let target = root.href
40
+ try {
41
+ const url = new URL(event.notification.data?.url ?? './', root)
42
+ if (url.origin === root.origin) target = url.href
43
+ } catch {
44
+ // Keep the app root.
45
+ }
46
+ event.waitUntil((async () => {
47
+ const windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true })
48
+ const open = windows.find(client => new URL(client.url).origin === root.origin)
49
+ if (open !== undefined) {
50
+ open.postMessage({ type: 'notify-inbox/open', url: target })
51
+ await open.focus()
52
+ return
53
+ }
54
+ await self.clients.openWindow(target)
55
+ })())
56
+ })
57
+
58
+ self.addEventListener('pushsubscriptionchange', event => {
59
+ const old = event.oldSubscription?.endpoint
60
+ event.waitUntil((async () => {
61
+ const post = (path, value) => fetch(new URL(path, self.location.href), {
62
+ method: 'POST',
63
+ credentials: 'same-origin',
64
+ headers: { 'content-type': 'application/json' },
65
+ body: JSON.stringify(value),
66
+ })
67
+ let next = event.newSubscription
68
+ if (!next) {
69
+ const config = await (await fetch(new URL('push/config', self.location.href), { credentials: 'same-origin' })).json()
70
+ const base64 = config.publicKey.replaceAll('-', '+').replaceAll('_', '/')
71
+ const raw = atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, '='))
72
+ next = await self.registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: Uint8Array.from(raw, c => c.charCodeAt(0)) })
73
+ }
74
+ await post('push/subscribe', { subscription: next.toJSON(), label: 'renewed' })
75
+ if (old !== undefined && old !== next.endpoint) await post('push/unsubscribe', { endpoint: old })
76
+ })().catch(() => {}))
77
+ })
package/src/webpush.js ADDED
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Web Push on node:crypto: message encryption (RFC 8291, aes128gcm from
3
+ * RFC 8188) and the application server's VAPID identity (RFC 8292).
4
+ *
5
+ * The push service only ever sees the encrypted body; the browser decrypts
6
+ * it with the keys it handed out when it subscribed.
7
+ */
8
+ import { createECDH, createPrivateKey, createCipheriv, generateKeyPairSync, hkdfSync, randomBytes, sign } from 'node:crypto'
9
+
10
+ const RECORD_SIZE = 4096
11
+ const VAPID_LIFETIME_SECONDS = 12 * 60 * 60
12
+
13
+ export const b64url = {
14
+ encode: buffer => Buffer.from(buffer).toString('base64url'),
15
+ decode: text => Buffer.from(String(text).replace(/\s+/g, ''), 'base64url'),
16
+ }
17
+
18
+ /** A fresh VAPID key pair: the raw uncompressed public point and the private scalar, base64url. */
19
+ export function generateVapidKeys() {
20
+ const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' })
21
+ const jwk = privateKey.export({ format: 'jwk' })
22
+ return { publicKey: publicFromJwk(jwk), privateKey: jwk.d }
23
+ }
24
+
25
+ function publicFromJwk(jwk) {
26
+ return b64url.encode(Buffer.concat([Buffer.from([4]), b64url.decode(jwk.x), b64url.decode(jwk.y)]))
27
+ }
28
+
29
+ /** Check a stored key pair and return it ready for signing; throws when it is not a P-256 pair. */
30
+ export function loadVapidKeys({ publicKey, privateKey }) {
31
+ const point = b64url.decode(publicKey)
32
+ if (point.length !== 65 || point[0] !== 4) throw new Error('VAPID public key is not an uncompressed P-256 point')
33
+ const jwk = { kty: 'EC', crv: 'P-256', d: privateKey, x: b64url.encode(point.subarray(1, 33)), y: b64url.encode(point.subarray(33)) }
34
+ const derived = createECDH('prime256v1')
35
+ derived.setPrivateKey(b64url.decode(privateKey))
36
+ if (!derived.getPublicKey().equals(point)) throw new Error('VAPID keys do not belong together')
37
+ return { publicKey: b64url.encode(point), key: createPrivateKey({ key: jwk, format: 'jwk' }) }
38
+ }
39
+
40
+ /** The `Authorization` header value for one push service origin. */
41
+ export function vapidAuthorization(keys, audience, subject, now = Date.now()) {
42
+ const header = b64url.encode(JSON.stringify({ typ: 'JWT', alg: 'ES256' }))
43
+ const claims = b64url.encode(JSON.stringify({ aud: audience, exp: Math.floor(now / 1000) + VAPID_LIFETIME_SECONDS, sub: subject }))
44
+ const signature = sign('sha256', Buffer.from(`${header}.${claims}`), { key: keys.key, dsaEncoding: 'ieee-p1363' })
45
+ return `vapid t=${header}.${claims}.${b64url.encode(signature)}, k=${keys.publicKey}`
46
+ }
47
+
48
+ /**
49
+ * Encrypt one push message for a subscription's keys.
50
+ * `serverKeys` and `salt` are for tests; normally both are fresh per message.
51
+ * @param {Buffer|string} plaintext
52
+ * @param {{ p256dh: string, auth: string }} subscriptionKeys - base64url, as the browser gives them
53
+ */
54
+ export function encrypt(plaintext, subscriptionKeys, { serverPrivateKey, salt = randomBytes(16) } = {}) {
55
+ const uaPublic = b64url.decode(subscriptionKeys.p256dh)
56
+ const authSecret = b64url.decode(subscriptionKeys.auth)
57
+ if (uaPublic.length !== 65 || uaPublic[0] !== 4) throw new Error('subscription p256dh is not an uncompressed P-256 point')
58
+ if (authSecret.length !== 16) throw new Error('subscription auth secret is not 16 bytes')
59
+ const ecdh = createECDH('prime256v1')
60
+ if (serverPrivateKey === undefined) ecdh.generateKeys()
61
+ else ecdh.setPrivateKey(b64url.decode(serverPrivateKey))
62
+ const asPublic = ecdh.getPublicKey()
63
+ const ecdhSecret = ecdh.computeSecret(uaPublic)
64
+ const keyInfo = Buffer.concat([Buffer.from('WebPush: info\0'), uaPublic, asPublic])
65
+ const ikm = Buffer.from(hkdfSync('sha256', ecdhSecret, authSecret, keyInfo, 32))
66
+ const cek = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: aes128gcm\0'), 16))
67
+ const nonce = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: nonce\0'), 12))
68
+ const cipher = createCipheriv('aes-128-gcm', cek, nonce)
69
+ const body = Buffer.concat([cipher.update(Buffer.concat([Buffer.from(plaintext), Buffer.from([2])])), cipher.final(), cipher.getAuthTag()])
70
+ const header = Buffer.alloc(21)
71
+ salt.copy(header, 0)
72
+ header.writeUInt32BE(RECORD_SIZE, 16)
73
+ header.writeUInt8(asPublic.length, 20)
74
+ return Buffer.concat([header, asPublic, body])
75
+ }
76
+
77
+ /**
78
+ * Send one message. Resolves `{ ok, status }`; `gone` is true when the push
79
+ * service says the subscription no longer exists (404, 410).
80
+ * @param {{ endpoint: string, keys: { p256dh: string, auth: string } }} subscription
81
+ * @param {ReturnType<typeof loadVapidKeys>} vapid
82
+ */
83
+ export async function sendPush(subscription, payload, { vapid, subject, ttl = 86400, urgency = 'normal', topic, fetchImpl = fetch, timeoutMs = 10000 }) {
84
+ const url = new URL(subscription.endpoint)
85
+ const headers = {
86
+ authorization: vapidAuthorization(vapid, url.origin, subject),
87
+ 'content-encoding': 'aes128gcm',
88
+ 'content-type': 'application/octet-stream',
89
+ ttl: String(ttl),
90
+ urgency,
91
+ }
92
+ if (topic !== undefined) headers.topic = topic
93
+ const response = await fetchImpl(url.href, {
94
+ method: 'POST',
95
+ headers,
96
+ body: encrypt(typeof payload === 'string' ? payload : JSON.stringify(payload), subscription.keys),
97
+ signal: AbortSignal.timeout(timeoutMs),
98
+ })
99
+ await response.arrayBuffer().catch(() => undefined)
100
+ return { ok: response.ok, status: response.status, gone: response.status === 404 || response.status === 410 }
101
+ }