@protobase/server 0.133.2 → 0.133.4
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/api-cors.js +4 -1
- package/dist/better-auth/organizations/host.js +4 -3
- package/dist/better-auth/organizations/not-default.js +13 -0
- package/dist/create-admin.js +23 -8
- package/dist/deps.d.ts +3 -0
- package/dist/functions/define-function.d.ts +5 -0
- package/dist/functions/routes.js +4 -1
- package/dist/functions/supabase-routes.js +6 -3
- package/dist/list-service.js +15 -5
- package/dist/live/live-route.js +20 -5
- package/dist/live/refresh/live-refresh.d.ts +13 -0
- package/dist/live/refresh/live-refresh.js +8 -0
- package/dist/live/refresh/refresh-notices.js +21 -0
- package/dist/live/token/key-filter.js +31 -0
- package/dist/live/token/live-headers.js +9 -0
- package/dist/live/token/live-key.js +16 -0
- package/dist/live/token/live-preference.js +11 -0
- package/dist/live/token/live-subject.js +26 -0
- package/dist/live/token/live-token.d.ts +14 -0
- package/dist/live/token/live-token.js +24 -0
- package/dist/live/token/live-tokens.d.ts +20 -0
- package/dist/live/token/live-tokens.js +28 -0
- package/dist/live/visible-notices.js +5 -1
- package/dist/package.js +1 -1
- package/dist/read-service.js +27 -6
- package/dist/records.d.ts +1 -1
- package/dist/request-access.d.ts +1 -1
- package/dist/routes/collection.js +17 -6
- package/dist/routes/record.js +8 -8
- package/dist/sql-parts.d.ts +1 -1
- package/dist/webhooks/attempt.js +1 -0
- package/dist/webhooks/webhooks.js +3 -1
- package/dist/write-shared.d.ts +1 -1
- package/package.json +6 -6
package/dist/api-cors.js
CHANGED
|
@@ -28,6 +28,7 @@ const allowHeaders = [
|
|
|
28
28
|
"content-type",
|
|
29
29
|
"if-match",
|
|
30
30
|
"if-none-match",
|
|
31
|
+
"prefer",
|
|
31
32
|
"apikey",
|
|
32
33
|
"x-client-info",
|
|
33
34
|
"x-supabase-api-version"
|
|
@@ -36,7 +37,9 @@ const exposeHeaders = [
|
|
|
36
37
|
"location",
|
|
37
38
|
"etag",
|
|
38
39
|
"x-meta-version",
|
|
39
|
-
"x-protobase-warning"
|
|
40
|
+
"x-protobase-warning",
|
|
41
|
+
"preference-applied",
|
|
42
|
+
"protobase-live"
|
|
40
43
|
];
|
|
41
44
|
/**
|
|
42
45
|
* CORS for the API: an allowed origin gets `Access-Control-Allow-Origin` (`*` when any is), preflights are answered
|
|
@@ -6,6 +6,7 @@ import { storeSqlOf } from "../store/store-sql.js";
|
|
|
6
6
|
import { mayBeId } from "../store/store-reads.js";
|
|
7
7
|
import { pageOf } from "../store/page-of.js";
|
|
8
8
|
import { builderName, rowsIn } from "./host-scope.js";
|
|
9
|
+
import { notDefaultOrganization } from "./not-default.js";
|
|
9
10
|
import { isEveryOrganization } from "@protobase/query";
|
|
10
11
|
import { sql } from "kysely";
|
|
11
12
|
//#region src/better-auth/organizations/host.ts
|
|
@@ -285,11 +286,11 @@ const organizationsPage = async (auth, scope, { after, size = 100 }) => {
|
|
|
285
286
|
const ownOrganizationsWithoutMembers = (auth, userId) => acrossOrganizations("the first user owns every organization without members", () => ownEmptyOrganizations(auth, userId));
|
|
286
287
|
const ownEmptyOrganizations = async (auth, userId) => {
|
|
287
288
|
const settings = settingsOf(auth);
|
|
288
|
-
const
|
|
289
|
+
const context = await contextOf(auth);
|
|
290
|
+
const store = storeSqlOf(context);
|
|
289
291
|
const member = store.table("member");
|
|
290
292
|
const m = member.columns;
|
|
291
|
-
const
|
|
292
|
-
const notDefault = defaultId === void 0 ? sql`` : sql`and cast(o.id as text) <> ${defaultId}`;
|
|
293
|
+
const notDefault = notDefaultOrganization(context.options, settings.options.default?.id);
|
|
293
294
|
const { rows } = await sql`insert into ${member} (id, ${m.organization_id}, ${m.user_id}, ${m.role}, ${m.app_roles}, ${m.created_at})
|
|
294
295
|
select ${store.newId}, o.id, ${userId}, 'owner', ${JSON.stringify(settings.creatorAppRoles)}::jsonb, ${/* @__PURE__ */ new Date()} from ${store.table("organization")} o
|
|
295
296
|
where not exists (select from ${member} m where m.${m.organization_id} = o.id) ${notDefault}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { storedId } from "../store/store-reads.js";
|
|
2
|
+
import { sql } from "kysely";
|
|
3
|
+
//#region src/better-auth/organizations/not-default.ts
|
|
4
|
+
/**
|
|
5
|
+
* The condition that leaves the configured default organization out of a statement on `organization o`, nothing without
|
|
6
|
+
* one. Where the ids are uuids, the id is compared as Postgres prints it, so one written in upper case matches too.
|
|
7
|
+
*/
|
|
8
|
+
const notDefaultOrganization = (options, defaultId) => {
|
|
9
|
+
if (defaultId === void 0) return sql``;
|
|
10
|
+
return sql`and cast(o.id as text) <> ${storedId(options, defaultId)}`;
|
|
11
|
+
};
|
|
12
|
+
//#endregion
|
|
13
|
+
export { notDefaultOrganization };
|
package/dist/create-admin.js
CHANGED
|
@@ -62,6 +62,7 @@ import { bucketsRefreshJob } from "./computed/buckets-job.js";
|
|
|
62
62
|
import { hasBuckets } from "./computed/buckets-targets.js";
|
|
63
63
|
import { callerRecords } from "./functions/records.js";
|
|
64
64
|
import { toApiFunction } from "./functions/define-function.js";
|
|
65
|
+
import { liveRefresh } from "./live/refresh/live-refresh.js";
|
|
65
66
|
import { createWebhooks } from "./webhooks/webhooks.js";
|
|
66
67
|
import { webhookTable } from "./webhooks/table/webhook-table.js";
|
|
67
68
|
import { subscriptionUrlCheck, subscriptionWriteCheck } from "./webhooks/table/validate-hook.js";
|
|
@@ -93,8 +94,11 @@ import { appRelayChannels } from "./relay/realtime-channels.js";
|
|
|
93
94
|
import { appRelaySettings } from "./relay/relay-switch.js";
|
|
94
95
|
import { idleRelayJobs } from "./relay/relay-jobs.js";
|
|
95
96
|
import { relayPresencePath } from "./relay/presence-route.js";
|
|
97
|
+
import { sessionEnd } from "./relay/session-end.js";
|
|
96
98
|
import { relayTicketPath } from "./relay/ticket-route.js";
|
|
97
99
|
import { relayRuntime } from "./relay/relay-runtime.js";
|
|
100
|
+
import { liveTokens } from "./live/token/live-tokens.js";
|
|
101
|
+
import { writeRefreshNotices } from "./live/refresh/refresh-notices.js";
|
|
98
102
|
import { typingViewErrors } from "./relay/typing-views.js";
|
|
99
103
|
import { liveSessions } from "./better-auth/live-sessions.js";
|
|
100
104
|
import { mailSenderUse } from "./personal-mail/mail-sender-use.js";
|
|
@@ -290,6 +294,17 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
|
|
|
290
294
|
...options.roles && { roles: options.roles },
|
|
291
295
|
...options.defaultAccess && { defaultAccess: options.defaultAccess }
|
|
292
296
|
};
|
|
297
|
+
const relayApp = {
|
|
298
|
+
views: viewModels,
|
|
299
|
+
models: appModels,
|
|
300
|
+
signIn: Boolean(auth)
|
|
301
|
+
};
|
|
302
|
+
const relaySettings = appRelaySettings(realtime?.relay, globalThis.process?.env ?? {}, relayApp);
|
|
303
|
+
const tokens = relaySettings && auth && liveTokens({
|
|
304
|
+
app: relaySettings.app,
|
|
305
|
+
ticketKey: relaySettings.ticketKey,
|
|
306
|
+
sessionEnd: sessionEnd(auth)
|
|
307
|
+
});
|
|
293
308
|
const deps = {
|
|
294
309
|
db,
|
|
295
310
|
registry,
|
|
@@ -352,14 +367,9 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
|
|
|
352
367
|
organizations: Boolean(auth?.organizations),
|
|
353
368
|
...auth?.origins[0] && { origin: auth.origins[0] },
|
|
354
369
|
...statusTables && { doNotDisturb: (ringDb, userIds) => onDoNotDisturb(ringDb, statusTables.statuses, userIds) }
|
|
355
|
-
}) }
|
|
370
|
+
}) },
|
|
371
|
+
...tokens && { liveTokens: tokens }
|
|
356
372
|
};
|
|
357
|
-
const relayApp = {
|
|
358
|
-
views: viewModels,
|
|
359
|
-
models: appModels,
|
|
360
|
-
signIn: Boolean(auth)
|
|
361
|
-
};
|
|
362
|
-
const relaySettings = appRelaySettings(realtime?.relay, globalThis.process?.env ?? {}, relayApp);
|
|
363
373
|
const relay = relaySettings && relayRuntime(relaySettings, auth, deps);
|
|
364
374
|
const relayJobList = relay ? relay.jobs : appRelayChannels(realtime?.relay, relayApp) ? idleRelayJobs() : [];
|
|
365
375
|
const typingErrors = typingViewErrors(viewModels, relaySettings && new Set(Object.keys(relaySettings.channels)));
|
|
@@ -522,6 +532,8 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
|
|
|
522
532
|
const decryptField = fieldDecrypter(deps);
|
|
523
533
|
const hubs = realtimeHubs(deps, realtime, report);
|
|
524
534
|
const channels = channelSender(registry, hubs.records.broadcasts);
|
|
535
|
+
const noticed = appModels.some((model) => model.live) || deps.calls !== void 0;
|
|
536
|
+
const refresh = liveRefresh(noticed ? (userIds) => writeRefreshNotices(db, changes, userIds) : void 0);
|
|
525
537
|
app.route("/", functionRoutes({
|
|
526
538
|
basePath: `${systemPath}/functions`,
|
|
527
539
|
functions: apiFunctions,
|
|
@@ -531,6 +543,7 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
|
|
|
531
543
|
scope,
|
|
532
544
|
records: (session) => callerRecords(deps, session),
|
|
533
545
|
channels,
|
|
546
|
+
live: refresh,
|
|
534
547
|
decryptField,
|
|
535
548
|
...auth && auth.personalMail.length > 0 && { personalMailer: auth.personalMailer },
|
|
536
549
|
onError,
|
|
@@ -575,6 +588,7 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
|
|
|
575
588
|
keys: apiKeys,
|
|
576
589
|
verify: verifyGoTrue
|
|
577
590
|
}),
|
|
591
|
+
live: refresh,
|
|
578
592
|
onError
|
|
579
593
|
}));
|
|
580
594
|
app.route("/", batchRoute(deps, authenticate, meta));
|
|
@@ -663,7 +677,7 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
|
|
|
663
677
|
if (engine) app.route(`${systemPath}/workflows/tasks`, engine.routes.tasks());
|
|
664
678
|
if (engine?.routes.runners) app.route(`${systemPath}/runners/v1`, engine.routes.runners());
|
|
665
679
|
if (engine?.routes.runnerInstall) app.route(`${systemPath}/runners/install.sh`, engine.routes.runnerInstall());
|
|
666
|
-
if (
|
|
680
|
+
if (noticed) app.route(systemPath || "/", guarded((live) => void live.route("/", liveRoutes(feed, (session) => visibleNotices(deps, session))), withAnonymous(authenticate, options.roles)));
|
|
667
681
|
if (engine) app.route(`${systemPath}/workflows`, guarded((routes) => void routes.route("/", engine.routes.issue())));
|
|
668
682
|
app.route(basePath, api);
|
|
669
683
|
app.route(`${deps.systemPath}/meta`, metaApp);
|
|
@@ -684,6 +698,7 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
|
|
|
684
698
|
subscriptions,
|
|
685
699
|
functions: apiFunctions,
|
|
686
700
|
channels,
|
|
701
|
+
live: refresh,
|
|
687
702
|
schema: changes,
|
|
688
703
|
log: (line) => console.log(line),
|
|
689
704
|
...table && { table },
|
package/dist/deps.d.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { MapSettings } from "./maps/map-settings.js";
|
|
|
13
13
|
import { PluginOption } from "./plugins/plugin-settings.js";
|
|
14
14
|
import { SourceOption } from "./sources/source-settings.js";
|
|
15
15
|
import { ScanGuard } from "./scan-guard.js";
|
|
16
|
+
import { LiveTokens } from "./live/token/live-tokens.js";
|
|
16
17
|
import { PageModel, Translations } from "@protobase/layout";
|
|
17
18
|
import { Locale } from "@protobase/schema/internal";
|
|
18
19
|
import { BottomBarModel, ResolveOptions, UserMenuModel, ViewModel } from "@protobase/schema";
|
|
@@ -104,5 +105,7 @@ export type Deps = {
|
|
|
104
105
|
mailSenders?: (userId: string) => Promise<MailSender[]>;
|
|
105
106
|
/** With `calls`: the app's calls, which functions admit members to and the records' readers follow. */
|
|
106
107
|
calls?: CallsService;
|
|
108
|
+
/** With the relay: the live tokens a list or record read of a live resource gives on `Prefer: live`. */
|
|
109
|
+
liveTokens?: LiveTokens;
|
|
107
110
|
};
|
|
108
111
|
//#endregion
|
|
@@ -5,6 +5,7 @@ import { Caller } from "../api-keys/resolve-caller.js";
|
|
|
5
5
|
import { SocketEvents } from "./function-socket.js";
|
|
6
6
|
import { CallsAccess } from "../calls/calls-access.js";
|
|
7
7
|
import { ChannelSender } from "../channels/channel-sender.js";
|
|
8
|
+
import { LiveRefresh } from "../live/refresh/live-refresh.js";
|
|
8
9
|
import { FunctionRecords } from "./records.js";
|
|
9
10
|
import { Capability } from "@protobase/schema";
|
|
10
11
|
import { ScopedDb } from "@protobase/query";
|
|
@@ -34,6 +35,8 @@ export type PublicFunctionContext = {
|
|
|
34
35
|
acceptWebSocket: (events: SocketEvents) => Response;
|
|
35
36
|
/** Admits a member to a call's media, over the socket the function accepts: see `CallsAccess`. */
|
|
36
37
|
calls: CallsAccess;
|
|
38
|
+
/** Tells a person's open pages to read again once their access changed: `live.refresh({ user })`, see `LiveRefresh`. */
|
|
39
|
+
live: LiveRefresh;
|
|
37
40
|
};
|
|
38
41
|
/** Who called a function, and the app's resources as them. */
|
|
39
42
|
export type FunctionCaller = {
|
|
@@ -72,6 +75,8 @@ export type KeyFunctionContext = {
|
|
|
72
75
|
db: ScopedDb;
|
|
73
76
|
/** The caller of the `apikey` header and bearer token: rejects with a 401 problem when they admit nobody. */
|
|
74
77
|
caller: () => Promise<Caller>;
|
|
78
|
+
/** Tells a person's open pages to read again once their access changed: `live.refresh({ user })`, see `LiveRefresh`. */
|
|
79
|
+
live: LiveRefresh;
|
|
75
80
|
};
|
|
76
81
|
/** A Web-standard handler. Its request's path is the part after `/api/functions/<name>`: `/` or `/more/parts`. */
|
|
77
82
|
export type FunctionHandler = (request: Request, context: FunctionContext) => Response | Promise<Response>;
|
package/dist/functions/routes.js
CHANGED
|
@@ -2,6 +2,7 @@ import { forbidden, notFound } from "../problem.js";
|
|
|
2
2
|
import { namingTimeouts } from "../statement-timeout.js";
|
|
3
3
|
import { auditOrigin } from "../audit/origin.js";
|
|
4
4
|
import { invokeFunction } from "./define-function.js";
|
|
5
|
+
import { liveRefresh } from "../live/refresh/live-refresh.js";
|
|
5
6
|
import { socketAcceptor } from "./accept-socket.js";
|
|
6
7
|
import { functionGate, requireGate } from "./function-gate.js";
|
|
7
8
|
import { runInBackground } from "../background-work.js";
|
|
@@ -33,7 +34,7 @@ const isUpgrade = (request) => request.headers.get("upgrade")?.toLowerCase() ===
|
|
|
33
34
|
* A function may answer an upgrade with a socket, only once it returned. While it is open, its caller is checked again
|
|
34
35
|
* every minute: a protected function's always, a public one's once `caller()` resolved.
|
|
35
36
|
*/
|
|
36
|
-
const functionRoutes = ({ basePath, functions, authenticate, access, db, records, channels, decryptField, personalMailer = noPersonalMail, onError, wake, upgradeWebSocket, upgradeAuthenticate = authenticate, calls, report, scope }) => {
|
|
37
|
+
const functionRoutes = ({ basePath, functions, authenticate, access, db, records, channels, live = liveRefresh(void 0), decryptField, personalMailer = noPersonalMail, onError, wake, upgradeWebSocket, upgradeAuthenticate = authenticate, calls, report, scope }) => {
|
|
37
38
|
const app = new Hono().basePath(basePath);
|
|
38
39
|
app.onError(onError);
|
|
39
40
|
const sessionOf = (request) => isUpgrade(request) ? upgradeAuthenticate(request) : authenticate(request);
|
|
@@ -77,6 +78,7 @@ const functionRoutes = ({ basePath, functions, authenticate, access, db, records
|
|
|
77
78
|
name,
|
|
78
79
|
db: scopedDb(db, (await scope()).tables, void 0),
|
|
79
80
|
channels,
|
|
81
|
+
live,
|
|
80
82
|
caller: resolveCaller,
|
|
81
83
|
acceptWebSocket: acceptor.accept,
|
|
82
84
|
calls: callsAccess(calls, resolveCaller)
|
|
@@ -106,6 +108,7 @@ const functionRoutes = ({ basePath, functions, authenticate, access, db, records
|
|
|
106
108
|
name,
|
|
107
109
|
db: scopedDb(db, tables, organizationOf(caller.session)),
|
|
108
110
|
channels,
|
|
111
|
+
live,
|
|
109
112
|
...caller,
|
|
110
113
|
caller: async () => caller,
|
|
111
114
|
decryptField: decryptField(reader),
|
|
@@ -2,6 +2,7 @@ import { notFound, unauthorized } from "../problem.js";
|
|
|
2
2
|
import { namingTimeouts } from "../statement-timeout.js";
|
|
3
3
|
import { supabaseFunctionsPath } from "../supabase-paths.js";
|
|
4
4
|
import { invokeFunction } from "./define-function.js";
|
|
5
|
+
import { liveRefresh } from "../live/refresh/live-refresh.js";
|
|
5
6
|
import { runInBackground } from "../background-work.js";
|
|
6
7
|
import { relativeRequest } from "./routes.js";
|
|
7
8
|
import { Hono } from "hono";
|
|
@@ -16,7 +17,7 @@ import { cors } from "hono/cors";
|
|
|
16
17
|
* `/<name>/more/parts`, and a CORS preflight, which carries no key, reaches it unchecked. Every other function is a 404
|
|
17
18
|
* here, and none of its code runs.
|
|
18
19
|
*/
|
|
19
|
-
const supabaseFunctionRoutes = ({ functions, db, scope, keys, caller, onError }) => {
|
|
20
|
+
const supabaseFunctionRoutes = ({ functions, db, scope, keys, caller, live = liveRefresh(void 0), onError }) => {
|
|
20
21
|
const app = new Hono().basePath(supabaseFunctionsPath);
|
|
21
22
|
app.onError(onError);
|
|
22
23
|
const hasKeys = keys.publishable !== void 0 || keys.secret !== void 0;
|
|
@@ -40,7 +41,8 @@ const supabaseFunctionRoutes = ({ functions, db, scope, keys, caller, onError })
|
|
|
40
41
|
const context = {
|
|
41
42
|
name,
|
|
42
43
|
db: scopedDb(db, (await scope()).tables, void 0),
|
|
43
|
-
caller: () => resolved ??= caller(c.req.raw)
|
|
44
|
+
caller: () => resolved ??= caller(c.req.raw),
|
|
45
|
+
live
|
|
44
46
|
};
|
|
45
47
|
return invokeFunction(name, fn, request, context);
|
|
46
48
|
}
|
|
@@ -49,7 +51,8 @@ const supabaseFunctionRoutes = ({ functions, db, scope, keys, caller, onError })
|
|
|
49
51
|
return invokeFunction(name, fn, request, {
|
|
50
52
|
name,
|
|
51
53
|
db: scopedDb(db, (await scope()).tables, void 0),
|
|
52
|
-
caller: async () => resolved
|
|
54
|
+
caller: async () => resolved,
|
|
55
|
+
live
|
|
53
56
|
});
|
|
54
57
|
}), { longQueries: options.longQueries }));
|
|
55
58
|
}
|
package/dist/list-service.js
CHANGED
|
@@ -3,7 +3,7 @@ import { checkedSort } from "./filter-input.js";
|
|
|
3
3
|
import { requestAccess, requireOperation } from "./request-access.js";
|
|
4
4
|
import { exposeRow, pickFields } from "./rows.js";
|
|
5
5
|
import { labelRequests, relatedLabels } from "./related-labels.js";
|
|
6
|
-
import { readTransaction } from "./transactions.js";
|
|
6
|
+
import { readTransaction, snapshotReadTransaction } from "./transactions.js";
|
|
7
7
|
import { deletedRows, listParams, pageSizeOf, parseParams, seekParams, selectedFields } from "./params.js";
|
|
8
8
|
import { readFilter } from "./related-filter.js";
|
|
9
9
|
import { etagAlias } from "./sql-parts.js";
|
|
@@ -21,9 +21,10 @@ const exactCountLimit = 1e4;
|
|
|
21
21
|
* so a hidden field is refused exactly like an unknown one; the access row filter is applied by the query layer.
|
|
22
22
|
* `labels` names the records the returned relations point at, each read under the related resource's own access, and
|
|
23
23
|
* `photos` brings each record's first photos, read under the photos' resource's own access. `limit_per` keeps the first
|
|
24
|
-
* rows per value of a field, by value and in the list's order within each, with no further page.
|
|
24
|
+
* rows per value of a field, by value and in the list's order within each, with no further page. `live` asks for a live
|
|
25
|
+
* token of the read (`token`), for a live resource when the app has one to give: the read then runs in one snapshot.
|
|
25
26
|
*/
|
|
26
|
-
const listRecords = async (deps, entry, session, input, maxFilterLength, jump = false, within) => {
|
|
27
|
+
const listRecords = async (deps, entry, session, input, maxFilterLength, jump = false, within, live = false) => {
|
|
27
28
|
const params = jump ? parseParams(seekParams, input) : parseParams(listParams, input);
|
|
28
29
|
const access = await requestAccess(deps, entry, session);
|
|
29
30
|
requireOperation(access, "list");
|
|
@@ -77,7 +78,8 @@ const listRecords = async (deps, entry, session, input, maxFilterLength, jump =
|
|
|
77
78
|
scope
|
|
78
79
|
});
|
|
79
80
|
const position = jump ? params.position : void 0;
|
|
80
|
-
const
|
|
81
|
+
const subject = live && entry.model.live && deps.liveTokens ? await deps.liveTokens.subject(session) : void 0;
|
|
82
|
+
const result = await (subject ? snapshotReadTransaction : readTransaction)(deps.db, deps.statementTimeoutMs, async (trx) => {
|
|
81
83
|
const extraColumns = entry.etag && etags ? [{
|
|
82
84
|
field: entry.etag.field.name,
|
|
83
85
|
as: "text",
|
|
@@ -110,13 +112,21 @@ const listRecords = async (deps, entry, session, input, maxFilterLength, jump =
|
|
|
110
112
|
permissions: permitted ? await rowPermissions(trx, access, rows) : void 0,
|
|
111
113
|
estimate: await estimateCount(trx, queryModel, filter, scope),
|
|
112
114
|
...params.count === "exact" && { counted: await countUpTo(trx, queryModel, 10001, filter, scope) },
|
|
113
|
-
...params.labels !== void 0 && { labels: await relatedLabels(trx, labels, rows) }
|
|
115
|
+
...params.labels !== void 0 && { labels: await relatedLabels(trx, labels, rows) },
|
|
116
|
+
token: subject && await deps.liveTokens.seal(trx, subject, {
|
|
117
|
+
resource: entry.name,
|
|
118
|
+
model: queryModel,
|
|
119
|
+
scope,
|
|
120
|
+
...filter && { filter },
|
|
121
|
+
fields: columns ?? Object.keys(model.fields)
|
|
122
|
+
})
|
|
114
123
|
};
|
|
115
124
|
});
|
|
116
125
|
const shown = await presentFiles(access, result.rows);
|
|
117
126
|
const included = photos && await recordPhotos(deps, photos, model, result.rows);
|
|
118
127
|
return {
|
|
119
128
|
warning: warning ?? included?.warning,
|
|
129
|
+
token: result.token,
|
|
120
130
|
body: {
|
|
121
131
|
items: shown.map((row, i) => ({
|
|
122
132
|
...pickFields(row, columns),
|
package/dist/live/live-route.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { parseParams } from "../params.js";
|
|
2
|
+
import "./refresh/refresh-notices.js";
|
|
2
3
|
import { Hono } from "hono";
|
|
3
4
|
import { z } from "zod";
|
|
4
5
|
import { streamSSE } from "hono/streaming";
|
|
@@ -10,18 +11,20 @@ const heartbeatMs = 25e3;
|
|
|
10
11
|
const later = (id, than) => BigInt(id) > BigInt(than);
|
|
11
12
|
/**
|
|
12
13
|
* `GET /live`: the changes of the live resources the caller may read, as they come, keys only. `visibleTo` says which
|
|
13
|
-
* notices a caller hears of (`visibleNotices`)
|
|
14
|
+
* notices a caller hears of (`visibleNotices`), for the access the caller connected with: a `refresh` ends the stream,
|
|
15
|
+
* so the page connects again from its cursor as its access is now.
|
|
14
16
|
*/
|
|
15
17
|
const liveRoutes = (feed, visibleTo) => {
|
|
16
18
|
const app = new Hono();
|
|
17
19
|
app.get("/live", async (c) => {
|
|
18
20
|
const { after } = parseParams(params, c.req.query());
|
|
19
21
|
const visible = await visibleTo(c.get("session"));
|
|
20
|
-
const changesOf = (notices) => notices.filter(visible).map(({ resource, key, operation }) => ({
|
|
22
|
+
const changesOf = (notices) => notices.filter((notice) => notice.resource !== "$live" && visible(notice)).map(({ resource, key, operation }) => ({
|
|
21
23
|
resource,
|
|
22
24
|
key,
|
|
23
25
|
operation
|
|
24
26
|
}));
|
|
27
|
+
const refreshes = (notices) => notices.some((notice) => notice.resource === "$live" && visible(notice));
|
|
25
28
|
const queue = [];
|
|
26
29
|
let wake = () => {};
|
|
27
30
|
const held = [];
|
|
@@ -38,6 +41,10 @@ const liveRoutes = (feed, visibleTo) => {
|
|
|
38
41
|
type: "resync",
|
|
39
42
|
cursor
|
|
40
43
|
});
|
|
44
|
+
else if (refreshes(caught)) queue.push({
|
|
45
|
+
type: "refresh",
|
|
46
|
+
cursor
|
|
47
|
+
});
|
|
41
48
|
else if (changesOf(caught).length > 0) queue.push({
|
|
42
49
|
type: "changes",
|
|
43
50
|
cursor,
|
|
@@ -52,7 +59,11 @@ const liveRoutes = (feed, visibleTo) => {
|
|
|
52
59
|
if (fresh.length === 0) return;
|
|
53
60
|
cursor = fresh.at(-1).id;
|
|
54
61
|
const changes = changesOf(fresh);
|
|
55
|
-
if (
|
|
62
|
+
if (refreshes(fresh)) queue.push({
|
|
63
|
+
type: "refresh",
|
|
64
|
+
cursor
|
|
65
|
+
});
|
|
66
|
+
else if (changes.length > 0) queue.push({
|
|
56
67
|
type: "changes",
|
|
57
68
|
cursor,
|
|
58
69
|
changes
|
|
@@ -69,8 +80,12 @@ const liveRoutes = (feed, visibleTo) => {
|
|
|
69
80
|
}, heartbeatMs);
|
|
70
81
|
while (!stream.aborted) {
|
|
71
82
|
const event = queue.shift();
|
|
72
|
-
if (event)
|
|
73
|
-
|
|
83
|
+
if (!event) {
|
|
84
|
+
await new Promise((resolve) => wake = resolve);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
await stream.writeSSE({ data: JSON.stringify(event) });
|
|
88
|
+
if (event.type === "refresh") return;
|
|
74
89
|
}
|
|
75
90
|
};
|
|
76
91
|
return streamSSE(c, (stream) => follow(stream).finally(() => {
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
//#region src/live/refresh/live-refresh.d.ts
|
|
2
|
+
/** What a server function tells open pages with: `refresh({ user })` once a person's access changed. */
|
|
3
|
+
export type LiveRefresh = {
|
|
4
|
+
/**
|
|
5
|
+
* Tells the open pages of `user`, by their id, to read what they show again, which gives them new live tokens for
|
|
6
|
+
* their access as it is now: call it once the change of their roles or memberships committed. Subqueries of access
|
|
7
|
+
* rules are evaluated when a token is issued, so a token made before stays as it was until then.
|
|
8
|
+
*/
|
|
9
|
+
refresh: (options: {
|
|
10
|
+
user: string;
|
|
11
|
+
}) => Promise<void>;
|
|
12
|
+
};
|
|
13
|
+
//#endregion
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
//#region src/live/refresh/live-refresh.ts
|
|
2
|
+
/** Refreshes through `write`, the notices' writer, or does nothing for an app without live resources, whose pages hold no tokens. */
|
|
3
|
+
const liveRefresh = (write) => ({ refresh: async ({ user }) => {
|
|
4
|
+
if (!write) return;
|
|
5
|
+
await write([user]);
|
|
6
|
+
} });
|
|
7
|
+
//#endregion
|
|
8
|
+
export { liveRefresh };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { quoteIdent } from "../../changes/capture-sql.js";
|
|
2
|
+
import { sql } from "kysely";
|
|
3
|
+
//#region src/live/refresh/refresh-notices.ts
|
|
4
|
+
/** The resource of a notice that tells one user's pages their access changed, keyed by the user's id. */
|
|
5
|
+
const refreshNotice = "$live";
|
|
6
|
+
const textArray = (values) => `{${values.map((value) => JSON.stringify(value)).join(",")}}`;
|
|
7
|
+
/**
|
|
8
|
+
* Tells these users' open pages, through the live stream's notices, that what they may read changed, so they read
|
|
9
|
+
* again and get new live tokens. The table is locked against other writers first, so the notice commits in the order
|
|
10
|
+
* of its id and no reader skips it.
|
|
11
|
+
*/
|
|
12
|
+
const writeRefreshNotices = async (db, schema, userIds) => {
|
|
13
|
+
if (userIds.length === 0) return;
|
|
14
|
+
const table = sql.raw(`${quoteIdent(schema)}."notices"`);
|
|
15
|
+
await db.transaction().execute(async (trx) => {
|
|
16
|
+
await sql`lock table ${table} in share row exclusive mode`.execute(trx);
|
|
17
|
+
await sql`insert into ${table} ("resource", "record_key", "operation") select ${refreshNotice}, u, 'update' from unnest(${textArray([...new Set(userIds)])}::text[]) as u`.execute(trx);
|
|
18
|
+
});
|
|
19
|
+
};
|
|
20
|
+
//#endregion
|
|
21
|
+
export { refreshNotice, writeRefreshNotices };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
//#region src/live/token/key-filter.ts
|
|
2
|
+
const span = {
|
|
3
|
+
start: 0,
|
|
4
|
+
end: 0
|
|
5
|
+
};
|
|
6
|
+
const literalOf = (value) => typeof value === "number" ? {
|
|
7
|
+
kind: "number",
|
|
8
|
+
value,
|
|
9
|
+
raw: String(value),
|
|
10
|
+
span
|
|
11
|
+
} : {
|
|
12
|
+
kind: "string",
|
|
13
|
+
value,
|
|
14
|
+
span
|
|
15
|
+
};
|
|
16
|
+
/** The record with this key, as a filter: each part of the primary key among its one value, as `=` reads a `*` in text as a wildcard. */
|
|
17
|
+
const keyFilter = (model, key) => {
|
|
18
|
+
const parts = model.primaryKey.map((name, i) => ({
|
|
19
|
+
kind: "in",
|
|
20
|
+
field: model.fields[name],
|
|
21
|
+
values: [literalOf(key[i])],
|
|
22
|
+
span
|
|
23
|
+
}));
|
|
24
|
+
return parts.length === 1 ? parts[0] : {
|
|
25
|
+
kind: "and",
|
|
26
|
+
args: parts,
|
|
27
|
+
span
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
//#endregion
|
|
31
|
+
export { keyFilter };
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
//#region src/live/token/live-headers.ts
|
|
2
|
+
/** The headers of a list or record read: it varies with `Prefer`, and carries the live token when one was asked for and made. */
|
|
3
|
+
const liveHeaders = (token) => token ? {
|
|
4
|
+
Vary: "Prefer",
|
|
5
|
+
"Preference-Applied": "live",
|
|
6
|
+
"Protobase-Live": token
|
|
7
|
+
} : { Vary: "Prefer" };
|
|
8
|
+
//#endregion
|
|
9
|
+
export { liveHeaders };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
//#region src/live/token/live-key.ts
|
|
2
|
+
/** What the live token key is derived for, so the same secret signs relay tickets and seals live tokens apart. */
|
|
3
|
+
const info = "protobase live token";
|
|
4
|
+
/** The 256-bit key live tokens are sealed with: HKDF-SHA-256 of the relay's ticket key, which the relay holds too. */
|
|
5
|
+
const liveTokenKey = async (ticketKey) => {
|
|
6
|
+
const secret = await crypto.subtle.importKey("raw", new TextEncoder().encode(ticketKey), "HKDF", false, ["deriveBits"]);
|
|
7
|
+
const bits = await crypto.subtle.deriveBits({
|
|
8
|
+
name: "HKDF",
|
|
9
|
+
hash: "SHA-256",
|
|
10
|
+
salt: /* @__PURE__ */ new Uint8Array(),
|
|
11
|
+
info: new TextEncoder().encode(info)
|
|
12
|
+
}, secret, 256);
|
|
13
|
+
return new Uint8Array(bits);
|
|
14
|
+
};
|
|
15
|
+
//#endregion
|
|
16
|
+
export { liveTokenKey };
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
//#region src/live/token/live-preference.ts
|
|
2
|
+
/**
|
|
3
|
+
* Whether the request asks for a live token: RFC 7240 `Prefer: live`, alone or among other preferences, in one header
|
|
4
|
+
* or several, or `?live=1` where a page cannot set headers.
|
|
5
|
+
*/
|
|
6
|
+
const asksLive = (c) => {
|
|
7
|
+
if (c.req.query("live") === "1") return true;
|
|
8
|
+
return (c.req.header("prefer") ?? "").split(",").some((preference) => preference.split(/[=;]/, 1)[0].trim().toLowerCase() === "live");
|
|
9
|
+
};
|
|
10
|
+
//#endregion
|
|
11
|
+
export { asksLive };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
//#region src/live/token/live-subject.ts
|
|
2
|
+
/** How long a token lasts at most: a visitor's always, longer than the API lets anyone cache a response (it lets none). */
|
|
3
|
+
const liveTokenSeconds = 3600;
|
|
4
|
+
/**
|
|
5
|
+
* Whom a live token is for: a visitor, unbound, for `liveTokenSeconds`; a person signed in with a session of the app,
|
|
6
|
+
* bound to it until it ends, at most `liveTokenSeconds`. Undefined for any other caller, such as an API key or an
|
|
7
|
+
* outside app, and for a session that has ended: they get no token.
|
|
8
|
+
*/
|
|
9
|
+
const liveSubject = async (session, sessionEnd, now = /* @__PURE__ */ new Date()) => {
|
|
10
|
+
const longest = new Date(now.getTime() + liveTokenSeconds * 1e3);
|
|
11
|
+
if (session.anonymous) return {
|
|
12
|
+
anonymous: true,
|
|
13
|
+
expiresAt: longest
|
|
14
|
+
};
|
|
15
|
+
const id = session.signIn?.session;
|
|
16
|
+
if (session.client || typeof id !== "string" || id === "") return;
|
|
17
|
+
const end = await sessionEnd(id);
|
|
18
|
+
if (!end || end.getTime() <= now.getTime()) return;
|
|
19
|
+
return {
|
|
20
|
+
user: String(session.user.id),
|
|
21
|
+
session: id,
|
|
22
|
+
expiresAt: end < longest ? end : longest
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
//#endregion
|
|
26
|
+
export { liveSubject, liveTokenSeconds };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
//#region src/live/token/live-token.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Who a live token is for: a signed-in person in their sign-in session, which ends it, or a visitor, bound to nothing.
|
|
4
|
+
* `expiresAt` is when it stops being taken.
|
|
5
|
+
*/
|
|
6
|
+
export type LiveSubject = {
|
|
7
|
+
user: string;
|
|
8
|
+
session: string;
|
|
9
|
+
expiresAt: Date;
|
|
10
|
+
} | {
|
|
11
|
+
anonymous: true;
|
|
12
|
+
expiresAt: Date;
|
|
13
|
+
};
|
|
14
|
+
//#endregion
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { EncryptJWT } from "jose";
|
|
2
|
+
//#region src/live/token/live-token.ts
|
|
3
|
+
/** The largest token sent: the response's whole header block stays under a proxy's default 4 KB buffer. */
|
|
4
|
+
const maxLiveTokenBytes = 3e3;
|
|
5
|
+
/**
|
|
6
|
+
* The read sealed as a JWE (`dir`, A256GCM) with the live token key, so its caller can neither read nor change the
|
|
7
|
+
* conditions, which may hold keys of records they cannot see. Undefined when it is longer than `maxLiveTokenBytes`.
|
|
8
|
+
*/
|
|
9
|
+
const sealLiveToken = async (key, app, read, subject, now = /* @__PURE__ */ new Date()) => {
|
|
10
|
+
const claims = {
|
|
11
|
+
...read,
|
|
12
|
+
..."session" in subject ? { sid: subject.session } : { anonymous: true }
|
|
13
|
+
};
|
|
14
|
+
const jwt = new EncryptJWT(claims).setProtectedHeader({
|
|
15
|
+
alg: "dir",
|
|
16
|
+
enc: "A256GCM",
|
|
17
|
+
typ: "JWT"
|
|
18
|
+
}).setIssuer(app).setIssuedAt(Math.floor(now.getTime() / 1e3)).setExpirationTime(Math.floor(subject.expiresAt.getTime() / 1e3));
|
|
19
|
+
if ("user" in subject) jwt.setSubject(subject.user);
|
|
20
|
+
const token = await jwt.encrypt(key);
|
|
21
|
+
return token.length > 3e3 ? void 0 : token;
|
|
22
|
+
};
|
|
23
|
+
//#endregion
|
|
24
|
+
export { maxLiveTokenBytes, sealLiveToken };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { Session } from "../../types.js";
|
|
2
|
+
import { LiveSubject } from "./live-token.js";
|
|
3
|
+
import { CheckedFilter, ResourceModel } from "@protobase/schema";
|
|
4
|
+
import { Db, Scope } from "@protobase/query";
|
|
5
|
+
//#region src/live/token/live-tokens.d.ts
|
|
6
|
+
/** What a read gave a live token for: the query's model and scope, the caller's filter and the fields it returned. */
|
|
7
|
+
export type LiveTokenRead = {
|
|
8
|
+
resource: string;
|
|
9
|
+
model: ResourceModel;
|
|
10
|
+
scope: Scope;
|
|
11
|
+
filter?: CheckedFilter;
|
|
12
|
+
fields: string[];
|
|
13
|
+
};
|
|
14
|
+
export type LiveTokens = {
|
|
15
|
+
/** Whom a token would be for, before the read's transaction opens; undefined when the caller gets none. */
|
|
16
|
+
subject: (session: Session) => Promise<LiveSubject | undefined>;
|
|
17
|
+
/** The token for the read, in its REPEATABLE READ transaction; undefined when it cannot be made or is too long. */
|
|
18
|
+
seal: (trx: Db, subject: LiveSubject, read: LiveTokenRead) => Promise<string | undefined>;
|
|
19
|
+
};
|
|
20
|
+
//#endregion
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { liveTokenKey } from "./live-key.js";
|
|
2
|
+
import { liveSubject } from "./live-subject.js";
|
|
3
|
+
import { sealLiveToken } from "./live-token.js";
|
|
4
|
+
import { printFilter } from "@protobase/schema";
|
|
5
|
+
import { sameRowFilter } from "@protobase/query";
|
|
6
|
+
import { sql } from "kysely";
|
|
7
|
+
//#region src/live/token/live-tokens.ts
|
|
8
|
+
/** Live tokens sealed with the key derived from the relay's ticket key, for the app the relay knows as `app`. */
|
|
9
|
+
const liveTokens = (options) => {
|
|
10
|
+
const key = liveTokenKey(options.ticketKey);
|
|
11
|
+
return {
|
|
12
|
+
subject: (session) => liveSubject(session, options.sessionEnd),
|
|
13
|
+
seal: async (trx, subject, read) => {
|
|
14
|
+
const where = await sameRowFilter(trx, read.model, read.scope, read.filter);
|
|
15
|
+
if (where === false) return;
|
|
16
|
+
const { rows } = await sql`select pg_current_snapshot()::text as snapshot`.execute(trx);
|
|
17
|
+
const claims = {
|
|
18
|
+
resource: read.resource,
|
|
19
|
+
...where && { where: printFilter(where) },
|
|
20
|
+
fields: read.fields,
|
|
21
|
+
snapshot: rows[0].snapshot
|
|
22
|
+
};
|
|
23
|
+
return sealLiveToken(await key, options.app, claims, subject);
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
//#endregion
|
|
28
|
+
export { liveTokens };
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { requestAccess } from "../request-access.js";
|
|
2
|
+
import "./refresh/refresh-notices.js";
|
|
2
3
|
import { ringNotice } from "@protobase/schema/internal";
|
|
3
4
|
//#region src/live/visible-notices.ts
|
|
4
5
|
/**
|
|
5
6
|
* Which notices a caller hears of: those of the live resources they may list or read, in their tenant, and, with
|
|
6
|
-
* calls, those of the calls that ring them (`ringNotice`, keyed by the user's id)
|
|
7
|
+
* calls, those of the calls that ring them (`ringNotice`, keyed by the user's id), and those that refresh their
|
|
8
|
+
* access (`refreshNotice`, keyed likewise). A notice names a record, never its
|
|
7
9
|
* values, and the page reads the record again as the caller, so no row filter applies here. A notice of `anyRecord`
|
|
8
10
|
* without a tenant, of a view's source without tenants, reaches every tenant's readers of the view.
|
|
9
11
|
*/
|
|
@@ -16,8 +18,10 @@ const visibleNotices = async (deps, session) => {
|
|
|
16
18
|
readable.set(entry.name, entry.model.tenant ? String(session.tenant) : void 0);
|
|
17
19
|
}
|
|
18
20
|
const rung = deps.calls && !session.anonymous && !session.client ? String(session.user.id) : void 0;
|
|
21
|
+
const own = session.anonymous ? void 0 : String(session.user.id);
|
|
19
22
|
return (notice) => {
|
|
20
23
|
if (notice.resource === ringNotice) return rung !== void 0 && notice.key === rung;
|
|
24
|
+
if (notice.resource === "$live") return own !== void 0 && notice.key === own;
|
|
21
25
|
if (!readable.has(notice.resource)) return false;
|
|
22
26
|
const tenant = readable.get(notice.resource);
|
|
23
27
|
return tenant === void 0 || tenant === notice.tenant || notice.key === "" && notice.tenant === null;
|
package/dist/package.js
CHANGED
package/dist/read-service.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { notFound } from "./problem.js";
|
|
2
|
-
import { requestAccess, requireOperation, visibleFields, writableFields } from "./request-access.js";
|
|
2
|
+
import { ownScope, requestAccess, requireOperation, visibleFields, writableFields } from "./request-access.js";
|
|
3
3
|
import { pickFields } from "./rows.js";
|
|
4
|
-
import { readTransaction } from "./transactions.js";
|
|
5
|
-
import { deletedRows } from "./params.js";
|
|
4
|
+
import { readTransaction, snapshotReadTransaction } from "./transactions.js";
|
|
5
|
+
import { deletedRows, selectedFields } from "./params.js";
|
|
6
6
|
import { fetchReadable } from "./fetch-readable.js";
|
|
7
7
|
import { presentFiles } from "./files/present.js";
|
|
8
8
|
import { rowPermissions } from "./row-permissions.js";
|
|
9
|
+
import { keyFilter } from "./live/token/key-filter.js";
|
|
9
10
|
//#region src/read-service.ts
|
|
10
11
|
/**
|
|
11
12
|
* `edit` for fields the caller may change on this record, `read` for the rest (sensitive ones included); hidden fields
|
|
@@ -21,13 +22,19 @@ const fieldModes = (access, canUpdate) => {
|
|
|
21
22
|
* The record with this key as the caller may see it: readable fields only, inside the caller's tenant and row filter.
|
|
22
23
|
* A key outside the tenant, outside the row filter, or failing a record-level read rule is a plain 404. `showDeleted`
|
|
23
24
|
* also finds a soft-deleted record, and is refused on a resource without a soft delete once the caller may read it.
|
|
25
|
+
* `live` asks for a live token of the read (`token`), for a live resource when the app has one to give and no
|
|
26
|
+
* record-level read rule decides it, which reads no filter: the read then runs in one snapshot. `fields`, the
|
|
27
|
+
* selection of `?fields=`, is checked against the caller's readable fields and is what the token names (`columns`).
|
|
24
28
|
*/
|
|
25
|
-
const readRecord = async (deps, entry, session, key, showDeleted = false) => {
|
|
29
|
+
const readRecord = async (deps, entry, session, key, showDeleted = false, live = false, fields) => {
|
|
26
30
|
const access = await requestAccess(deps, entry, session);
|
|
27
31
|
requireOperation(access, "read");
|
|
28
32
|
const deleted = deletedRows(access.full, showDeleted);
|
|
29
33
|
const names = Object.keys(access.model.fields);
|
|
30
|
-
const
|
|
34
|
+
const subject = live && entry.model.live && deps.liveTokens && !access.resolved.recordChecks.includes("read") ? await deps.liveTokens.subject(session) : void 0;
|
|
35
|
+
const transaction = subject ? snapshotReadTransaction : readTransaction;
|
|
36
|
+
const sealed = subject && selectedFields(access.model, fields);
|
|
37
|
+
const found = await transaction(deps.db, deps.statementTimeoutMs, async (trx) => {
|
|
31
38
|
const current = await fetchReadable(trx, access, key, deleted, {
|
|
32
39
|
etagFields: names,
|
|
33
40
|
fields: visibleFields(access)
|
|
@@ -35,18 +42,32 @@ const readRecord = async (deps, entry, session, key, showDeleted = false) => {
|
|
|
35
42
|
if (!current) return void 0;
|
|
36
43
|
const record = pickFields(current.record, names);
|
|
37
44
|
const [row] = await rowPermissions(trx, access, [record]);
|
|
45
|
+
const full = deleted === "show" ? {
|
|
46
|
+
...access.full,
|
|
47
|
+
softDelete: void 0
|
|
48
|
+
} : access.full;
|
|
49
|
+
const read = {
|
|
50
|
+
resource: entry.name,
|
|
51
|
+
model: full,
|
|
52
|
+
scope: ownScope(access, full),
|
|
53
|
+
filter: keyFilter(full, key),
|
|
54
|
+
fields: sealed || names
|
|
55
|
+
};
|
|
56
|
+
const token = subject && await deps.liveTokens.seal(trx, subject, read);
|
|
38
57
|
return {
|
|
39
58
|
record,
|
|
40
59
|
etag: current.etag,
|
|
41
60
|
permissions: {
|
|
42
61
|
...row,
|
|
43
62
|
fields: fieldModes(access, row.update)
|
|
44
|
-
}
|
|
63
|
+
},
|
|
64
|
+
token
|
|
45
65
|
};
|
|
46
66
|
});
|
|
47
67
|
if (!found) throw notFound(`No ${entry.name} with this key`);
|
|
48
68
|
return {
|
|
49
69
|
...found,
|
|
70
|
+
columns: selectedFields(access.model, fields),
|
|
50
71
|
record: (await presentFiles(access, [found.record]))[0]
|
|
51
72
|
};
|
|
52
73
|
};
|
package/dist/records.d.ts
CHANGED
package/dist/request-access.d.ts
CHANGED
|
@@ -10,6 +10,8 @@ import { batchAggregates } from "../aggregate-batch.js";
|
|
|
10
10
|
import { mapRecords } from "../map-service.js";
|
|
11
11
|
import { uploadFile } from "../files/upload.js";
|
|
12
12
|
import { returnPreference } from "./preferences.js";
|
|
13
|
+
import { asksLive } from "../live/token/live-preference.js";
|
|
14
|
+
import { liveHeaders } from "../live/token/live-headers.js";
|
|
13
15
|
import { resolveTarget, unknownAction } from "./target.js";
|
|
14
16
|
import { Hono } from "hono";
|
|
15
17
|
import { encodeKey } from "@protobase/schema/internal";
|
|
@@ -20,8 +22,11 @@ const warningHeader = (warning) => warning ? { "X-Protobase-Warning": warning }
|
|
|
20
22
|
const listMethod = async (c, deps, entry, action, query, within) => {
|
|
21
23
|
const session = c.get("session");
|
|
22
24
|
if (action === "") {
|
|
23
|
-
const { body, warning } = await listRecords(deps, entry, session, query, void 0, false, within);
|
|
24
|
-
return c.json(body, 200,
|
|
25
|
+
const { body, warning, token } = await listRecords(deps, entry, session, query, void 0, false, within, asksLive(c));
|
|
26
|
+
return c.json(body, 200, {
|
|
27
|
+
...warningHeader(warning),
|
|
28
|
+
...liveHeaders(token)
|
|
29
|
+
});
|
|
25
30
|
}
|
|
26
31
|
if (action === "facets") {
|
|
27
32
|
const { body, warning } = await facets(deps, entry, session, query, within);
|
|
@@ -74,8 +79,11 @@ const collectionRoutes = (deps) => {
|
|
|
74
79
|
if (action !== "search") return unknownAction(action);
|
|
75
80
|
const body = parseParams(listParams, await c.req.json());
|
|
76
81
|
const within = await belongingFilter(deps, entry, c.get("session"), parent, key);
|
|
77
|
-
const { body: page, warning } = await listRecords(deps, entry, c.get("session"), body, searchFilterLength, false, within);
|
|
78
|
-
return c.json(page, 200,
|
|
82
|
+
const { body: page, warning, token } = await listRecords(deps, entry, c.get("session"), body, searchFilterLength, false, within, asksLive(c));
|
|
83
|
+
return c.json(page, 200, {
|
|
84
|
+
...warningHeader(warning),
|
|
85
|
+
...liveHeaders(token)
|
|
86
|
+
});
|
|
79
87
|
});
|
|
80
88
|
app.post("/:target", async (c) => {
|
|
81
89
|
const { entry, action } = resolveTarget(deps, c.req.param("target"));
|
|
@@ -83,8 +91,11 @@ const collectionRoutes = (deps) => {
|
|
|
83
91
|
if (action === "upload") return c.json(await uploadFile(deps, entry, session, c.req.raw), 201);
|
|
84
92
|
const body = await c.req.json();
|
|
85
93
|
if (action === "search") {
|
|
86
|
-
const { body: page, warning } = await listRecords(deps, entry, session, body, searchFilterLength);
|
|
87
|
-
return c.json(page, 200,
|
|
94
|
+
const { body: page, warning, token } = await listRecords(deps, entry, session, body, searchFilterLength, false, void 0, asksLive(c));
|
|
95
|
+
return c.json(page, 200, {
|
|
96
|
+
...warningHeader(warning),
|
|
97
|
+
...liveHeaders(token)
|
|
98
|
+
});
|
|
88
99
|
}
|
|
89
100
|
if (action === "batchAggregates") {
|
|
90
101
|
const { body: read, warning } = await batchAggregates(deps, entry, session, body);
|
package/dist/routes/record.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { notFound } from "../problem.js";
|
|
2
2
|
import { pickFields } from "../rows.js";
|
|
3
|
-
import { selectedFields } from "../params.js";
|
|
4
3
|
import { keyFromPath } from "../key.js";
|
|
5
4
|
import { runWrite } from "../write-pipeline.js";
|
|
6
5
|
import { readRecord } from "../read-service.js";
|
|
@@ -8,6 +7,8 @@ import { postComment } from "../comments/post-comment.js";
|
|
|
8
7
|
import { readComments } from "../comments/read-comments.js";
|
|
9
8
|
import { auditOrigin } from "../audit/origin.js";
|
|
10
9
|
import { returnPreference } from "./preferences.js";
|
|
10
|
+
import { asksLive } from "../live/token/live-preference.js";
|
|
11
|
+
import { liveHeaders } from "../live/token/live-headers.js";
|
|
11
12
|
import { resolveTarget } from "./target.js";
|
|
12
13
|
import { revealField } from "../reveal-service.js";
|
|
13
14
|
import { readHistory } from "../history/read-history.js";
|
|
@@ -28,16 +29,15 @@ const recordRoutes = (deps) => {
|
|
|
28
29
|
return c.json(await readRecordCalls(deps, entry, c.get("session"), key));
|
|
29
30
|
}
|
|
30
31
|
if (c.req.param("key").endsWith(":mentionable")) return c.json(await mentionable(deps, entry, c.get("session"), keyFromPath(c, entry, ":mentionable"), c.req.query()));
|
|
31
|
-
const found = await readRecord(deps, entry, c.get("session"), keyFromPath(c, entry), c.req.query("show_deleted") === "true");
|
|
32
|
-
const columns = selectedFields({
|
|
33
|
-
...entry.model,
|
|
34
|
-
fields: Object.fromEntries(Object.keys(found.record).map((name) => [name, entry.model.fields[name]]))
|
|
35
|
-
}, c.req.query("fields"));
|
|
32
|
+
const found = await readRecord(deps, entry, c.get("session"), keyFromPath(c, entry), c.req.query("show_deleted") === "true", asksLive(c), c.req.query("fields"));
|
|
36
33
|
return c.json({
|
|
37
|
-
...pickFields(found.record, columns),
|
|
34
|
+
...pickFields(found.record, found.columns),
|
|
38
35
|
etag: found.etag,
|
|
39
36
|
permissions: found.permissions
|
|
40
|
-
}, 200, {
|
|
37
|
+
}, 200, {
|
|
38
|
+
ETag: found.etag,
|
|
39
|
+
...liveHeaders(found.token)
|
|
40
|
+
});
|
|
41
41
|
});
|
|
42
42
|
const reveal = async (c, entry) => {
|
|
43
43
|
const body = await c.req.json();
|
package/dist/sql-parts.d.ts
CHANGED
package/dist/webhooks/attempt.js
CHANGED
|
@@ -14,6 +14,7 @@ import { maxTries, nextRetryDelay } from "./retry-schedule.js";
|
|
|
14
14
|
import { eventChange, subscriberEvents } from "./subscriber-view.js";
|
|
15
15
|
import { attemptDelivery } from "./attempt.js";
|
|
16
16
|
import { subscriptionProblems, subscriptionRouter } from "./route-events.js";
|
|
17
|
+
import { liveRefresh } from "../live/refresh/live-refresh.js";
|
|
17
18
|
import { tableSubscriptionName } from "./table/options.js";
|
|
18
19
|
import { sendTestJob } from "./table/schema-sql.js";
|
|
19
20
|
import { testEvent } from "./test-event.js";
|
|
@@ -49,7 +50,7 @@ const deliveryGroup = ({ subscription, change }) => `${subscription.name}:${chan
|
|
|
49
50
|
*
|
|
50
51
|
* No jobs without a resource with events or history; the subscriptions must name declared events.
|
|
51
52
|
*/
|
|
52
|
-
const createWebhooks = ({ deps, subscriptions, functions, channels, schema, log, table, onChanges }) => {
|
|
53
|
+
const createWebhooks = ({ deps, subscriptions, functions, channels, live = liveRefresh(void 0), schema, log, table, onChanges }) => {
|
|
53
54
|
const entries = deps.registry.entries;
|
|
54
55
|
const models = entries.map((entry) => entry.model);
|
|
55
56
|
const problems = subscriptionProblems(subscriptions, models, Object.keys(functions));
|
|
@@ -72,6 +73,7 @@ const createWebhooks = ({ deps, subscriptions, functions, channels, schema, log,
|
|
|
72
73
|
functions,
|
|
73
74
|
records,
|
|
74
75
|
channels,
|
|
76
|
+
live,
|
|
75
77
|
attempt: tried,
|
|
76
78
|
signal,
|
|
77
79
|
allowPrivateAddresses
|
package/dist/write-shared.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { Row } from "./types.js";
|
|
|
3
3
|
import "./deps.js";
|
|
4
4
|
import "./request-access.js";
|
|
5
5
|
import "./records.js";
|
|
6
|
-
import "@protobase/schema";
|
|
6
|
+
import { CheckedFilter } from "@protobase/schema";
|
|
7
7
|
import { Db } from "@protobase/query";
|
|
8
8
|
//#region src/write-shared.d.ts
|
|
9
9
|
export type WriteResult = {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/server",
|
|
3
|
-
"version": "0.133.
|
|
3
|
+
"version": "0.133.4",
|
|
4
4
|
"description": "The Protobase REST API as a Hono app, with Better Auth sign-in.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -44,11 +44,11 @@
|
|
|
44
44
|
"@better-auth/sso": "^1.7.12",
|
|
45
45
|
"@livekit/protocol": "1.53.1",
|
|
46
46
|
"@modelcontextprotocol/server": "^2.3.1",
|
|
47
|
-
"@protobase/layout": "0.133.
|
|
48
|
-
"@protobase/query": "0.133.
|
|
49
|
-
"@protobase/schema": "0.133.
|
|
50
|
-
"@protobase/workflow-plugins": "0.133.
|
|
51
|
-
"@protobase/workflows": "0.133.
|
|
47
|
+
"@protobase/layout": "0.133.4",
|
|
48
|
+
"@protobase/query": "0.133.4",
|
|
49
|
+
"@protobase/schema": "0.133.4",
|
|
50
|
+
"@protobase/workflow-plugins": "0.133.4",
|
|
51
|
+
"@protobase/workflows": "0.133.4",
|
|
52
52
|
"@react-email/render": "^2.1.0",
|
|
53
53
|
"@react-pdf/primitives": "^4.4.0",
|
|
54
54
|
"@react-pdf/renderer": "^4.9.1",
|