@hamur/pwa 0.0.0-stage → 0.0.2

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.
Files changed (55) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +14 -2
  3. package/dist/chunks/bun-index-33c14md9.js +11 -0
  4. package/dist/chunks/bun-index-5jwxzmvt.js +133 -0
  5. package/dist/src/adapters/html.js +28 -0
  6. package/dist/src/adapters/preact.js +23 -0
  7. package/dist/src/adapters/react.js +19 -0
  8. package/dist/src/adapters/solid.js +29 -0
  9. package/dist/src/adapters/svelte.js +32 -0
  10. package/dist/src/adapters/vue.js +31 -0
  11. package/dist/src/client/index.js +43 -0
  12. package/dist/src/index.js +178 -0
  13. package/dist/src/server/index.js +202 -0
  14. package/dist/types/src/adapters/bind.d.ts +4 -0
  15. package/dist/types/src/adapters/html.d.ts +3 -0
  16. package/dist/types/src/adapters/preact.d.ts +3 -0
  17. package/dist/types/src/adapters/react.d.ts +3 -0
  18. package/dist/types/src/adapters/solid.d.ts +6 -0
  19. package/dist/types/src/adapters/svelte.d.ts +3 -0
  20. package/dist/types/src/adapters/vue.d.ts +6 -0
  21. package/dist/types/src/build/icons.d.ts +7 -0
  22. package/dist/types/src/client/index.d.ts +3 -0
  23. package/dist/types/src/client/plugin.d.ts +4 -0
  24. package/dist/types/src/client/push.d.ts +4 -0
  25. package/dist/types/src/client/store.d.ts +34 -0
  26. package/dist/types/src/index.d.ts +8 -0
  27. package/dist/types/src/module.d.ts +3 -0
  28. package/dist/types/src/options.d.ts +13 -0
  29. package/dist/types/src/server/encrypt.d.ts +18 -0
  30. package/dist/types/src/server/index.d.ts +2 -0
  31. package/dist/types/src/server/push.d.ts +28 -0
  32. package/dist/types/src/server/vapid.d.ts +7 -0
  33. package/dist/types/src/types.d.ts +16 -0
  34. package/package.json +129 -4
  35. package/src/adapters/bind.ts +10 -0
  36. package/src/adapters/html.ts +24 -0
  37. package/src/adapters/preact.ts +16 -0
  38. package/src/adapters/react.ts +12 -0
  39. package/src/adapters/solid.ts +22 -0
  40. package/src/adapters/svelte.ts +28 -0
  41. package/src/adapters/vue.ts +24 -0
  42. package/src/build/icons.ts +60 -0
  43. package/src/client/index.ts +3 -0
  44. package/src/client/plugin.ts +11 -0
  45. package/src/client/push.ts +37 -0
  46. package/src/client/store.ts +174 -0
  47. package/src/env.d.ts +4 -0
  48. package/src/index.ts +12 -0
  49. package/src/module.ts +110 -0
  50. package/src/options.ts +55 -0
  51. package/src/server/encrypt.ts +84 -0
  52. package/src/server/index.ts +2 -0
  53. package/src/server/push.ts +146 -0
  54. package/src/server/vapid.ts +32 -0
  55. package/src/types.ts +17 -0
