@protobase/cli 0.45.18 → 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.
@@ -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 };
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.45.18";
2
+ var version = "0.45.20";
3
3
  //#endregion
4
4
  export { version };
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 };
@@ -11,7 +11,7 @@ const migrationParts = (project) => {
11
11
  title: authMigrationTitle,
12
12
  sql: () => authSchemaMigration(project.auth)
13
13
  }] : [],
14
- ...project.jobs.length > 0 || project.models.some(isCaptured) || comments || aiFields || project.webhooks ? [{
14
+ ...project.jobs.length > 0 || project.models.some(isCaptured) || comments || aiFields || project.webhooks || project.notifications ? [{
15
15
  name: "jobs",
16
16
  title: "The jobs schema this version of Protobase needs",
17
17
  sql: () => jobsSchemaMigration(project.db)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.45.18",
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.18",
40
- "@protobase/query": "0.45.18",
41
- "@protobase/schema": "0.45.18",
42
- "@protobase/server": "0.45.18",
43
- "@protobase/ui": "0.45.18",
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) (in development): Each signed-in user registers their own browsers and phones to receive push, and a device moves to whoever registers it next.
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
- - Sending notifications (coming soon): Your code tells a user, or several, about something in the app, and each gets it in the bell and on their devices.
12
- - [Notification history](../reference/notifications.md#history) (in development): 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) (in development): Notifications reach desktop and Android browsers and home-screen web apps on iPhone through Web Push, with keys you generate.
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
+ - [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) (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.
@@ -68,7 +68,7 @@ export default defineConfig({
68
68
  | --- | --- |
69
69
  | `name` | Letters, digits, `_`, `-`, `.` and `/`. Two jobs may not share a name. |
70
70
  | `payload` | A [Standard Schema](https://standardschema.dev) such as a zod schema, checked when the job is enqueued and again before it runs. A payload it refuses at run time fails the job for good. |
71
- | `run(payload, { db, job, signal, mail })` | The work. `db` is the app's pool: the enqueuer's transaction has committed by then. `job` holds its `id`, `name`, `attempt` and `maxAttempts`. `signal` aborts when the try times out or the worker shuts down. `mail` sends mail, see [Mail](#mail). |
71
+ | `run(payload, { db, job, signal, mail, sendNotification })` | The work. `db` is the app's pool: the enqueuer's transaction has committed by then. `job` holds its `id`, `name`, `attempt`, `maxAttempts` and `startedOn`, when this try took it. `signal` aborts when the try times out or the worker shuts down. `mail` sends mail, see [Mail](#mail). `sendNotification` sends a notification, see [Sending](notifications.md#sending); inside a transaction of `db`, a try that throws in it queues nothing. |
72
72
  | `maxAttempts` | Tries before the job is kept as failed; default 10. |
73
73
  | `retryDelay`, `maxRetryDelay` | The wait before the first retry, doubling with each one (with some jitter), and its ceiling; default `2s` and `1 hour`. Milliseconds or text such as `30 seconds`. |
74
74
  | `timeout` | How long one try may run before it counts as failed; default `15 minutes`. |
@@ -2,12 +2,12 @@
2
2
 
3
3
  # Notifications
4
4
 
5
- Turn on notifications, let each signed-in user register their browsers and phones and read their notification history, deliver to browsers with Web Push, and keep devices and history in Postgres or stores of your own.
5
+ Turn on notifications, send them to users or devices, let each signed-in user register their browsers and phones and read their notification history, deliver to browsers with Web Push, and keep devices and history in Postgres or stores of your own.
6
6
 
7
7
  ## Turning them on
8
8
 
9
9
  :::caution[In development]
10
- Nothing sends notifications yet: sending, registering a browser, push on Android and iOS and the bell are coming soon.
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`:
@@ -21,14 +21,14 @@ export default defineConfig({
21
21
  })
22
22
  ```
23
23
 
24
- Then run `protobase migration`, which writes the [devices and history tables](#table-names) 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.
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
- The bell and push are coming soon. `notifications({ ui: false })` keeps only the backend, without the bell.
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[In development]
31
- A registered device receives nothing yet: sending is coming soon, and so are push on Android and iOS.
30
+ :::caution[Beta]
31
+ Only browsers receive push yet, through [Web Push](#web-push): push on Android and iOS is coming soon.
32
32
  :::
33
33
 
34
34
  A device is where a user receives push: a browser's push subscription, or an Android or iOS app's push token. Each signed-in user registers and removes only their own, through the API:
@@ -49,24 +49,77 @@ 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 a user id, 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.
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`.
58
61
 
59
- A device is one token, or one endpoint for a browser. Registering a device someone else had moves it to the caller, as a new device with a new id that keeps nothing of the previous user's, so a shared phone or browser notifies whoever signed in on it last. A user keeps up to 20 devices: registering one more removes their least recently seen. Deleting a user removes their devices. <gap>Signing out cannot remove the session's devices because removing devices when a session ends is not implemented.</gap> Remove the device with `DELETE` before signing out.
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.
63
+
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
 
68
+ ## Sending
69
+
70
+ :::caution[Beta]
71
+ Only browsers receive push yet; push on Android and iOS is coming soon. <gap>A send can reach a device twice, or keep an entry twice in a history store of your own, when a worker stops mid-send because saving the send's progress in the same step as the push is not implemented.</gap>
72
+ :::
73
+
74
+ You send a notification from your server code, such as a job, a hook, an event subscription or an API function, with `sendNotification(db, to, message)` from `@protobase/server`. It is queued as a background job in `db`'s transaction when `db` is one, so it goes out only once your write commits, and nothing goes out when the transaction rolls back. A running job also has it as `sendNotification` in its context, beside `mail`, when the app has `notifications()`.
75
+
76
+ Every send to users says whether it shows in their inbox:
77
+
78
+ - With `inbox: true` it is kept in each user's [history](#history), which the bell will show, and is pushed to their devices, such as a notice that the app has a new version.
79
+ - With `inbox: false` it is only pushed, such as a chat message that links to its chat.
80
+ - A send to devices, `{ deviceIds }`, is only pushed, and takes no inbox flag.
81
+
82
+ ```ts
83
+ import { appPath } from '@protobase/schema'
84
+ import { sendNotification, subscription } from '@protobase/server'
85
+
86
+ // The app's public origin, from its own configuration.
87
+ const appOrigin = 'https://tasks.example.com'
88
+
89
+ /** Tells a task's owner when someone changes it. */
90
+ export const taskChanged = subscription('taskChanged', {
91
+ events: ['tasks.updated'],
92
+ run: async ({ data }, { db }) => {
93
+ const owner = data.after?.owner_id
94
+ if (owner == null) return
95
+ const url = new URL(appPath({ kind: 'record', resource: 'tasks', key: data.key }), appOrigin).href
96
+ await sendNotification(db, { userIds: [String(owner)], inbox: true }, { title: `${data.after?.title} changed`, url })
97
+ },
98
+ })
99
+ ```
100
+
101
+ The message is the one [senders](#senders) take. Its `url` opens on tap: a URL on your app's origin opens inside the app, and any other `http` or `https` URL opens outside it. Any other scheme, such as `javascript:` or `data:`, is refused. Build the URL on your app's configured origin, never on one a request names in `Host`, `X-Forwarded-Host`, `Origin` or its own URL, so nobody can make a notification lead to their site.
102
+
103
+ A send is checked before anything is queued, and a send that is not valid throws a `NotificationSendError` that names the field at fault, never its value. A valid send:
104
+
105
+ - names 1 to 1000 users or devices;
106
+ - has a user send's `inbox` as `true` or `false`;
107
+ - has a message of at most 16 KB as JSON, without a field that is not one of the message's;
108
+ - for the inbox, has a message the history keeps.
109
+
110
+ The text you send shows on lock screens, where anyone holding the device can read it, so keep anything the recipient may not see out of it. It stays in the jobs table until the send is delivered, and in a failed send until it is retried or deleted in the admin app.
111
+
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.
113
+
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.
115
+
63
116
  ## History
64
117
 
65
- :::caution[In development]
66
- Nothing writes to the history until sending lands. <gap>The history cannot fill because sending notifications is not implemented.</gap>
118
+ :::caution[Beta]
119
+ The bell that shows the history is coming soon.
67
120
  :::
68
121
 
69
- The history is each user's inbox: every notification sent to a user with the inbox flag on is kept for them, and one sent without it is only pushed. Sending, which fills it, is coming soon. Each signed-in user reaches only their own, through the API:
122
+ The history is each user's inbox: every notification [sent](#sending) to a user with the inbox flag on is kept for them, and one sent without it is only pushed. Each signed-in user reaches only their own, through the API:
70
123
 
71
124
  | Request | |
72
125
  | --- | --- |
@@ -87,8 +140,8 @@ The paths come from `historyPath('/api')`, `historyPath('/api', 'unread')`, `his
87
140
 
88
141
  ## Web Push
89
142
 
90
- :::caution[In development]
91
- Browsers cannot register for push yet, so nothing reaches them until browser registration lands.
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.
92
145
  :::
93
146
 
94
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:
@@ -107,7 +160,31 @@ Without them Web Push is off and the app has no sender for browsers. One or two
107
160
 
108
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.
109
162
 
110
- 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. <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()`.
111
188
 
112
189
  ## Your own parts
113
190
 
@@ -121,7 +198,7 @@ The device store is an interface with a Postgres default, the [devices table](#t
121
198
  import { defineConfig, notifications, type DeviceStore } from '@protobase/server'
122
199
 
123
200
  const store: DeviceStore = {
124
- register: async (userId, device) => { /* add, refresh, or move the token to userId as a new device */ },
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 */ },
125
202
  remove: async (userId, id) => { /* only when the device is userId's */ },
126
203
  listForUser: async (userId) => [],
127
204
  listByIds: async (ids) => [],
@@ -132,7 +209,7 @@ const store: DeviceStore = {
132
209
  export default defineConfig({ extends: [notifications({ store })] })
133
210
  ```
134
211
 
135
- 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.
136
213
 
137
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()`.
138
215
 
@@ -177,6 +254,7 @@ export default defineConfig({ extends: [notifications({ senders: [sender] })] })
177
254
  | `ok` | the push service took the message |
178
255
  | `gone` | the device no longer exists there, and should be removed |
179
256
  | `retry` | the push service may take it later; `retryAfterSeconds` says when, if the service does |
257
+ | `refused` | the sender never delivers to the device as it is stored, so it is neither retried nor removed |
180
258
 
181
259
  A device with no answer, or an answer that is none of these, counts as `retry`, and answers for devices outside the batch are ignored. What a sender throws becomes an error that names only the sender's place in the list, since its own error may name devices.
182
260
 
@@ -195,7 +273,7 @@ A message is plain data:
195
273
  | `urgency` | `very-low`, `low`, `normal` or `high` |
196
274
  | `platform` | each protocol's own fields: `web`, `apns` and `fcm` |
197
275
 
198
- `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.
199
277
 
200
278
  The bell is coming soon.
201
279
 
@@ -217,8 +295,11 @@ The default store keeps devices in the table `devices` of the schema `notificati
217
295
  | `environment` | an iOS app's `sandbox` or `production` |
218
296
  | `app_id` | the app's bundle id or package name |
219
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 |
220
299
  | `created_at`, `last_seen_at` | when the user registered it, and last refreshed it |
221
300
 
301
+ `protobase migration` adds `session_id` to a devices table written before devices kept their session.
302
+
222
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:
223
304
 
224
305
  ```ts