@protobase/server 0.0.0-stage → 0.1.1
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/LICENSE +202 -0
- package/dist/aggregate-service.js +135 -0
- package/dist/audit/console-queue.d.ts +5 -0
- package/dist/audit/console-queue.js +5 -0
- package/dist/auth/jwt.d.ts +21 -0
- package/dist/auth/jwt.js +49 -0
- package/dist/batch/refs.js +31 -0
- package/dist/batch/reorder.js +79 -0
- package/dist/batch/run-batch.js +105 -0
- package/dist/batch/schema.js +51 -0
- package/dist/better-auth/authenticator.d.ts +22 -0
- package/dist/better-auth/authenticator.js +21 -0
- package/dist/better-auth/create-auth.d.ts +1252 -0
- package/dist/better-auth/create-auth.js +104 -0
- package/dist/better-auth/jwks-cache.d.ts +9 -0
- package/dist/better-auth/jwks-cache.js +31 -0
- package/dist/better-auth/password-reset.js +32 -0
- package/dist/better-auth/status-route.js +19 -0
- package/dist/better-auth/tokens.d.ts +18 -0
- package/dist/better-auth/tokens.js +37 -0
- package/dist/better-auth/users.d.ts +50 -0
- package/dist/better-auth/users.js +111 -0
- package/dist/check-shell.js +17 -0
- package/dist/check-views.js +45 -0
- package/dist/create-admin.d.ts +23 -0
- package/dist/create-admin.js +85 -0
- package/dist/error-handler.js +44 -0
- package/dist/etag.js +22 -0
- package/dist/filter-input.js +28 -0
- package/dist/filter-shape.js +25 -0
- package/dist/hash.js +10 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +10 -0
- package/dist/key.js +22 -0
- package/dist/list-service.js +96 -0
- package/dist/mail/mail-settings.js +26 -0
- package/dist/mail/smtp-mailer.d.ts +11 -0
- package/dist/mail/smtp-mailer.js +17 -0
- package/dist/meta.js +63 -0
- package/dist/openapi/components.js +331 -0
- package/dist/openapi/document.js +74 -0
- package/dist/openapi/naming.js +4 -0
- package/dist/openapi/resource-paths.js +417 -0
- package/dist/openapi/schemas.js +93 -0
- package/dist/params.js +48 -0
- package/dist/problem.d.ts +17 -0
- package/dist/problem.js +43 -0
- package/dist/read-service.js +65 -0
- package/dist/records.js +66 -0
- package/dist/registry.js +44 -0
- package/dist/request-access.js +97 -0
- package/dist/resource-source.d.ts +35 -0
- package/dist/resource-source.js +22 -0
- package/dist/reveal-service.js +43 -0
- package/dist/routes/batch.js +21 -0
- package/dist/routes/collection.js +63 -0
- package/dist/routes/docs.js +20 -0
- package/dist/routes/meta.js +22 -0
- package/dist/routes/preferences.js +12 -0
- package/dist/routes/record.js +97 -0
- package/dist/routes/target.js +18 -0
- package/dist/row-permissions.js +69 -0
- package/dist/rows.js +12 -0
- package/dist/scan-guard.js +72 -0
- package/dist/sql-parts.js +32 -0
- package/dist/tenant.js +10 -0
- package/dist/transactions.js +14 -0
- package/dist/types.d.ts +97 -0
- package/dist/validate-body.js +73 -0
- package/dist/view-access.js +54 -0
- package/dist/view-related.js +59 -0
- package/dist/write-pipeline.js +94 -0
- package/dist/write-shared.js +52 -0
- package/dist/write-update.js +45 -0
- package/package.json +39 -3
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { badRequest } from "./problem.js";
|
|
2
|
+
import { checkedFilter } from "./filter-input.js";
|
|
3
|
+
import { readScope, requestAccess, requireOperation } from "./request-access.js";
|
|
4
|
+
import { readTransaction } from "./transactions.js";
|
|
5
|
+
import { columnId, filterCondition, scopeConditions, tableId, whereClause } from "./sql-parts.js";
|
|
6
|
+
import { parseParams } from "./params.js";
|
|
7
|
+
import { facetCounts, histogram, series } from "@protobase/query";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
import { sql } from "kysely";
|
|
10
|
+
//#region src/aggregate-service.ts
|
|
11
|
+
const field = z.string().min(1);
|
|
12
|
+
const filter = z.string().optional();
|
|
13
|
+
const facetParams = z.object({
|
|
14
|
+
field,
|
|
15
|
+
filter,
|
|
16
|
+
limit: z.coerce.number().int().optional()
|
|
17
|
+
});
|
|
18
|
+
const seriesParams = z.object({
|
|
19
|
+
field,
|
|
20
|
+
filter,
|
|
21
|
+
range: z.enum([
|
|
22
|
+
"7d",
|
|
23
|
+
"30d",
|
|
24
|
+
"90d",
|
|
25
|
+
"1y",
|
|
26
|
+
"all"
|
|
27
|
+
]).optional(),
|
|
28
|
+
from: z.string().optional(),
|
|
29
|
+
to: z.string().optional(),
|
|
30
|
+
granularity: z.enum([
|
|
31
|
+
"hour",
|
|
32
|
+
"day",
|
|
33
|
+
"week",
|
|
34
|
+
"month"
|
|
35
|
+
]).default("day"),
|
|
36
|
+
time_zone: z.string().optional()
|
|
37
|
+
});
|
|
38
|
+
const histogramParams = z.object({
|
|
39
|
+
field,
|
|
40
|
+
filter,
|
|
41
|
+
buckets: z.coerce.number().int().default(20)
|
|
42
|
+
});
|
|
43
|
+
const rangeDays = {
|
|
44
|
+
"7d": 7,
|
|
45
|
+
"30d": 30,
|
|
46
|
+
"90d": 90,
|
|
47
|
+
"1y": 365
|
|
48
|
+
};
|
|
49
|
+
const scoped = async (deps, entry, session, source) => {
|
|
50
|
+
const access = await requestAccess(deps, entry, session);
|
|
51
|
+
requireOperation(access, "list");
|
|
52
|
+
return {
|
|
53
|
+
access,
|
|
54
|
+
model: access.model,
|
|
55
|
+
filter: checkedFilter(access.model, source),
|
|
56
|
+
scope: readScope(access)
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
/** Counts per value of a field, ignoring the filter's own terms on that field (AIP-160 filters, UI facet panels). */
|
|
60
|
+
const facets = async (deps, entry, session, input) => {
|
|
61
|
+
const params = parseParams(facetParams, input);
|
|
62
|
+
const { model, filter: checked, scope } = await scoped(deps, entry, session, params.filter);
|
|
63
|
+
const counts = await readTransaction(deps.db, deps.statementTimeoutMs, (trx) => facetCounts(trx, model, params.field, checked, {
|
|
64
|
+
statementTimeoutMs: deps.statementTimeoutMs,
|
|
65
|
+
...params.limit !== void 0 && { limit: params.limit },
|
|
66
|
+
scope
|
|
67
|
+
}));
|
|
68
|
+
return {
|
|
69
|
+
field: params.field,
|
|
70
|
+
facets: counts
|
|
71
|
+
};
|
|
72
|
+
};
|
|
73
|
+
const earliest = async (deps, access, fieldName, scope) => {
|
|
74
|
+
const target = access.model.fields[fieldName];
|
|
75
|
+
const conditions = [...scopeConditions(access.full, scope.tenantValue), ...filterCondition(access.full, scope.rowFilter)];
|
|
76
|
+
return (await readTransaction(deps.db, deps.statementTimeoutMs, (trx) => sql`select min(${columnId(target)})::text as lowest from ${tableId(access.full)} as t${whereClause(conditions)}`.execute(trx))).rows[0]?.lowest ?? void 0;
|
|
77
|
+
};
|
|
78
|
+
const bound = (model, fieldName, value) => model.fields[fieldName]?.type === "date" ? value.slice(0, 10) : value;
|
|
79
|
+
const seriesRange = async (deps, access, params, scope) => {
|
|
80
|
+
const to = params.to ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
81
|
+
const { model } = access;
|
|
82
|
+
if (params.from) return {
|
|
83
|
+
from: bound(model, params.field, params.from),
|
|
84
|
+
to: bound(model, params.field, to)
|
|
85
|
+
};
|
|
86
|
+
const range = params.range ?? "30d";
|
|
87
|
+
if (range !== "all") {
|
|
88
|
+
const from = (/* @__PURE__ */ new Date(Date.now() - rangeDays[range] * 864e5)).toISOString();
|
|
89
|
+
return {
|
|
90
|
+
from: bound(model, params.field, from),
|
|
91
|
+
to: bound(model, params.field, to)
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
const lowest = await earliest(deps, access, params.field, scope);
|
|
95
|
+
return lowest ? {
|
|
96
|
+
from: bound(model, params.field, lowest),
|
|
97
|
+
to: bound(model, params.field, to)
|
|
98
|
+
} : void 0;
|
|
99
|
+
};
|
|
100
|
+
/** Row counts per calendar bucket of a date or timestamp field, empty buckets included. */
|
|
101
|
+
const timeSeries = async (deps, entry, session, input) => {
|
|
102
|
+
const params = parseParams(seriesParams, input);
|
|
103
|
+
const { access, model, filter: checked, scope } = await scoped(deps, entry, session, params.filter);
|
|
104
|
+
if (!model.fields[params.field]) throw badRequest("invalid-parameter", `Unknown field "${params.field}"`, { errors: [{
|
|
105
|
+
parameter: "field",
|
|
106
|
+
message: "Unknown field"
|
|
107
|
+
}] });
|
|
108
|
+
const range = await seriesRange(deps, access, params, scope);
|
|
109
|
+
const timeZone = params.time_zone ?? "UTC";
|
|
110
|
+
const points = range ? await readTransaction(deps.db, deps.statementTimeoutMs, (trx) => series(trx, model, params.field, {
|
|
111
|
+
range,
|
|
112
|
+
granularity: params.granularity,
|
|
113
|
+
timeZone,
|
|
114
|
+
...checked && { filter: checked },
|
|
115
|
+
scope
|
|
116
|
+
})) : [];
|
|
117
|
+
return {
|
|
118
|
+
field: params.field,
|
|
119
|
+
granularity: params.granularity,
|
|
120
|
+
time_zone: timeZone,
|
|
121
|
+
points
|
|
122
|
+
};
|
|
123
|
+
};
|
|
124
|
+
/** Equal-width buckets between the filtered minimum and maximum of a numeric field. */
|
|
125
|
+
const numericHistogram = async (deps, entry, session, input) => {
|
|
126
|
+
const params = parseParams(histogramParams, input);
|
|
127
|
+
const { model, filter: checked, scope } = await scoped(deps, entry, session, params.filter);
|
|
128
|
+
const result = await readTransaction(deps.db, deps.statementTimeoutMs, (trx) => histogram(trx, model, params.field, checked, params.buckets, scope));
|
|
129
|
+
return {
|
|
130
|
+
field: params.field,
|
|
131
|
+
...result
|
|
132
|
+
};
|
|
133
|
+
};
|
|
134
|
+
//#endregion
|
|
135
|
+
export { facets, numericHistogram, timeSeries };
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { AuditQueue } from "../types.js";
|
|
2
|
+
//#region src/audit/console-queue.d.ts
|
|
3
|
+
/** The stand-in queue: prints each event as one JSON line, so nothing is kept. */
|
|
4
|
+
export declare const consoleAuditQueue: (print?: (line: string) => void) => AuditQueue;
|
|
5
|
+
//#endregion
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
//#region src/audit/console-queue.ts
|
|
2
|
+
/** The stand-in queue: prints each event as one JSON line, so nothing is kept. */
|
|
3
|
+
const consoleAuditQueue = (print = console.info) => ({ publish: async (event) => print(`[audit] ${JSON.stringify(event)}`) });
|
|
4
|
+
//#endregion
|
|
5
|
+
export { consoleAuditQueue };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { Authenticator, TenantValue } from "../types.js";
|
|
2
|
+
import { JWTVerifyGetKey } from "jose";
|
|
3
|
+
//#region src/auth/jwt.d.ts
|
|
4
|
+
export type JwtOptions = {
|
|
5
|
+
/** JWKS endpoint of the identity provider; or pass `keys`, for example `createLocalJWKSet`. */
|
|
6
|
+
jwksUrl?: string | URL;
|
|
7
|
+
keys?: JWTVerifyGetKey;
|
|
8
|
+
issuer?: string;
|
|
9
|
+
audience?: string;
|
|
10
|
+
/** Claim holding the roles, an array, or a string separated by spaces or commas. Default `roles`. */
|
|
11
|
+
rolesClaim?: string;
|
|
12
|
+
/** Claim holding the tenant. Default `tenant`. */
|
|
13
|
+
tenantClaim?: string;
|
|
14
|
+
/** Accepted signature algorithms. Default: asymmetric ones only, so a token can never be "verified" with a public key used as an HMAC secret. */
|
|
15
|
+
algorithms?: string[];
|
|
16
|
+
/** A fixed tenant (or resolver) used instead of any claim, for single-tenant deployments. */
|
|
17
|
+
tenant?: TenantValue | (() => Promise<TenantValue | undefined>);
|
|
18
|
+
};
|
|
19
|
+
/** Verifies `Authorization: Bearer <jwt>` against a JWKS; `sub` is the user id. */
|
|
20
|
+
export declare const jwtAuthenticator: (options: JwtOptions) => Authenticator;
|
|
21
|
+
//#endregion
|
package/dist/auth/jwt.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { unauthorized } from "../problem.js";
|
|
2
|
+
import { createRemoteJWKSet, errors, jwtVerify } from "jose";
|
|
3
|
+
//#region src/auth/jwt.ts
|
|
4
|
+
const asymmetric = [
|
|
5
|
+
"EdDSA",
|
|
6
|
+
"ES256",
|
|
7
|
+
"ES384",
|
|
8
|
+
"ES512",
|
|
9
|
+
"RS256",
|
|
10
|
+
"RS384",
|
|
11
|
+
"RS512",
|
|
12
|
+
"PS256",
|
|
13
|
+
"PS384",
|
|
14
|
+
"PS512"
|
|
15
|
+
];
|
|
16
|
+
const rolesOf = (claim) => {
|
|
17
|
+
if (typeof claim === "string") return claim.split(/[\s,]+/).filter(Boolean);
|
|
18
|
+
return Array.isArray(claim) ? claim.filter((role) => typeof role === "string") : [];
|
|
19
|
+
};
|
|
20
|
+
/** Verifies `Authorization: Bearer <jwt>` against a JWKS; `sub` is the user id. */
|
|
21
|
+
const jwtAuthenticator = (options) => {
|
|
22
|
+
const { rolesClaim = "roles", tenantClaim = "tenant" } = options;
|
|
23
|
+
const keys = options.keys ?? (options.jwksUrl ? createRemoteJWKSet(new URL(options.jwksUrl)) : void 0);
|
|
24
|
+
if (!keys) throw new Error("jwtAuthenticator needs jwksUrl or keys");
|
|
25
|
+
return async (request) => {
|
|
26
|
+
const [scheme, token] = (request.headers.get("authorization") ?? "").split(" ");
|
|
27
|
+
if (scheme?.toLowerCase() !== "bearer" || !token) throw unauthorized("Send a bearer token in the Authorization header");
|
|
28
|
+
const { sub, [tenantClaim]: tenant, [rolesClaim]: roles } = (await jwtVerify(token, keys, {
|
|
29
|
+
algorithms: options.algorithms ?? asymmetric,
|
|
30
|
+
...options.issuer && { issuer: options.issuer },
|
|
31
|
+
...options.audience && { audience: options.audience }
|
|
32
|
+
}).catch((error) => {
|
|
33
|
+
if (error instanceof errors.JOSEError) throw unauthorized("The bearer token is invalid or expired");
|
|
34
|
+
throw error;
|
|
35
|
+
})).payload;
|
|
36
|
+
if (!sub) throw unauthorized("The bearer token has no subject");
|
|
37
|
+
const claimed = typeof tenant === "string" || typeof tenant === "number" ? tenant : void 0;
|
|
38
|
+
const tenantValue = options.tenant === void 0 ? claimed : typeof options.tenant === "function" ? await options.tenant() : options.tenant;
|
|
39
|
+
return {
|
|
40
|
+
user: {
|
|
41
|
+
id: sub,
|
|
42
|
+
roles: rolesOf(roles)
|
|
43
|
+
},
|
|
44
|
+
...tenantValue !== void 0 && { tenant: tenantValue }
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
//#endregion
|
|
49
|
+
export { jwtAuthenticator };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { badRequest } from "../problem.js";
|
|
2
|
+
import { decodeKeyText } from "../key.js";
|
|
3
|
+
import { encodeKey } from "@protobase/schema";
|
|
4
|
+
//#region src/batch/refs.ts
|
|
5
|
+
const isRef = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && "$ref" in value;
|
|
6
|
+
const valueOf = (created, ref) => {
|
|
7
|
+
const target = created.get(ref.$ref);
|
|
8
|
+
if (!target) throw badRequest("unknown-ref", `"${ref.$ref}" is not the ref of an earlier create in this batch`);
|
|
9
|
+
if (ref.field) {
|
|
10
|
+
const value = target.record[ref.field];
|
|
11
|
+
if (typeof value !== "string" && typeof value !== "number") throw badRequest("unknown-ref", `"${ref.$ref}" has no readable field "${ref.field}" to point at`);
|
|
12
|
+
return value;
|
|
13
|
+
}
|
|
14
|
+
if (target.key.length !== 1) throw badRequest("unknown-ref", `"${ref.$ref}" has a composite key; name the field to point at with { $ref, field }`);
|
|
15
|
+
return target.key[0];
|
|
16
|
+
};
|
|
17
|
+
/** Replaces every `{ $ref }` in a record's values with the key (or `field`) of the record it names. */
|
|
18
|
+
const resolveData = (created, data) => Object.fromEntries(Object.entries(data).map(([name, value]) => [name, isRef(value) ? valueOf(created, value) : value]));
|
|
19
|
+
/** A batch key as typed key parts, for `entry`. */
|
|
20
|
+
const resolveKey = (created, entry, input) => {
|
|
21
|
+
if (isRef(input)) {
|
|
22
|
+
const target = created.get(input.$ref);
|
|
23
|
+
if (!target) throw badRequest("unknown-ref", `"${input.$ref}" is not the ref of an earlier create in this batch`);
|
|
24
|
+
return input.field ? [valueOf(created, input)] : [...target.key];
|
|
25
|
+
}
|
|
26
|
+
if (typeof input === "number") return decodeKeyText(entry, String(input));
|
|
27
|
+
if (typeof input === "string") return decodeKeyText(entry, input);
|
|
28
|
+
return decodeKeyText(entry, encodeKey(input.map((part) => isRef(part) ? valueOf(created, part) : part)));
|
|
29
|
+
};
|
|
30
|
+
//#endregion
|
|
31
|
+
export { resolveData, resolveKey };
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { badRequest } from "../problem.js";
|
|
2
|
+
import { tenantScope } from "../tenant.js";
|
|
3
|
+
import { requireOperation, targetFilter, writableFields } from "../request-access.js";
|
|
4
|
+
import { columnId, keyConditions, scopeConditions, tableId, whereClause } from "../sql-parts.js";
|
|
5
|
+
import { fetchRecord } from "../records.js";
|
|
6
|
+
import { missing, shown } from "../write-shared.js";
|
|
7
|
+
import { validateBody } from "../validate-body.js";
|
|
8
|
+
import { applyUpdate, planUpdate } from "../write-update.js";
|
|
9
|
+
import { encodeKey } from "@protobase/schema";
|
|
10
|
+
import { sql } from "kysely";
|
|
11
|
+
//#region src/batch/reorder.ts
|
|
12
|
+
const checkViolation = "23514";
|
|
13
|
+
const isDatabaseCode = (error, code) => error instanceof Error && error.code === code;
|
|
14
|
+
/**
|
|
15
|
+
* Moves the affected rows out of the range in use, in one statement per row and without touching their ETags, so the
|
|
16
|
+
* final positions can be written without any two rows colliding on a non-deferrable unique index.
|
|
17
|
+
* First above the highest value in the column; when a check constraint refuses that, below the lowest (negative).
|
|
18
|
+
* The first attempt runs in a savepoint, so a refusal costs nothing.
|
|
19
|
+
*/
|
|
20
|
+
const moveAside = async (trx, access, field, keys) => {
|
|
21
|
+
const { full } = access;
|
|
22
|
+
const column = columnId(full.fields[field]);
|
|
23
|
+
const tenant = tenantScope(access.entry, access.session)?.tenantValue;
|
|
24
|
+
const bounds = (await sql`select max(${column}) as high, min(${column}) as low from ${tableId(full)} as t`.execute(trx)).rows[0];
|
|
25
|
+
const assign = async (temporary) => {
|
|
26
|
+
for (const [rank, key] of keys.entries()) {
|
|
27
|
+
const conditions = [...scopeConditions(full, tenant), ...keyConditions(full, key)];
|
|
28
|
+
await sql`update ${tableId(full)} as t set ${column} = ${temporary(rank)}${whereClause(conditions)}`.execute(trx);
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
await sql`savepoint reorder_aside`.execute(trx);
|
|
32
|
+
try {
|
|
33
|
+
await assign((rank) => Number(bounds.high ?? 0) + 1 + rank);
|
|
34
|
+
await sql`release savepoint reorder_aside`.execute(trx);
|
|
35
|
+
} catch (error) {
|
|
36
|
+
if (!isDatabaseCode(error, checkViolation)) throw error;
|
|
37
|
+
await sql`rollback to savepoint reorder_aside`.execute(trx);
|
|
38
|
+
await assign((rank) => Math.min(Number(bounds.low ?? 0), 0) - 1 - rank);
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* `reorder`: the listed records end up with `field` = 1, 2, 3, ... in the given order. Only records whose value changes
|
|
43
|
+
* are written, each as an ordinary update (validation, access, ETag, hooks); they are first moved aside (see `moveAside`)
|
|
44
|
+
* so that a unique index such as (invoice_id, position) is never violated half way. Everything checks out before any row moves.
|
|
45
|
+
*/
|
|
46
|
+
const reorderIn = async (trx, deps, access, input) => {
|
|
47
|
+
const { entry, full } = access;
|
|
48
|
+
requireOperation(access, "update");
|
|
49
|
+
const field = full.fields[input.field];
|
|
50
|
+
validateBody(access, "update", { [input.field]: 1 });
|
|
51
|
+
if (field?.type !== "integer" && field?.type !== "bigint") throw badRequest("invalid-parameter", `"${input.field}" must be an integer field to order by`);
|
|
52
|
+
if (!writableFields(access, "update").includes(input.field)) throw badRequest("invalid-parameter", `"${input.field}" is read-only`);
|
|
53
|
+
const names = input.keys.map((key) => encodeKey(key));
|
|
54
|
+
if (new Set(names).size !== names.length) throw badRequest("invalid-parameter", "A record appears twice in keys");
|
|
55
|
+
const tenant = tenantScope(entry, access.session)?.tenantValue;
|
|
56
|
+
const target = targetFilter(access, "update");
|
|
57
|
+
const current = await Promise.all(input.keys.map(async (key) => {
|
|
58
|
+
const found = await fetchRecord(trx, entry, key, tenant, {
|
|
59
|
+
deleted: "hide",
|
|
60
|
+
lock: true,
|
|
61
|
+
...target && { filter: target },
|
|
62
|
+
etagFields: Object.keys(access.model.fields)
|
|
63
|
+
});
|
|
64
|
+
if (!found) throw missing(entry);
|
|
65
|
+
return found;
|
|
66
|
+
}));
|
|
67
|
+
const changing = input.keys.flatMap((key, i) => Number(current[i].record[input.field]) === i + 1 ? [] : [i]);
|
|
68
|
+
const plans = /* @__PURE__ */ new Map();
|
|
69
|
+
for (const i of changing) plans.set(i, await planUpdate(trx, access, input.keys[i], { [input.field]: i + 1 }, input.etags[names[i]] ?? null));
|
|
70
|
+
if (changing.length > 0) await moveAside(trx, access, input.field, changing.map((i) => input.keys[i]));
|
|
71
|
+
const results = [];
|
|
72
|
+
for (const [i, key] of input.keys.entries()) {
|
|
73
|
+
const plan = plans.get(i);
|
|
74
|
+
results.push(shown(access, plan ? await applyUpdate(trx, deps, access, key, plan) : current[i]));
|
|
75
|
+
}
|
|
76
|
+
return results;
|
|
77
|
+
};
|
|
78
|
+
//#endregion
|
|
79
|
+
export { reorderIn };
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { HttpProblem, badRequest, notFound } from "../problem.js";
|
|
2
|
+
import { problemOf } from "../error-handler.js";
|
|
3
|
+
import { requestAccess } from "../request-access.js";
|
|
4
|
+
import { writeTransaction } from "../transactions.js";
|
|
5
|
+
import { keyOf } from "../write-shared.js";
|
|
6
|
+
import { writeIn } from "../write-pipeline.js";
|
|
7
|
+
import { resolveData, resolveKey } from "./refs.js";
|
|
8
|
+
import { reorderIn } from "./reorder.js";
|
|
9
|
+
//#region src/batch/run-batch.ts
|
|
10
|
+
const entryOf = (deps, name) => {
|
|
11
|
+
const entry = deps.registry.find(name);
|
|
12
|
+
if (!entry) throw notFound(`There is no resource "${name}"`);
|
|
13
|
+
return entry;
|
|
14
|
+
};
|
|
15
|
+
const atOperation = (error, index, operation) => {
|
|
16
|
+
const known = problemOf(error);
|
|
17
|
+
if (!known) throw error;
|
|
18
|
+
return new HttpProblem(known.status, known.slug, known.title, known.detail, {
|
|
19
|
+
...known.extras,
|
|
20
|
+
operation: index,
|
|
21
|
+
op: operation.op,
|
|
22
|
+
resource: operation.resource
|
|
23
|
+
}, known.headers);
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Runs the operations in order inside ONE transaction, each through the normal write pipeline (validation, access with row
|
|
27
|
+
* filters and record-level rules, tenant, ETags, hooks). Any failure rolls the whole batch back and names the failing operation.
|
|
28
|
+
*/
|
|
29
|
+
const runBatch = async (deps, session, operations) => {
|
|
30
|
+
const refs = operations.flatMap((operation) => operation.op === "create" && operation.ref ? [operation.ref] : []);
|
|
31
|
+
if (new Set(refs).size !== refs.length) throw badRequest("invalid-parameter", "Each create may use a ref name once");
|
|
32
|
+
const accesses = /* @__PURE__ */ new Map();
|
|
33
|
+
const accessFor = async (entry) => {
|
|
34
|
+
const known = accesses.get(entry.name);
|
|
35
|
+
if (known) return known;
|
|
36
|
+
const access = await requestAccess(deps, entry, session);
|
|
37
|
+
accesses.set(entry.name, access);
|
|
38
|
+
return access;
|
|
39
|
+
};
|
|
40
|
+
return writeTransaction(deps.db, deps.statementTimeoutMs, async (trx) => {
|
|
41
|
+
const created = /* @__PURE__ */ new Map();
|
|
42
|
+
const results = [];
|
|
43
|
+
for (const [index, operation] of operations.entries()) try {
|
|
44
|
+
const entry = entryOf(deps, operation.resource);
|
|
45
|
+
const access = await accessFor(entry);
|
|
46
|
+
if (operation.op === "create") {
|
|
47
|
+
const written = await writeIn(trx, deps, access, {
|
|
48
|
+
operation: "create",
|
|
49
|
+
body: resolveData(created, operation.data)
|
|
50
|
+
});
|
|
51
|
+
if (operation.ref) created.set(operation.ref, {
|
|
52
|
+
entry,
|
|
53
|
+
key: keyOf(access, written.record),
|
|
54
|
+
record: written.record
|
|
55
|
+
});
|
|
56
|
+
results.push({
|
|
57
|
+
op: "create",
|
|
58
|
+
resource: entry.name,
|
|
59
|
+
...operation.ref && { ref: operation.ref },
|
|
60
|
+
...written
|
|
61
|
+
});
|
|
62
|
+
} else if (operation.op === "update") {
|
|
63
|
+
const written = await writeIn(trx, deps, access, {
|
|
64
|
+
operation: "update",
|
|
65
|
+
key: resolveKey(created, entry, operation.key),
|
|
66
|
+
body: resolveData(created, operation.data),
|
|
67
|
+
ifMatch: operation.etag ?? null
|
|
68
|
+
});
|
|
69
|
+
results.push({
|
|
70
|
+
op: "update",
|
|
71
|
+
resource: entry.name,
|
|
72
|
+
...written
|
|
73
|
+
});
|
|
74
|
+
} else if (operation.op === "delete") {
|
|
75
|
+
await writeIn(trx, deps, access, {
|
|
76
|
+
operation: "delete",
|
|
77
|
+
key: resolveKey(created, entry, operation.key),
|
|
78
|
+
ifMatch: operation.etag ?? null
|
|
79
|
+
});
|
|
80
|
+
results.push({
|
|
81
|
+
op: "delete",
|
|
82
|
+
resource: entry.name,
|
|
83
|
+
deleted: true
|
|
84
|
+
});
|
|
85
|
+
} else {
|
|
86
|
+
const keys = operation.keys.map((key) => resolveKey(created, entry, key));
|
|
87
|
+
const records = await reorderIn(trx, deps, access, {
|
|
88
|
+
field: operation.field,
|
|
89
|
+
keys,
|
|
90
|
+
etags: operation.etags ?? {}
|
|
91
|
+
});
|
|
92
|
+
results.push({
|
|
93
|
+
op: "reorder",
|
|
94
|
+
resource: entry.name,
|
|
95
|
+
records
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
} catch (error) {
|
|
99
|
+
throw atOperation(error, index, operation);
|
|
100
|
+
}
|
|
101
|
+
return results;
|
|
102
|
+
});
|
|
103
|
+
};
|
|
104
|
+
//#endregion
|
|
105
|
+
export { runBatch };
|