@protobase/cli 0.45.19 → 0.45.20
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/dist/build/service-worker-code.js +7 -4
- package/dist/build/service-worker-push-code.js +123 -0
- package/dist/cli/package.js +1 -1
- package/dist/dev/entry.js +2 -1
- package/dist/dev/run.js +1 -1
- package/dist/dev/service-worker-route.js +18 -0
- package/package.json +6 -6
- package/skills/protobase/references/features/notifications.md +2 -2
- package/skills/protobase/references/reference/notifications.md +44 -12
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { faviconFile } from "./favicon.js";
|
|
2
2
|
import { themeFile } from "./theme.js";
|
|
3
|
+
import { pushHandlersCode } from "./service-worker-push-code.js";
|
|
4
|
+
import { serviceWorkerFile as serviceWorkerFile$1 } from "@protobase/schema/internal";
|
|
3
5
|
//#region src/build/service-worker-code.ts
|
|
4
|
-
/** The service worker's file in the shell, at the root so it may answer the whole origin. */
|
|
5
|
-
const serviceWorkerFile = "protobase.sw.js";
|
|
6
6
|
/**
|
|
7
7
|
* The shell's service worker, which makes the admin app open without a network and then say the API is unreachable;
|
|
8
8
|
* data is never cached. A build of the shell names its own `version`, so a new shell's worker replaces the old one and
|
|
@@ -13,6 +13,8 @@ const serviceWorkerFile = "protobase.sw.js";
|
|
|
13
13
|
* - The content-hashed assets under /assets come from the cache, filled as the app loads them.
|
|
14
14
|
* - The project's theme and favicon go to the network, the cached copy standing in when it fails.
|
|
15
15
|
* - Everything else, the API above all, never reaches the worker's cache.
|
|
16
|
+
*
|
|
17
|
+
* It also shows push notifications and opens them on tap (see `pushHandlersCode`).
|
|
16
18
|
*/
|
|
17
19
|
const serviceWorkerCode = ({ version, precache }) => `const cacheName = ${JSON.stringify(`protobase-shell-${version}`)}
|
|
18
20
|
const precache = ${JSON.stringify(precache)}
|
|
@@ -47,6 +49,7 @@ self.addEventListener('fetch', (event) => {
|
|
|
47
49
|
else if (url.pathname.startsWith('/assets/')) event.respondWith(fromCache(request))
|
|
48
50
|
else if (revalidated.includes(url.pathname)) event.respondWith(fromNetwork(request, request))
|
|
49
51
|
})
|
|
50
|
-
|
|
52
|
+
|
|
53
|
+
${pushHandlersCode}`;
|
|
51
54
|
//#endregion
|
|
52
|
-
export { serviceWorkerCode, serviceWorkerFile };
|
|
55
|
+
export { serviceWorkerCode, serviceWorkerFile$1 as serviceWorkerFile };
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { pushRecord } from "@protobase/schema/internal";
|
|
2
|
+
//#region src/build/service-worker-push-code.ts
|
|
3
|
+
/**
|
|
4
|
+
* The service worker's push handlers, in the shell's worker and as all of `protobase dev`'s. Nothing in it is a secret:
|
|
5
|
+
* the worker learns the user this browser is registered for from the record the push helper keeps (`pushRecord`).
|
|
6
|
+
*
|
|
7
|
+
* - `push` shows the notification's title, body and tag, and sets the app's badge to its number, only while the record
|
|
8
|
+
* names the subscription's endpoint and the push names the record's user. A push without a title shows the app's
|
|
9
|
+
* name alone. A push with no record, or for another endpoint or user, shows nothing: the worker closes what it showed,
|
|
10
|
+
* clears the badge, drops the record and unsubscribes.
|
|
11
|
+
* - `notificationclick` opens the notification's url only when it is an absolute `http` or `https` URL, parsed without
|
|
12
|
+
* a base: on the worker's own origin in a window of the app, focused and navigated there, or in a new window when none
|
|
13
|
+
* is open; on any other origin always in a new window. Anything else opens nothing, whoever showed the notification.
|
|
14
|
+
* - `pushsubscriptionchange` marks an existing record for renewal, which the helper registers once its user is signed
|
|
15
|
+
* in; the worker has no token to do so itself.
|
|
16
|
+
*/
|
|
17
|
+
const pushHandlersCode = `const pushRecord = ${JSON.stringify(pushRecord)}
|
|
18
|
+
|
|
19
|
+
const pushRecordRequest = (mode, act) => new Promise((resolve, reject) => {
|
|
20
|
+
const opened = self.indexedDB.open(pushRecord.database, 1)
|
|
21
|
+
opened.onupgradeneeded = () => opened.result.createObjectStore(pushRecord.store)
|
|
22
|
+
opened.onerror = () => reject(opened.error)
|
|
23
|
+
opened.onsuccess = () => {
|
|
24
|
+
const db = opened.result
|
|
25
|
+
const request = act(db.transaction(pushRecord.store, mode).objectStore(pushRecord.store))
|
|
26
|
+
request.onsuccess = () => (db.close(), resolve(request.result))
|
|
27
|
+
request.onerror = () => (db.close(), reject(request.error))
|
|
28
|
+
}
|
|
29
|
+
})
|
|
30
|
+
const readPushRecord = () => pushRecordRequest('readonly', (store) => store.get(pushRecord.key))
|
|
31
|
+
const writePushRecord = (record) => pushRecordRequest('readwrite', (store) => store.put(record, pushRecord.key))
|
|
32
|
+
const dropPushRecord = () => pushRecordRequest('readwrite', (store) => store.delete(pushRecord.key))
|
|
33
|
+
|
|
34
|
+
// No whitespace or control character, which a URL parser drops silently, so java\\tscript: cannot pass as javascript:.
|
|
35
|
+
const plainUrl = /^[^\\s\\u0000-\\u001f\\u007f-\\u009f]+$/
|
|
36
|
+
|
|
37
|
+
const tapUrl = (value) => {
|
|
38
|
+
if (typeof value !== 'string' || value.length > 2048 || !plainUrl.test(value)) return undefined
|
|
39
|
+
let url
|
|
40
|
+
try {
|
|
41
|
+
url = new URL(value)
|
|
42
|
+
} catch (error) {
|
|
43
|
+
if (error instanceof TypeError) return undefined
|
|
44
|
+
throw error
|
|
45
|
+
}
|
|
46
|
+
return url.protocol === 'https:' || url.protocol === 'http:' ? url.href : undefined
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const pushData = (data) => {
|
|
50
|
+
if (!data) return undefined
|
|
51
|
+
let value
|
|
52
|
+
try {
|
|
53
|
+
value = data.json()
|
|
54
|
+
} catch (error) {
|
|
55
|
+
if (error instanceof SyntaxError) return undefined
|
|
56
|
+
throw error
|
|
57
|
+
}
|
|
58
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const text = (value) => (typeof value === 'string' ? value : undefined)
|
|
62
|
+
|
|
63
|
+
// This browser is no longer registered for anyone: nothing it showed stays, and it gets no more pushes.
|
|
64
|
+
const forgetPush = async () => {
|
|
65
|
+
for (const shown of await self.registration.getNotifications()) shown.close()
|
|
66
|
+
if (self.navigator.clearAppBadge) await self.navigator.clearAppBadge()
|
|
67
|
+
await dropPushRecord()
|
|
68
|
+
const subscription = await self.registration.pushManager.getSubscription()
|
|
69
|
+
if (subscription) await subscription.unsubscribe()
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const showPush = async (data) => {
|
|
73
|
+
const [record, subscription] = await Promise.all([readPushRecord(), self.registration.pushManager.getSubscription()])
|
|
74
|
+
if (!record || !subscription || record.endpoint !== subscription.endpoint) return forgetPush()
|
|
75
|
+
const push = pushData(data)
|
|
76
|
+
if (!push || text(push.title) === undefined) return self.registration.showNotification(text(record.appName) || self.location.host, {})
|
|
77
|
+
if (push.user !== record.userId) return forgetPush()
|
|
78
|
+
const url = tapUrl(push.url)
|
|
79
|
+
const options = {}
|
|
80
|
+
if (text(push.body) !== undefined) options.body = push.body
|
|
81
|
+
if (text(push.tag) !== undefined) options.tag = push.tag
|
|
82
|
+
if (url !== undefined) options.data = { url }
|
|
83
|
+
if (typeof push.badge === 'number' && self.navigator.setAppBadge) await self.navigator.setAppBadge(push.badge)
|
|
84
|
+
return self.registration.showNotification(push.title, options)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// A window of the app navigated to the url as a page load; a window the worker cannot navigate gets a new one instead.
|
|
88
|
+
const openInApp = async (url) => {
|
|
89
|
+
const windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true })
|
|
90
|
+
const open = windows.find((client) => new URL(client.url).origin === self.location.origin)
|
|
91
|
+
if (!open) return self.clients.openWindow(url)
|
|
92
|
+
try {
|
|
93
|
+
const focused = await open.focus()
|
|
94
|
+
return await focused.navigate(url)
|
|
95
|
+
} catch (error) {
|
|
96
|
+
if (error instanceof TypeError) return self.clients.openWindow(url)
|
|
97
|
+
throw error
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const openTap = (notification) => {
|
|
102
|
+
notification.close()
|
|
103
|
+
const url = tapUrl(notification.data && notification.data.url)
|
|
104
|
+
if (url === undefined) return Promise.resolve()
|
|
105
|
+
return new URL(url).origin === self.location.origin ? openInApp(url) : self.clients.openWindow(url)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
self.addEventListener('push', (event) => event.waitUntil(showPush(event.data)))
|
|
109
|
+
self.addEventListener('notificationclick', (event) => event.waitUntil(openTap(event.notification)))
|
|
110
|
+
self.addEventListener('pushsubscriptionchange', (event) => {
|
|
111
|
+
event.waitUntil(readPushRecord().then((record) => record && writePushRecord({ ...record, renew: true })))
|
|
112
|
+
})
|
|
113
|
+
`;
|
|
114
|
+
/**
|
|
115
|
+
* The worker `protobase dev` serves when the app has `notifications()`: the push handlers alone, taking over the open
|
|
116
|
+
* pages at once so a tap can navigate them. It caches nothing.
|
|
117
|
+
*/
|
|
118
|
+
const devServiceWorkerCode = `self.addEventListener('install', () => self.skipWaiting())
|
|
119
|
+
self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim()))
|
|
120
|
+
|
|
121
|
+
${pushHandlersCode}`;
|
|
122
|
+
//#endregion
|
|
123
|
+
export { devServiceWorkerCode, pushHandlersCode };
|
package/dist/cli/package.js
CHANGED
package/dist/dev/entry.js
CHANGED
|
@@ -3,6 +3,7 @@ import { devJobs } from "./dev-jobs.js";
|
|
|
3
3
|
import { projectErrorReporter } from "../project/error-reporter.js";
|
|
4
4
|
import { projectAdmin } from "../project/project-admin.js";
|
|
5
5
|
import { loadProject, projectDb } from "./project.js";
|
|
6
|
+
import { withDevServiceWorker } from "./service-worker-route.js";
|
|
6
7
|
import { setMissing, supabaseEnv } from "./supabase-env.js";
|
|
7
8
|
import { apiKeySettings, assistantSettings, authStoreTables, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkNotificationsSchema, checkQueryRunner, checkWebhooksSchema, configExports, hasUsers } from "@protobase/server";
|
|
8
9
|
import { upgradeWebSocket } from "@hono/node-server";
|
|
@@ -47,7 +48,7 @@ const { admin, jobs } = projectAdmin({
|
|
|
47
48
|
authenticate: project.authenticate
|
|
48
49
|
}, project.exports, db, ui, reporter, upgradeWebSocket);
|
|
49
50
|
await devJobs(db, jobs);
|
|
50
|
-
var entry_default = new Hono().route("/", admin);
|
|
51
|
+
var entry_default = withDevServiceWorker(new Hono(), Boolean(project.notifications)).route("/", admin);
|
|
51
52
|
if (project.auth && !store.__protobaseNoUsersShown) {
|
|
52
53
|
store.__protobaseNoUsersShown = true;
|
|
53
54
|
hasUsers(project.auth).then((any) => {
|
package/dist/dev/run.js
CHANGED
|
@@ -98,7 +98,7 @@ const runDev = async (options, out) => {
|
|
|
98
98
|
tailwindcss(),
|
|
99
99
|
devServer({
|
|
100
100
|
entry,
|
|
101
|
-
exclude: [/^(?!\/api(\/|\?|$)|\/\.well-known\/webauthn(\?|$)|\/\.well-known\/oauth-(authorization-server|protected-resource)(\/|\?|$)).*/],
|
|
101
|
+
exclude: [/^(?!\/api(\/|\?|$)|\/\.well-known\/webauthn(\?|$)|\/\.well-known\/oauth-(authorization-server|protected-resource)(\/|\?|$)|\/protobase\.sw\.js(\?|$)).*/],
|
|
102
102
|
injectClientScript: false
|
|
103
103
|
})
|
|
104
104
|
]
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { devServiceWorkerCode } from "../build/service-worker-push-code.js";
|
|
2
|
+
import { serviceWorkerFile } from "@protobase/schema/internal";
|
|
3
|
+
//#region src/dev/service-worker-route.ts
|
|
4
|
+
/** Where `protobase dev` serves its worker, as the built shell serves its own. */
|
|
5
|
+
const devServiceWorkerPath = `/${serviceWorkerFile}`;
|
|
6
|
+
/**
|
|
7
|
+
* Serves `protobase dev`'s worker, the push handlers alone (see `devServiceWorkerCode`), when the app has
|
|
8
|
+
* `notifications()`, so push can be tried in development; without them the path is unknown and no worker registers.
|
|
9
|
+
*/
|
|
10
|
+
const withDevServiceWorker = (app, notifications) => {
|
|
11
|
+
if (notifications) app.get(devServiceWorkerPath, (c) => c.body(devServiceWorkerCode, 200, {
|
|
12
|
+
"content-type": "text/javascript; charset=utf-8",
|
|
13
|
+
"cache-control": "no-cache"
|
|
14
|
+
}));
|
|
15
|
+
return app;
|
|
16
|
+
};
|
|
17
|
+
//#endregion
|
|
18
|
+
export { devServiceWorkerPath, withDevServiceWorker };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/cli",
|
|
3
|
-
"version": "0.45.
|
|
3
|
+
"version": "0.45.20",
|
|
4
4
|
"description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -36,11 +36,11 @@
|
|
|
36
36
|
"@better-auth/core": "^1.7.12",
|
|
37
37
|
"@hono/node-server": "^2.1.3",
|
|
38
38
|
"@hono/vite-dev-server": "^0.26.1",
|
|
39
|
-
"@protobase/layout": "0.45.
|
|
40
|
-
"@protobase/query": "0.45.
|
|
41
|
-
"@protobase/schema": "0.45.
|
|
42
|
-
"@protobase/server": "0.45.
|
|
43
|
-
"@protobase/ui": "0.45.
|
|
39
|
+
"@protobase/layout": "0.45.20",
|
|
40
|
+
"@protobase/query": "0.45.20",
|
|
41
|
+
"@protobase/schema": "0.45.20",
|
|
42
|
+
"@protobase/server": "0.45.20",
|
|
43
|
+
"@protobase/ui": "0.45.20",
|
|
44
44
|
"@react-email/render": "^2.1.0",
|
|
45
45
|
"@scalar/hono-api-reference": "^0.12.10",
|
|
46
46
|
"@tailwindcss/vite": "^4.3.3",
|
|
@@ -5,12 +5,12 @@
|
|
|
5
5
|
A bell in the top bar and push to browsers and phones, for what your app tells its users.
|
|
6
6
|
|
|
7
7
|
- [Notifications](../reference/notifications.md#turning-them-on) (in development): `extends: [notifications()]` gives every signed-in user a bell in the top bar and push to their browsers and phones; `ui: false` keeps only the backend.
|
|
8
|
-
- [Devices](../reference/notifications.md#devices) (
|
|
8
|
+
- [Devices](../reference/notifications.md#devices) (beta): Each signed-in user registers their own browsers and phones to receive push, and a device gets it only while the sign-in it was registered in lasts.
|
|
9
9
|
- [Your own parts](../reference/notifications.md#your-own-parts) (in development): Senders, the device store, the history store and the bell can each be replaced by your own, such as a store outside the database.
|
|
10
10
|
- [Table names](../reference/notifications.md#table-names) (beta): The built-in stores' schema, tables and columns can be renamed, as auth's users table can.
|
|
11
11
|
- [Sending notifications](../reference/notifications.md#sending) (beta): Your code sends a notification to users or to devices as a background job, queued in the same transaction as a write, and says on each one whether it shows in the inbox.
|
|
12
12
|
- [Notification history](../reference/notifications.md#history) (beta): Each user's inbox notifications are kept with when they were read, and the API lists them, counts the unread ones and marks them read.
|
|
13
|
-
- [Web Push](../reference/notifications.md#web-push) (
|
|
13
|
+
- [Web Push](../reference/notifications.md#web-push) (beta): Notifications reach desktop and Android browsers and home-screen web apps on iPhone through Web Push, with keys you generate.
|
|
14
14
|
- Push on Android (coming soon): Notifications reach the Android build of the app on a user's phones.
|
|
15
15
|
- Push on iOS (coming soon): Notifications reach the iOS build of the app on a user's iPhones and iPads.
|
|
16
16
|
- Notification bell (coming soon): A bell in the top bar shows a user's unread notifications and lists the latest.
|
|
@@ -7,7 +7,7 @@ Turn on notifications, send them to users or devices, let each signed-in user re
|
|
|
7
7
|
## Turning them on
|
|
8
8
|
|
|
9
9
|
:::caution[In development]
|
|
10
|
-
Sending keeps notifications in the history and pushes them to browsers
|
|
10
|
+
Sending keeps notifications in the history and pushes them to browsers; push on Android and iOS and the bell are coming soon.
|
|
11
11
|
:::
|
|
12
12
|
|
|
13
13
|
Notifications tell a user about something in the app, in a bell in the top bar and as push on their devices. You turn them on in `protobase.config.ts`:
|
|
@@ -23,11 +23,11 @@ export default defineConfig({
|
|
|
23
23
|
|
|
24
24
|
Then run `protobase migration`, which writes the [devices and history tables](#table-names), and the jobs schema that [sending](#sending) runs on, as a migration of the project's own, and apply it with the project's migrations. `protobase dev` and `protobase serve` refuse to start while a table is missing or lacks what notifications need, and name it. Without `notifications()` there is none of it: no endpoints, no tables and no migration.
|
|
25
25
|
|
|
26
|
-
|
|
26
|
+
Browsers receive push through [Web Push](#web-push); the bell, and push on Android and iOS, are coming soon. `notifications({ ui: false })` keeps only the backend, without the bell.
|
|
27
27
|
|
|
28
28
|
## Devices
|
|
29
29
|
|
|
30
|
-
:::caution[
|
|
30
|
+
:::caution[Beta]
|
|
31
31
|
Only browsers receive push yet, through [Web Push](#web-push): push on Android and iOS is coming soon.
|
|
32
32
|
:::
|
|
33
33
|
|
|
@@ -49,14 +49,19 @@ The body of a register is JSON (`Content-Type: application/json`, at most 8 KB),
|
|
|
49
49
|
{ "kind": "fcm", "token": "…", "appId": "net.example.app" }
|
|
50
50
|
```
|
|
51
51
|
|
|
52
|
-
A field that does not belong to the kind, a missing one, an unknown one such as
|
|
52
|
+
A field that does not belong to the kind, a missing one, an unknown one such as an owner, or a value out of its format is a `400` that names the field and stores nothing. A browser's `endpoint` must be an https URL on one of the browsers' push services. `environment` is `sandbox` or `production`, and `userAgent`, optional for every kind, is at most 512 characters. The stored device keeps `null` in the fields its kind does not have.
|
|
53
|
+
|
|
54
|
+
`userId`, optional for every kind, names the user the client registers for, such as the one whose click turned push on. When someone else is signed in by the time the request arrives, it is a `409` of type `other-user` that stores nothing.
|
|
53
55
|
|
|
54
56
|
Who may call them:
|
|
55
57
|
|
|
56
58
|
- Only someone signed in as themselves, with the token of their own sign-in. Visitors are refused with a `401`, and staff signed in as the user, outside apps acting for the user (such as an MCP client) and tokens minted with `issueToken` with a `403`.
|
|
57
59
|
- An app with its own `authenticate` marks a user's own sign-in on the session it returns, `signIn: { staff: false }`; without that mark, its sessions are refused.
|
|
60
|
+
- With Protobase's auth, every token the endpoints take names its sign-in session; one that names none is refused with a `403`.
|
|
61
|
+
|
|
62
|
+
A device is one token, or one endpoint for a browser. An Android or iOS token someone else had moves to the caller, as a new device with a new id that keeps nothing of the previous user's, so a shared phone notifies whoever signed in on it last. A browser's endpoint never moves: registering one another user holds is a `409` of type `device-held` that stores nothing, and the browser subscribes again for a new endpoint, as [the browser helper](#in-the-browser) does. A user keeps up to 20 devices: registering one more removes their least recently seen. Deleting a user removes their devices.
|
|
58
63
|
|
|
59
|
-
|
|
64
|
+
With Protobase's auth, a device belongs to the sign-in session it was registered in. Once that session ends, the device gets no more push and is removed at the next send: when the user signs out, someone signs in on the same browser, the user signs out everywhere, a password change signs out their other devices, an admin ends their sessions or bans them, or the session expires. Registering the device again ties it to the session of that request, which the browser helper does on its own for the same user. With an app's own `authenticate`, a device stays its user's until it is removed with `DELETE`.
|
|
60
65
|
|
|
61
66
|
The path comes from `devicesPath('/api', id)`, and the name of its id parameter from `deviceIdParam`, both exported by `@protobase/server`.
|
|
62
67
|
|
|
@@ -106,7 +111,7 @@ The text you send shows on lock screens, where anyone holding the device can rea
|
|
|
106
111
|
|
|
107
112
|
A send checks no permission. A device send reaches the devices whatever user holds them. So check ids taken from a request against the caller first, such as a device id against the caller's own devices.
|
|
108
113
|
|
|
109
|
-
A user send reaches the user's devices as they are when the job runs. A device that moved to someone else, or was removed, gets nothing.
|
|
114
|
+
A user send reaches the user's devices as they are when the job runs. A device that moved to someone else, or was removed, gets nothing. With Protobase's auth, a device whose sign-in session has [ended](#devices) is removed instead; a send whose devices' sessions cannot be read pushes to none of them and is retried. With an app's own `authenticate`, a device keeps receiving its user's notifications until it is removed. When a push service reports a device gone, the device is removed. A device whose push service asks to try again later is tried once more, on the job's next try, and then given up on without being removed. <gap>A push service's own wait before a retry cannot set when the device is tried again because retries follow the job's backoff and timing them per device is not implemented.</gap> A sender that fails is retried with its devices, up to 5 tries of the job. Devices of a kind without a sender are skipped. Without any sender, a send for the inbox is kept in the history and a send that is not does nothing.
|
|
110
115
|
|
|
111
116
|
## History
|
|
112
117
|
|
|
@@ -135,8 +140,8 @@ The paths come from `historyPath('/api')`, `historyPath('/api', 'unread')`, `his
|
|
|
135
140
|
|
|
136
141
|
## Web Push
|
|
137
142
|
|
|
138
|
-
:::caution[
|
|
139
|
-
|
|
143
|
+
:::caution[Beta]
|
|
144
|
+
On iPhone and iPad, a browser tab gets no push; the app added to the Home Screen does. The ready-made button is coming soon with the bell.
|
|
140
145
|
:::
|
|
141
146
|
|
|
142
147
|
Browsers receive push through the Web Push protocol: desktop and Android browsers, and web apps added to the home screen on iPhone. You generate a key pair with the CLI and set it, with a contact address, in three environment variables:
|
|
@@ -155,7 +160,31 @@ Without them Web Push is off and the app has no sender for browsers. One or two
|
|
|
155
160
|
|
|
156
161
|
The private key is a secret: keep it out of client code, `VITE_` variables and the repository. Anyone holding it and the stored subscriptions can push to every subscribed browser. Browsers subscribe with the public key, which `/meta` gives every caller as `notifications.webPushKey`, so a new key pair breaks every subscription until its browser registers again.
|
|
157
162
|
|
|
158
|
-
Each message is encrypted for its browser and signed with the key. It goes only to an endpoint on one of the browsers' push services, never through a redirect; a device stored with any other endpoint, or with keys that are not a subscription's, is `refused`. <gap>Web Push cannot deliver to a push service outside the browsers' own because adding one to the list is not implemented.</gap> A message's `platform.web` sets the request's `ttl`, `urgency` and `topic` and fields merged into the JSON the browser receives (`payload`), in place of those built from the message; every URL in that JSON is checked as the message's `url` is. The JSON carries at most 3993 bytes.
|
|
163
|
+
Each message is encrypted for its browser and signed with the key. It goes only to an endpoint on one of the browsers' push services, never through a redirect; a device stored with any other endpoint, or with keys that are not a subscription's, is `refused`. <gap>Web Push cannot deliver to a push service outside the browsers' own because adding one to the list is not implemented.</gap> A message's `platform.web` sets the request's `ttl`, `urgency` and `topic` and fields merged into the JSON the browser receives (`payload`), in place of those built from the message; every URL in that JSON is checked as the message's `url` is. The JSON also carries `user`, the id of the user the device is registered for, over any `user` in `payload`, and at most 3993 bytes.
|
|
164
|
+
|
|
165
|
+
### In the browser
|
|
166
|
+
|
|
167
|
+
`usePushNotifications()` from `@protobase/ui` turns push on and off for the signed-in user in this browser, for your own button or menu item. Its `state` tells whether push is `on`, `off`, `blocked` because the user refused notifications in the browser's settings, or `unsupported`, and `loading` until it knows. Hide the button while it is `unsupported`: the browser has no Web Push, the app has no VAPID keys, or it runs in the Android or iOS app.
|
|
168
|
+
|
|
169
|
+
```tsx
|
|
170
|
+
import { Button, usePushNotifications } from '@protobase/ui'
|
|
171
|
+
|
|
172
|
+
export const PushButton = () => {
|
|
173
|
+
const push = usePushNotifications()
|
|
174
|
+
if (push.state === 'loading' || push.state === 'unsupported') return null
|
|
175
|
+
if (push.state === 'blocked') return <p>Notifications are blocked in this browser's settings.</p>
|
|
176
|
+
if (push.state === 'on') return <Button onClick={() => void push.turnOff()}>Turn off notifications</Button>
|
|
177
|
+
return <Button onClick={() => void push.turnOn()}>Turn on notifications</Button>
|
|
178
|
+
}
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
- Call `turnOn` straight from a click. The browser asks for permission then, and only then: without a click nothing happens, and push is never turned on when a page loads. Once the user said no, `turnOn` does not ask again and answers `blocked`.
|
|
182
|
+
- Only someone signed in as themselves can turn push on: a visitor's click and staff signed in as the user do nothing.
|
|
183
|
+
- On iPhone and iPad, push works in the app added to the Home Screen; a browser tab answers `unsupported`.
|
|
184
|
+
- Signing out turns push off in this browser, and so does someone else signing in on it: what the browser showed is closed, the app's badge cleared, and the device removed. Signing in again as the same user keeps it on.
|
|
185
|
+
- A tap on a notification whose url is on your app's origin opens that page in the app, in an open window of it or a new one; any other url opens in a new tab.
|
|
186
|
+
|
|
187
|
+
`protobase serve` and `protobase dev` both serve the service worker that shows notifications, `protobase dev` only when the app has `notifications()`.
|
|
159
188
|
|
|
160
189
|
## Your own parts
|
|
161
190
|
|
|
@@ -169,7 +198,7 @@ The device store is an interface with a Postgres default, the [devices table](#t
|
|
|
169
198
|
import { defineConfig, notifications, type DeviceStore } from '@protobase/server'
|
|
170
199
|
|
|
171
200
|
const store: DeviceStore = {
|
|
172
|
-
register: async (userId, device) => { /* add
|
|
201
|
+
register: async (userId, device) => { /* add or refresh it, or move a phone's token to userId as a new device; undefined for a browser's endpoint another user holds */ },
|
|
173
202
|
remove: async (userId, id) => { /* only when the device is userId's */ },
|
|
174
203
|
listForUser: async (userId) => [],
|
|
175
204
|
listByIds: async (ids) => [],
|
|
@@ -180,7 +209,7 @@ const store: DeviceStore = {
|
|
|
180
209
|
export default defineConfig({ extends: [notifications({ store })] })
|
|
181
210
|
```
|
|
182
211
|
|
|
183
|
-
Every method takes and returns plain data: the user id as text, and devices as `{ id, userId, kind, token, p256dh, auth, environment, appId, userAgent, createdAt, lastSeenAt }`, with `token` the endpoint for a browser. A method given an empty user id, id or token throws. `listByIds` and `removeGone` act on any user's devices, for the code that sends; the endpoints never call them. A store missing a method stops startup, naming it.
|
|
212
|
+
Every method takes and returns plain data: the user id as text, and devices as `{ id, userId, kind, token, p256dh, auth, environment, appId, userAgent, sessionId, createdAt, lastSeenAt }`, with `token` the endpoint for a browser and `sessionId` the sign-in session it was registered in. A method given an empty user id, id or token throws. `listByIds` and `removeGone` act on any user's devices, for the code that sends; the endpoints never call them. A store missing a method stops startup, naming it.
|
|
184
213
|
|
|
185
214
|
When Protobase's auth deletes a user, by an admin or with `protobase users delete`, it calls the store's `removeAllForUser` before anything is deleted, so a store that throws stops the deletion, and once more afterwards. An app that deletes users otherwise calls `deviceStore(db, options).removeAllForUser(userId)` as it deletes one, with the options it gave `notifications()`.
|
|
186
215
|
|
|
@@ -244,7 +273,7 @@ A message is plain data:
|
|
|
244
273
|
| `urgency` | `very-low`, `low`, `normal` or `high` |
|
|
245
274
|
| `platform` | each protocol's own fields: `web`, `apns` and `fcm` |
|
|
246
275
|
|
|
247
|
-
`pushMessage(message)` checks a message and answers it as senders get it, or throws a `PushMessageError` that names the field at fault, never its value. Every sender gets a checked message: a `url` with any other scheme, such as `javascript:` or `data:`, or a relative one, is refused, and so is a field that is not one of the message's, a key `__proto__`, `constructor` or `prototype` anywhere in it, or text with control characters. A sender for `web` devices names the VAPID `publicKey` browsers subscribe with, which `/meta` gives every caller; it must be a P-256 public key in base64url.
|
|
276
|
+
`pushMessage(message)` checks a message and answers it as senders get it, or throws a `PushMessageError` that names the field at fault, never its value. Every sender gets a checked message: a `url` with any other scheme, such as `javascript:` or `data:`, or a relative one, is refused, and so is a field that is not one of the message's, a key `__proto__`, `constructor` or `prototype` anywhere in it, or text with control characters. A sender for `web` devices names the VAPID `publicKey` browsers subscribe with, which `/meta` gives every caller; it must be a P-256 public key in base64url. Its JSON carries the device's `userId` as `user`, as the built-in sender's does: the service worker shows nothing of a push for another user, or for none.
|
|
248
277
|
|
|
249
278
|
The bell is coming soon.
|
|
250
279
|
|
|
@@ -266,8 +295,11 @@ The default store keeps devices in the table `devices` of the schema `notificati
|
|
|
266
295
|
| `environment` | an iOS app's `sandbox` or `production` |
|
|
267
296
|
| `app_id` | the app's bundle id or package name |
|
|
268
297
|
| `user_agent` | what the device said it is |
|
|
298
|
+
| `session_id` | the id of the sign-in session it was registered in, never its token; `NULL` when the app's `authenticate` names none |
|
|
269
299
|
| `created_at`, `last_seen_at` | when the user registered it, and last refreshed it |
|
|
270
300
|
|
|
301
|
+
`protobase migration` adds `session_id` to a devices table written before devices kept their session.
|
|
302
|
+
|
|
271
303
|
You rename the schema, the table and each column, as auth takes `users.table` and `users.columns`, such as to keep devices in a table you already have:
|
|
272
304
|
|
|
273
305
|
```ts
|