@@ -0,0 +1,146 @@
1
+ import { fromBase64Url, privateAddress, toBase64Url } from "hamur/server/internal"
2
+ import { encryptPayload, importPublicKey, MAX_PAYLOAD } from "./encrypt.ts"
3
+ import { vapidAuthorization } from "./vapid.ts"
4
+
5
+ type Urgency = "very-low" | "low" | "normal" | "high"
6
+
7
+ interface PushSubscriptionData {
8
+ endpoint: string
9
+ keys: { p256dh: string; auth: string }
10
+ }
11
+
12
+ interface SendPushOptions {
13
+ vapid: { subject: string; publicKey: string; privateKey: string }
14
+ ttl?: number
15
+ urgency?: Urgency
16
+ topic?: string
17
+ /** Milliseconds the push service has to answer, default 10000. */
18
+ timeout?: number
19
+ /** Accepts `http:` endpoints and local or private hosts, for a push service in tests. */
20
+ allowInsecureEndpoint?: boolean
21
+ }
22
+
23
+ const URGENCIES: readonly string[] = ["very-low", "low", "normal", "high"]
24
+ const MAX_TTL = 2_419_200
25
+ const TOPIC = /^[A-Za-z0-9_-]{1,32}$/
26
+ const AUTH_BYTES = 16
27
+ const PRIVATE_BYTES = 32
28
+ const DEFAULT_TIMEOUT = 10_000
29
+ const IPV4 = /^\d{1,3}(?:\.\d{1,3}){3}$/
30
+
31
+ const encoder = new TextEncoder()
32
+ const shown = (value: unknown): string =>
33
+ typeof value === "number" ? String(value) : (JSON.stringify(value) ?? String(value))
34
+ const isObject = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null
35
+ const bytesOf = (value: unknown) => (typeof value === "string" ? fromBase64Url(value) : undefined)
36
+
37
+ function fail(message: string): never {
38
+ throw new TypeError(`sendPush: ${message}`)
39
+ }
40
+
41
+ function subjectOf(subject: unknown): string {
42
+ const url = typeof subject === "string" && URL.canParse(subject) ? new URL(subject) : undefined
43
+ if (!url || !((url.protocol === "mailto:" && url.pathname !== "") || (url.protocol === "https:" && url.host !== "")))
44
+ fail(`vapid.subject must be a mailto: or https: URL (got ${shown(subject)})`)
45
+ return subject as string
46
+ }
47
+
48
+ /** URL parsing normalises every IPv4 spelling to dotted form, so a literal is caught here without DNS, which Workers lack. */
49
+ function localHost(hostname: string): boolean {
50
+ if (hostname === "localhost" || hostname.endsWith(".localhost")) return true
51
+ return (hostname.startsWith("[") || IPV4.test(hostname)) && privateAddress(hostname)
52
+ }
53
+
54
+ function endpointOf(endpoint: unknown, insecure: boolean): URL {
55
+ const url = typeof endpoint === "string" && URL.canParse(endpoint) ? new URL(endpoint) : undefined
56
+ if (insecure) {
57
+ if (!url || (url.protocol !== "https:" && url.protocol !== "http:"))
58
+ fail("subscription.endpoint must be an http: or https: URL")
59
+ return url
60
+ }
61
+ if (!url || url.protocol !== "https:") fail("subscription.endpoint must be an https: URL")
62
+ if (localHost(url.hostname))
63
+ fail(`subscription.endpoint must not be a local or private address (got host ${shown(url.hostname)})`)
64
+ return url
65
+ }
66
+
67
+ const typeOf = (value: unknown): string => (value === null ? "null" : Array.isArray(value) ? "an array" : typeof value)
68
+
69
+ /** One push message, encrypted with RFC 8291 and signed with RFC 8292 VAPID, posted to the subscription's endpoint. */
70
+ export async function sendPush(
71
+ subscription: PushSubscriptionData,
72
+ payload: string | Uint8Array | null,
73
+ options: SendPushOptions,
74
+ ): Promise<{ status: number; gone: boolean }> {
75
+ const {
76
+ vapid,
77
+ ttl = 86_400,
78
+ urgency = "normal",
79
+ topic,
80
+ timeout = DEFAULT_TIMEOUT,
81
+ allowInsecureEndpoint = false,
82
+ } = options ?? ({} as SendPushOptions)
83
+ const subject = subjectOf(isObject(vapid) ? vapid.subject : undefined)
84
+ const vapidPublic = bytesOf(vapid.publicKey)
85
+ if (!(await importPublicKey(vapidPublic))) fail("vapid.publicKey must be a base64url P-256 public key")
86
+ if (bytesOf(vapid.privateKey)?.length !== PRIVATE_BYTES)
87
+ fail("vapid.privateKey must be a base64url P-256 private key")
88
+ const endpoint = endpointOf(
89
+ isObject(subscription) ? subscription.endpoint : undefined,
90
+ allowInsecureEndpoint === true,
91
+ )
92
+ const keys: Record<string, unknown> = isObject(subscription) && isObject(subscription.keys) ? subscription.keys : {}
93
+ const receiverPublic = bytesOf(keys.p256dh)
94
+ const receiverKey = await importPublicKey(receiverPublic)
95
+ if (!receiverKey) fail("subscription.keys.p256dh must be a base64url P-256 public key")
96
+ const auth = bytesOf(keys.auth)
97
+ if (auth?.length !== AUTH_BYTES) fail("subscription.keys.auth must be 16 bytes in base64url")
98
+ if (!Number.isInteger(ttl) || ttl < 0 || ttl > MAX_TTL)
99
+ fail(`ttl must be an integer from 0 to ${MAX_TTL} (got ${shown(ttl)})`)
100
+ if (!URGENCIES.includes(urgency))
101
+ fail(`urgency must be "very-low", "low", "normal" or "high" (got ${shown(urgency)})`)
102
+ if (topic !== undefined && !(typeof topic === "string" && TOPIC.test(topic)))
103
+ fail(`topic must be at most 32 characters of A–Z, a–z, 0–9, - and _ (got ${shown(topic)})`)
104
+ if (!Number.isInteger(timeout) || timeout <= 0)
105
+ fail(`timeout must be a positive integer of milliseconds (got ${shown(timeout)})`)
106
+ if (!(typeof payload === "string" || payload instanceof Uint8Array || payload === null))
107
+ fail(`payload must be a string, a Uint8Array or null (got ${typeOf(payload)})`)
108
+ const plaintext = typeof payload === "string" ? encoder.encode(payload) : payload
109
+ if (plaintext && plaintext.length > MAX_PAYLOAD)
110
+ throw new RangeError(
111
+ `sendPush: the payload is ${plaintext.length} bytes; a push message holds at most ${MAX_PAYLOAD}`,
112
+ )
113
+
114
+ let authorization: string
115
+ try {
116
+ authorization = await vapidAuthorization(endpoint, subject, vapidPublic!, toBase64Url(bytesOf(vapid.privateKey)!))
117
+ } catch (error) {
118
+ if (error instanceof TypeError) fail("vapid.privateKey must be a base64url P-256 private key")
119
+ throw error
120
+ }
121
+ const headers = new Headers({ authorization, ttl: String(ttl), urgency })
122
+ if (topic !== undefined) headers.set("topic", topic)
123
+ let body: Uint8Array<ArrayBuffer> | undefined
124
+ if (plaintext) {
125
+ body = await encryptPayload(plaintext, { publicKey: receiverPublic!, key: receiverKey, auth })
126
+ headers.set("content-encoding", "aes128gcm")
127
+ headers.set("content-type", "application/octet-stream")
128
+ }
129
+ let response: Response
130
+ try {
131
+ // A push service answers 201; a redirect is reported as its status, never followed with the VAPID token to another host.
132
+ response = await fetch(endpoint, {
133
+ method: "POST",
134
+ headers,
135
+ redirect: "manual",
136
+ signal: AbortSignal.timeout(timeout),
137
+ ...(body ? { body } : {}),
138
+ })
139
+ } catch (error) {
140
+ if ((error as Error)?.name === "TimeoutError")
141
+ throw new Error(`sendPush: the push service did not answer within ${timeout} ms`)
142
+ throw error
143
+ }
144
+ await response.body?.cancel().catch(() => undefined)
145
+ return { status: response.status, gone: response.status === 404 || response.status === 410 }
146
+ }
@@ -0,0 +1,32 @@
1
+ import { signJWT } from "hamur/server"
2
+ import { toBase64Url } from "hamur/server/internal"
3
+
4
+ export const VAPID_LIFETIME = 12 * 60 * 60
5
+
6
+ export async function generateVapidKeys(): Promise<{ publicKey: string; privateKey: string }> {
7
+ const pair = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [
8
+ "sign",
9
+ "verify",
10
+ ])) as CryptoKeyPair
11
+ const publicKey = new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey))
12
+ const { d } = await crypto.subtle.exportKey("jwk", pair.privateKey)
13
+ return { publicKey: toBase64Url(publicKey), privateKey: d! }
14
+ }
15
+
16
+ /** RFC 8292 §2 and §3: an ES256 JWT for the endpoint's origin, sent with the public key as `vapid t=<jwt>, k=<key>`. */
17
+ export async function vapidAuthorization(
18
+ endpoint: URL,
19
+ subject: string,
20
+ publicKey: Uint8Array<ArrayBuffer>,
21
+ privateKey: string,
22
+ ): Promise<string> {
23
+ const jwk: JsonWebKey = {
24
+ kty: "EC",
25
+ crv: "P-256",
26
+ x: toBase64Url(publicKey.subarray(1, 33)),
27
+ y: toBase64Url(publicKey.subarray(33, 65)),
28
+ d: privateKey,
29
+ }
30
+ const token = await signJWT({ aud: endpoint.origin, sub: subject }, jwk, { alg: "ES256", expiresIn: VAPID_LIFETIME })
31
+ return `vapid t=${token}, k=${toBase64Url(publicKey)}`
32
+ }
package/src/types.ts ADDED
@@ -0,0 +1,17 @@
1
+ /** Icons made from one source image. */
2
+ export interface PwaIcons {
3
+ /** A PNG, JPEG or WebP file from `rootDir`, square and at least as large as the largest size. */
4
+ source: string
5
+ /** A second source drawn with the safe zone of a maskable icon; the plain source is never padded. */
6
+ maskable?: string
7
+ /** Default `[192, 512]`. */
8
+ sizes?: number[]
9
+ /** Default `true`: a 180 px `apple-touch-icon`, unless `app/apple-icon.*` exists. */
10
+ apple?: boolean
11
+ }
12
+
13
+ /** The `pwa` config key. */
14
+ export interface PwaOptions {
15
+ registerType?: "prompt" | "autoUpdate"
16
+ icons?: PwaIcons | false
17
+ }