@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/CHANGELOG.md +9 -0
- package/LICENSE +21 -0
- package/README.md +96 -2
- package/client.actions.js +259 -0
- package/client.js +526 -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 +50 -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/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) || undefined,
|
|
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
|
+
}
|