@protobase/cli 0.45.16 → 0.45.18

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,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.45.16";
2
+ var version = "0.45.18";
3
3
  //#endregion
4
4
  export { version };
package/dist/main.js CHANGED
@@ -22,6 +22,7 @@ import { registerFiles } from "./files/register.js";
22
22
  import { registerEncryption } from "./encryption/register.js";
23
23
  import { registerMigration } from "./migration/register.js";
24
24
  import { registerMobile } from "./mobile/register.js";
25
+ import { registerNotifications } from "./notifications/register.js";
25
26
  import { registerSkill } from "./skill/register.js";
26
27
  import { registerImport } from "./supabase/register.js";
27
28
  import { registerToken, registerUsers } from "./users/register.js";
@@ -138,6 +139,7 @@ registerEncryption(program);
138
139
  registerSkill(program);
139
140
  registerImport(program);
140
141
  registerMobile(program);
142
+ registerNotifications(program);
141
143
  const run = (argv) => program.parseAsync(argv).catch((error) => {
142
144
  process.stderr.write(`error: ${error.message}\n`);
143
145
  process.exitCode = 1;
@@ -41,9 +41,9 @@ const migrationParts = (project) => {
41
41
  title: "The webhook subscriptions of webhooks()",
42
42
  sql: () => webhooksMigration(project.db, project.webhooks, project.events)
43
43
  }] : [],
44
- ...project.notifications && !project.notifications.store ? [{
44
+ ...project.notifications && !(project.notifications.store && project.notifications.historyStore) ? [{
45
45
  name: "notifications",
46
- title: "The devices table of notifications()",
46
+ title: "The tables of notifications()",
47
47
  sql: () => notificationsMigration(project.db, project.notifications, project.auth)
48
48
  }] : []
49
49
  ];
@@ -0,0 +1,13 @@
1
+ import { generateVapidKeys, vapidPrivateKeyVariable, vapidPublicKeyVariable, vapidSubjectVariable } from "@protobase/server";
2
+ //#region src/notifications/print-vapid-keys.ts
3
+ /**
4
+ * Prints a fresh VAPID key pair as the two environment variables Web Push reads, and on `note` how to set the third.
5
+ * It reads no project, writes no file and makes no request.
6
+ */
7
+ const printVapidKeys = (out, note) => {
8
+ const { publicKey, privateKey } = generateVapidKeys();
9
+ out(`${vapidPublicKeyVariable}=${publicKey}\n${vapidPrivateKeyVariable}=${privateKey}\n`);
10
+ note(`Set ${vapidSubjectVariable} too, to a mailto: address or https: URL push services can reach you at. Keep the private key secret.\n`);
11
+ };
12
+ //#endregion
13
+ export { printVapidKeys };
@@ -0,0 +1,7 @@
1
+ import { printVapidKeys } from "./print-vapid-keys.js";
2
+ //#region src/notifications/register.ts
3
+ const registerNotifications = (program) => {
4
+ program.command("notifications").description("Set up the delivery of notifications").command("vapid-keys").description("Print a fresh VAPID key pair for Web Push, as PROTOBASE_VAPID_PUBLIC_KEY and PROTOBASE_VAPID_PRIVATE_KEY").action(() => printVapidKeys((text) => void process.stdout.write(text), (text) => void process.stderr.write(text)));
5
+ };
6
+ //#endregion
7
+ export { registerNotifications };
@@ -2,12 +2,12 @@ import { loadNearestEnvFile } from "../dev/env.js";
2
2
  import { importProjectFile } from "../project/import-project-file.js";
3
3
  import { existsSync } from "node:fs";
4
4
  import path from "node:path";
5
- import { mergeConfig, removeDevicesWithUsers } from "@protobase/server";
5
+ import { mergeConfig, removeDevicesWithUsers, removeHistoryWithUsers } from "@protobase/server";
6
6
  //#region src/users/load-auth.ts
7
7
  /**
8
- * Imports the project's protobase.config.ts directly and returns its Better Auth instance. With a device store of the
9
- * app's own (`notifications({ store })`), deleting a user removes their devices from it too; the devices table goes
10
- * with the user by its foreign key.
8
+ * Imports the project's protobase.config.ts directly and returns its Better Auth instance. With a device or history
9
+ * store of the app's own (`notifications({ store, historyStore })`), deleting a user removes their devices or history
10
+ * from it too; the built-in tables go with the user by their foreign keys.
11
11
  */
12
12
  const loadProjectAuth = async (projectDir) => {
13
13
  loadNearestEnvFile(projectDir);
@@ -18,6 +18,7 @@ const loadProjectAuth = async (projectDir) => {
18
18
  const { auth } = project;
19
19
  if (!auth) throw new Error("protobase.config.ts does not export `auth`; users are managed by Better Auth");
20
20
  if (project.notifications?.store) removeDevicesWithUsers(auth, project.notifications.store);
21
+ if (project.notifications?.historyStore) removeHistoryWithUsers(auth, project.notifications.historyStore);
21
22
  return auth;
22
23
  };
23
24
  //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.45.16",
3
+ "version": "0.45.18",
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.16",
40
- "@protobase/query": "0.45.16",
41
- "@protobase/schema": "0.45.16",
42
- "@protobase/server": "0.45.16",
43
- "@protobase/ui": "0.45.16",
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",
44
44
  "@react-email/render": "^2.1.0",
45
45
  "@scalar/hono-api-reference": "^0.12.10",
46
46
  "@tailwindcss/vite": "^4.3.3",
@@ -7,10 +7,10 @@ A bell in the top bar and push to browsers and phones, for what your app tells i
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
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.
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
- - [Table names](../reference/notifications.md#table-names) (in development): The built-in stores' schema, tables and columns can be renamed, as auth's users table can.
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 (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 (coming soon): Every notification a user got is kept, read or unread, for the bell to list.
13
- - Web Push (coming soon): Notifications reach the browsers a user registered, also while the app is closed.
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.
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.
@@ -459,6 +459,14 @@ Encrypts every plaintext value of the encrypted fields with the current key, enc
459
459
 
460
460
  Run it at update time, after the migrations and before the new version serves, and again once an old version that wrote plaintext has stopped. It works over one database connection, so a project's own `db` with a pool of one is enough.
461
461
 
462
+ ## `notifications vapid-keys`
463
+
464
+ ```sh
465
+ protobase notifications vapid-keys
466
+ ```
467
+
468
+ Prints a fresh key pair for [Web Push](notifications.md#web-push) as `PROTOBASE_VAPID_PUBLIC_KEY` and `PROTOBASE_VAPID_PRIVATE_KEY` lines to paste into the environment or `.env`, and says to set `PROTOBASE_VAPID_SUBJECT` too. It reads no project, writes no file and makes no request.
469
+
462
470
  ## `users`
463
471
 
464
472
  ```sh
@@ -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 keep the devices in Postgres or a store of your own.
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.
6
6
 
7
7
  ## Turning them on
8
8
 
9
9
  :::caution[In development]
10
- Nothing sends notifications yet: sending, the history, Web Push, push on Android and iOS and the bell are coming soon.
10
+ Nothing sends notifications yet: sending, registering a browser, 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 table](#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 the table is missing or lacks what notifications need, and name it. Without `notifications()` there is none of it: no endpoints, no table and no migration.
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.
25
25
 
26
26
  The bell and push are coming soon. `notifications({ ui: false })` keeps only the backend, without the bell.
27
27
 
28
28
  ## Devices
29
29
 
30
30
  :::caution[In development]
31
- A registered device receives nothing yet: Web Push and push on Android and iOS are coming soon.
31
+ A registered device receives nothing yet: sending is coming soon, and so are push on Android and iOS.
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:
@@ -60,10 +60,59 @@ A device is one token, or one endpoint for a browser. Registering a device someo
60
60
 
61
61
  The path comes from `devicesPath('/api', id)`, and the name of its id parameter from `deviceIdParam`, both exported by `@protobase/server`.
62
62
 
63
+ ## History
64
+
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>
67
+ :::
68
+
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:
70
+
71
+ | Request | |
72
+ | --- | --- |
73
+ | `GET /api/notifications/history` | the caller's notifications, newest first: `{ items, next }` |
74
+ | `GET /api/notifications/history/unread` | how many are unread: `{ count }`, at most 100, so show `99+` from there |
75
+ | `POST /api/notifications/history/<id>/read` | marks the caller's notification with that id read; answers `204` whether or not the caller had it |
76
+ | `POST /api/notifications/history/read` | marks all read up to the newest one the caller was shown: `{ "upTo": "<its createdAt>" }`, then `204` |
77
+
78
+ Each item is `{ id, title, body, url, data, createdAt, readAt }`, with `readAt` `null` while unread. A notification read once keeps its first `readAt`, and marking all read leaves those read earlier as they were. Marking all read takes the `createdAt` of the newest notification the user saw, so one that arrives meanwhile stays unread.
79
+
80
+ The list gives 20 at a time, or as many as `?limit=` says, up to 50. A full page's `next` is a cursor: pass it as `?cursor=` for the page after it, until `next` is `null`. A limit or cursor out of its format, and a parameter or body field the request does not take, such as a user, is a `400` that changes nothing. Both marks take JSON (`Content-Type: application/json`): marking one takes an empty body or `{}`. Answers about the history are never cached.
81
+
82
+ `title` and `body` are plain text: show them as text, never as HTML. `url` is a path on the app, such as `/tasks/42`, or an absolute URL on one of the app's own origins; anything else, another site, `javascript:` or `data:`, is answered as `null`. A notification's `url` and `data` are kept until its user is removed, so leave one-time links and secrets out of inbox notifications.
83
+
84
+ The same people may call them as may [register devices](#devices): only someone signed in as themselves. With Protobase's auth, deleting a user removes their history; an app that deletes users otherwise calls `historyStore(db, options).removeAllForUser(userId)` as it deletes one, with the options it gave `notifications()`.
85
+
86
+ The paths come from `historyPath('/api')`, `historyPath('/api', 'unread')`, `historyPath('/api', 'read')` and `historyPath('/api', { read: id })`, and the name of the id parameter from `historyIdParam`, all exported by `@protobase/server`.
87
+
88
+ ## Web Push
89
+
90
+ :::caution[In development]
91
+ Browsers cannot register for push yet, so nothing reaches them until browser registration lands.
92
+ :::
93
+
94
+ 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:
95
+
96
+ ```sh
97
+ protobase notifications vapid-keys
98
+ ```
99
+
100
+ | Variable | |
101
+ | --- | --- |
102
+ | `PROTOBASE_VAPID_PUBLIC_KEY` | the public key the command prints |
103
+ | `PROTOBASE_VAPID_PRIVATE_KEY` | the private key the command prints |
104
+ | `PROTOBASE_VAPID_SUBJECT` | how push services reach you: a `mailto:` address or an `https:` URL |
105
+
106
+ Without them Web Push is off and the app has no sender for browsers. One or two of them set, a blank one, a key that is not one, or a public key that is not the private key's stops startup, naming the variable without its value.
107
+
108
+ 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
+
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.
111
+
63
112
  ## Your own parts
64
113
 
65
114
  :::caution[In development]
66
- Only the device store can be replaced yet: senders, the history store and the bell are coming soon.
115
+ The device store, the history store and the senders can be replaced; the bell is coming soon.
67
116
  :::
68
117
 
69
118
  The device store is an interface with a Postgres default, the [devices table](#table-names). You pass your own store to `notifications()`, such as one from a package that keeps devices elsewhere, and then no table is needed and `protobase migration` writes none:
@@ -87,12 +136,73 @@ Every method takes and returns plain data: the user id as text, and devices as `
87
136
 
88
137
  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()`.
89
138
 
90
- Senders, the history store and the bell are coming soon.
139
+ The history store is an interface with a Postgres default too, the [history table](#table-names), and you pass your own as `historyStore`:
140
+
141
+ ```ts
142
+ import { defineConfig, notifications, type HistoryStore } from '@protobase/server'
143
+
144
+ const historyStore: HistoryStore = {
145
+ record: async (userId, notification) => { /* keep it unread, created now, under a new id */ },
146
+ list: async (userId, { before, limit }) => [], // newest first, after `before`
147
+ countUnread: async (userId) => 0, // counting up to 100
148
+ markRead: async (userId, id) => false, // true when userId has it
149
+ markAllRead: async (userId, upTo) => {}, // the unread ones created up to `upTo`
150
+ removeAllForUser: async (userId) => {},
151
+ }
152
+
153
+ export default defineConfig({ extends: [notifications({ historyStore })] })
154
+ ```
155
+
156
+ A notification is `{ id, userId, title, body, url, data, createdAt, readAt }`, and `before` is the `{ createdAt, id }` of the last one of the page before. Each method touches only the given user's notifications, and throws on an empty user id or id. An id is letters, digits, `-` and `_`, at most 64 characters, as it goes into a path. `record` keeps only what `historyLimits` allows: a title of up to 256 characters, a body and a url of up to 2048, and `data` of up to 4096 bytes of JSON. The endpoints answer with an error, showing nothing of it, when a store gives back another user's notification. A store missing a method stops startup, naming it. Deleting a user calls its `removeAllForUser` as it does the device store's; an app that deletes users otherwise calls `historyStore(db, options).removeAllForUser(userId)`.
157
+
158
+ ### Senders
159
+
160
+ A sender delivers notifications to the devices of the kinds it names, through their push service. Web Push is built in; you pass your own senders to `notifications()`, such as from a package, and they replace the built-in ones, at most one for each kind:
161
+
162
+ ```ts
163
+ import { defineConfig, notifications, type PushSender } from '@protobase/server'
164
+
165
+ const sender: PushSender = {
166
+ kinds: ['fcm'],
167
+ send: async (message, devices) => devices.map((device) => ({ id: device.id, result: 'ok' })),
168
+ }
169
+
170
+ export default defineConfig({ extends: [notifications({ senders: [sender] })] })
171
+ ```
172
+
173
+ `send` takes a message and a batch of devices of those kinds, and answers each device by its id with a result:
174
+
175
+ | Result | |
176
+ | --- | --- |
177
+ | `ok` | the push service took the message |
178
+ | `gone` | the device no longer exists there, and should be removed |
179
+ | `retry` | the push service may take it later; `retryAfterSeconds` says when, if the service does |
180
+
181
+ 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
+
183
+ A message is plain data:
184
+
185
+ | Field | |
186
+ | --- | --- |
187
+ | `title` | the title, required |
188
+ | `body` | the text under it |
189
+ | `url` | opened on tap: an absolute `http` or `https` URL, on the app's origin or any other |
190
+ | `data` | JSON the app reads when the notification is opened |
191
+ | `badge` | the number on the app's icon |
192
+ | `sound` | the sound to play |
193
+ | `tag` | a later notification with the same tag replaces this one: up to 32 letters, digits, `-` and `_` |
194
+ | `ttl` | how long, in seconds, a push service keeps it for a device that is offline, up to 28 days |
195
+ | `urgency` | `very-low`, `low`, `normal` or `high` |
196
+ | `platform` | each protocol's own fields: `web`, `apns` and `fcm` |
197
+
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.
199
+
200
+ The bell is coming soon.
91
201
 
92
202
  ## Table names
93
203
 
94
- :::caution[In development]
95
- Only the devices table exists yet: the history table comes with the notification history.
204
+ :::caution[Beta]
205
+ Both tables are written and checked; nothing writes to the history table until sending lands.
96
206
  :::
97
207
 
98
208
  The default store keeps devices in the table `devices` of the schema `notifications`:
@@ -118,4 +228,24 @@ notifications({
118
228
  })
119
229
  ```
120
230
 
121
- A name is lowercase letters, digits and `_`, at most 63 characters. Startup stops, naming what is wrong, while the table lacks a configured column, a unique index on the token column alone, which moving a device relies on, or, with Protobase's auth, the foreign key from the user column to the users table with `on delete cascade`.
231
+ The history is kept in the table `history` of the same schema:
232
+
233
+ | Column | |
234
+ | --- | --- |
235
+ | `id` | `uuid`, the id the endpoints answer with |
236
+ | `user_id` | the user's id, as in the devices table; with Protobase's auth a foreign key to auth's users table, so a deleted user's history goes with them |
237
+ | `title`, `body` | the text it shows |
238
+ | `url` | where it leads |
239
+ | `data` | `jsonb`, the app's own |
240
+ | `created_at` | when it was kept |
241
+ | `read_at` | when its user read it, `NULL` while unread |
242
+
243
+ Two indexes keep a user's newest-first pages and unread count cheap. You rename its table and columns as `history.table` and `history.columns`:
244
+
245
+ ```ts
246
+ notifications({
247
+ history: { table: 'inbox', columns: { user_id: 'owner_id', read_at: 'seen_at' } },
248
+ })
249
+ ```
250
+
251
+ A name is lowercase letters, digits and `_`, at most 63 characters. Startup stops, naming what is wrong, while a table lacks a configured column, while the devices table lacks a unique index on the token column alone, which moving a device relies on, or, with Protobase's auth, while either table lacks the foreign key from its user column to the users table with `on delete cascade`.