@zveltio/sdk 3.0.0-beta.1 → 3.0.0-beta.101
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/README.md +17 -4
- package/dist/client.d.ts +103 -7
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +117 -27
- package/dist/core.d.ts.map +1 -1
- package/dist/core.js +21 -3
- package/dist/crdt.d.ts.map +1 -1
- package/dist/crdt.js +11 -2
- package/dist/ddl/index.d.ts +20 -0
- package/dist/ddl/index.d.ts.map +1 -1
- package/dist/errors.d.ts +58 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +124 -0
- package/dist/extension/action-refusal.d.ts +27 -0
- package/dist/extension/action-refusal.d.ts.map +1 -0
- package/dist/extension/action-refusal.js +29 -0
- package/dist/extension/capabilities.d.ts +71 -0
- package/dist/extension/capabilities.d.ts.map +1 -0
- package/dist/extension/capabilities.js +79 -0
- package/dist/extension/dates.d.ts +7 -0
- package/dist/extension/dates.d.ts.map +1 -0
- package/dist/extension/dates.js +14 -0
- package/dist/extension/index.d.ts +1086 -38
- package/dist/extension/index.d.ts.map +1 -1
- package/dist/extension/index.js +16 -0
- package/dist/extension/jsonb.d.ts +62 -0
- package/dist/extension/jsonb.d.ts.map +1 -0
- package/dist/extension/jsonb.js +64 -0
- package/dist/extension/multipart.d.ts +58 -0
- package/dist/extension/multipart.d.ts.map +1 -0
- package/dist/extension/multipart.js +61 -0
- package/dist/extension/numeric.d.ts +94 -0
- package/dist/extension/numeric.d.ts.map +1 -0
- package/dist/extension/numeric.js +162 -0
- package/dist/extension/permission-gate.d.ts +15 -0
- package/dist/extension/permission-gate.d.ts.map +1 -1
- package/dist/extension/permission-gate.js +33 -1
- package/dist/extension/reserved-paths.d.ts +10 -0
- package/dist/extension/reserved-paths.d.ts.map +1 -0
- package/dist/extension/reserved-paths.js +23 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/local-store.d.ts +14 -1
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-store.js +92 -13
- package/dist/offline/index.d.ts +25 -55
- package/dist/offline/index.d.ts.map +1 -1
- package/dist/offline/index.js +173 -157
- package/dist/publish/index.d.ts.map +1 -1
- package/dist/publish/index.js +6 -1
- package/dist/realtime.d.ts +25 -1
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +47 -3
- package/dist/rpc/index.d.ts.map +1 -1
- package/dist/rpc/index.js +2 -0
- package/dist/schema-codegen.d.ts +25 -1
- package/dist/schema-codegen.d.ts.map +1 -1
- package/dist/schema-codegen.js +141 -7
- package/dist/schema-watcher.d.ts +10 -2
- package/dist/schema-watcher.d.ts.map +1 -1
- package/dist/schema-watcher.js +25 -10
- package/dist/studio/index.d.ts +1 -0
- package/dist/studio/index.d.ts.map +1 -1
- package/dist/studio/index.js +3 -0
- package/dist/studio/slot-owner-registry.d.ts +13 -0
- package/dist/studio/slot-owner-registry.d.ts.map +1 -0
- package/dist/studio/slot-owner-registry.js +21 -0
- package/dist/svelte.d.ts +1 -1
- package/dist/svelte.d.ts.map +1 -1
- package/dist/svelte.js +4 -2
- package/dist/sync-manager.d.ts +49 -4
- package/dist/sync-manager.d.ts.map +1 -1
- package/dist/sync-manager.js +173 -15
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js +23 -1
- package/dist/testing/with-test-db.d.ts +1 -1
- package/dist/testing/with-test-db.d.ts.map +1 -1
- package/dist/testing/with-test-db.js +22 -15
- package/dist/tests/action-refusal.test.d.ts +2 -0
- package/dist/tests/action-refusal.test.d.ts.map +1 -0
- package/dist/tests/action-refusal.test.js +13 -0
- package/dist/tests/client.test.d.ts +2 -0
- package/dist/tests/client.test.d.ts.map +1 -0
- package/dist/tests/client.test.js +164 -0
- package/dist/tests/crdt-orset.test.d.ts +2 -0
- package/dist/tests/crdt-orset.test.d.ts.map +1 -0
- package/dist/tests/crdt-orset.test.js +23 -0
- package/dist/tests/local-store.test.js +44 -0
- package/dist/tests/migration-parse.test.d.ts +2 -0
- package/dist/tests/migration-parse.test.d.ts.map +1 -0
- package/dist/tests/migration-parse.test.js +17 -0
- package/dist/tests/multipart.test.d.ts +2 -0
- package/dist/tests/multipart.test.d.ts.map +1 -0
- package/dist/tests/multipart.test.js +37 -0
- package/dist/tests/offline-provider-crdt.test.d.ts +2 -0
- package/dist/tests/offline-provider-crdt.test.d.ts.map +1 -0
- package/dist/tests/offline-provider-crdt.test.js +206 -0
- package/dist/tests/realtime.test.d.ts +2 -0
- package/dist/tests/realtime.test.d.ts.map +1 -0
- package/dist/tests/realtime.test.js +220 -0
- package/dist/tests/reserved-paths.test.d.ts +2 -0
- package/dist/tests/reserved-paths.test.d.ts.map +1 -0
- package/dist/tests/reserved-paths.test.js +21 -0
- package/dist/tests/sync-manager.test.d.ts +2 -0
- package/dist/tests/sync-manager.test.d.ts.map +1 -0
- package/dist/tests/sync-manager.test.js +123 -0
- package/dist/tests/today-in.test.d.ts +2 -0
- package/dist/tests/today-in.test.d.ts.map +1 -0
- package/dist/tests/today-in.test.js +14 -0
- package/dist/tests/validate-manifest-actions.test.d.ts +2 -0
- package/dist/tests/validate-manifest-actions.test.d.ts.map +1 -0
- package/dist/tests/validate-manifest-actions.test.js +82 -0
- package/dist/tests/validate-manifest-dependencies.test.d.ts +2 -0
- package/dist/tests/validate-manifest-dependencies.test.d.ts.map +1 -0
- package/dist/tests/validate-manifest-dependencies.test.js +27 -0
- package/dist/tests/validate-manifest-forward-credentials.test.d.ts +2 -0
- package/dist/tests/validate-manifest-forward-credentials.test.d.ts.map +1 -0
- package/dist/tests/validate-manifest-forward-credentials.test.js +35 -0
- package/dist/tests/validate-sdui-data-endpoints.test.d.ts +2 -0
- package/dist/tests/validate-sdui-data-endpoints.test.d.ts.map +1 -0
- package/dist/tests/validate-sdui-data-endpoints.test.js +41 -0
- package/dist/tests/with-test-db.test.d.ts +2 -0
- package/dist/tests/with-test-db.test.d.ts.map +1 -0
- package/dist/tests/with-test-db.test.js +57 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/validate/index.d.ts +53 -0
- package/dist/validate/index.d.ts.map +1 -1
- package/dist/validate/index.js +693 -7
- package/dist/validate/migration-parse.d.ts +10 -5
- package/dist/validate/migration-parse.d.ts.map +1 -1
- package/dist/validate/migration-parse.js +1 -1
- package/dist/validate/shared-message-keys.d.ts +16 -0
- package/dist/validate/shared-message-keys.d.ts.map +1 -0
- package/dist/validate/shared-message-keys.js +227 -0
- package/package.json +8 -8
- package/dist/client/Auth.d.ts +0 -19
- package/dist/client/Auth.d.ts.map +0 -1
- package/dist/client/Auth.js +0 -45
- package/dist/client/QueryBuilder.d.ts +0 -17
- package/dist/client/QueryBuilder.d.ts.map +0 -1
- package/dist/client/QueryBuilder.js +0 -85
- package/dist/client/RealtimeClient.d.ts +0 -22
- package/dist/client/RealtimeClient.d.ts.map +0 -1
- package/dist/client/RealtimeClient.js +0 -98
- package/dist/client/ZveltioClient.d.ts +0 -20
- package/dist/client/ZveltioClient.d.ts.map +0 -1
- package/dist/client/ZveltioClient.js +0 -78
- package/dist/generate-types.d.ts +0 -37
- package/dist/generate-types.d.ts.map +0 -1
- package/dist/generate-types.js +0 -157
|
@@ -1,6 +1,150 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import type {
|
|
1
|
+
import type { Capability, MembersLockedFor } from './capabilities.js';
|
|
2
|
+
import type { Context, Hono } from 'hono';
|
|
3
|
+
import type { Kysely, RawBuilder } from 'kysely';
|
|
3
4
|
export { permissionGate } from './permission-gate.js';
|
|
5
|
+
export { ActionRefusal, ACTION_REFUSAL, type RefusalStatus } from './action-refusal.js';
|
|
6
|
+
export { todayIn } from './dates.js';
|
|
7
|
+
export { RESERVED_PATH_SEGMENTS, isReservedPath } from './reserved-paths.js';
|
|
8
|
+
export { readMultipart, MULTIPART_REQUIRED } from './multipart.js';
|
|
9
|
+
export { toJsonb } from './jsonb.js';
|
|
10
|
+
/**
|
|
11
|
+
* The prefix of a field an operator adds to a collection an extension owns
|
|
12
|
+
* (ADR 0012 amendment 2). Such a name is the operator's: an extension may not
|
|
13
|
+
* declare one, and its load never drops or alters one.
|
|
14
|
+
*/
|
|
15
|
+
export declare const OPERATOR_FIELD_PREFIX = "my_";
|
|
16
|
+
export { isStorableNumeric, NumericConversionError, roundMoney, sumNumeric, toNumber, toNumberOrNull, toNumberSafe, } from './numeric.js';
|
|
17
|
+
/**
|
|
18
|
+
* One row-level-security condition, as `getRlsFilters` produces it and
|
|
19
|
+
* `applyRlsFilters` consumes it. Opaque in practice — an extension passes the
|
|
20
|
+
* array straight through rather than reading it.
|
|
21
|
+
*/
|
|
22
|
+
export interface RlsFilter {
|
|
23
|
+
readonly field: string;
|
|
24
|
+
readonly condition: {
|
|
25
|
+
readonly op: string;
|
|
26
|
+
readonly value?: unknown;
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/** What the data API answered a `ctx.internals` write: its HTTP status and JSON body. */
|
|
30
|
+
export interface DataApiAnswer {
|
|
31
|
+
status: number;
|
|
32
|
+
body: Record<string, unknown>;
|
|
33
|
+
}
|
|
34
|
+
/** One `ctx.internals.writeValidationRule` write; `collection` narrows a toggle or delete. */
|
|
35
|
+
export type ValidationRuleWrite = {
|
|
36
|
+
op: 'create';
|
|
37
|
+
rule: {
|
|
38
|
+
collection: string;
|
|
39
|
+
field_name: string;
|
|
40
|
+
rule_type: string;
|
|
41
|
+
rule_config?: unknown;
|
|
42
|
+
error_message: string;
|
|
43
|
+
nl_description?: string | null;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Whom the rule binds. Left out: an instance admin writes an instance rule
|
|
47
|
+
* (every tenant), a tenant admin a rule of the request's tenant. `'tenant'`
|
|
48
|
+
* lets an instance admin write one for the request's tenant; a tenant admin
|
|
49
|
+
* asking `'instance'` throws.
|
|
50
|
+
*/
|
|
51
|
+
scope?: 'instance' | 'tenant';
|
|
52
|
+
} | {
|
|
53
|
+
op: 'setActive';
|
|
54
|
+
id: string;
|
|
55
|
+
is_active: boolean;
|
|
56
|
+
collection?: string;
|
|
57
|
+
} | {
|
|
58
|
+
op: 'delete';
|
|
59
|
+
id: string;
|
|
60
|
+
collection?: string;
|
|
61
|
+
};
|
|
62
|
+
/** One `ctx.internals.writeValidationRuleGroup` write. */
|
|
63
|
+
export type ValidationRuleGroupWrite = {
|
|
64
|
+
op: 'create';
|
|
65
|
+
group: {
|
|
66
|
+
name: string;
|
|
67
|
+
collection: string;
|
|
68
|
+
field_name: string;
|
|
69
|
+
description?: string | null;
|
|
70
|
+
logic?: 'AND' | 'OR';
|
|
71
|
+
rule_ids: string[];
|
|
72
|
+
is_active?: boolean;
|
|
73
|
+
};
|
|
74
|
+
} | {
|
|
75
|
+
op: 'delete';
|
|
76
|
+
id: string;
|
|
77
|
+
};
|
|
78
|
+
/** The query of `ctx.internals.listRecords`: `GET /api/data/:collection`'s own parameters. */
|
|
79
|
+
export interface DataApiReadQuery {
|
|
80
|
+
page?: number;
|
|
81
|
+
limit?: number;
|
|
82
|
+
sort?: string;
|
|
83
|
+
order?: 'asc' | 'desc';
|
|
84
|
+
/** The route's `?filter=` JSON, as an object or already serialized. */
|
|
85
|
+
filter?: Record<string, unknown> | string;
|
|
86
|
+
search?: string;
|
|
87
|
+
cursor?: string;
|
|
88
|
+
count?: 'exact' | 'none';
|
|
89
|
+
expand?: string;
|
|
90
|
+
}
|
|
91
|
+
/** What `ctx.internals.readScope` resolves: one caller's read gate on one collection. */
|
|
92
|
+
export interface ReadScope {
|
|
93
|
+
/** The physical table the alters and entity checks are registered against. */
|
|
94
|
+
readonly table: string;
|
|
95
|
+
/** Row policies, for a reader that renders them itself. */
|
|
96
|
+
readonly rls: RlsFilter[];
|
|
97
|
+
readonly columns: {
|
|
98
|
+
hidden: Set<string>;
|
|
99
|
+
readOnly: Set<string>;
|
|
100
|
+
};
|
|
101
|
+
/** An extension alter changes what this caller reads (see `admits`). */
|
|
102
|
+
readonly altersRestrict: boolean;
|
|
103
|
+
/** Alters + row policies onto a SELECT builder. Not for UPDATE/DELETE. */
|
|
104
|
+
query<Q>(qb: Q): Q;
|
|
105
|
+
/** The fetched rows entity access lets the caller `view`. */
|
|
106
|
+
keep<R>(rows: R[]): Promise<R[]>;
|
|
107
|
+
/** One row that did not come through `query` (a write's RETURNING): all three row gates in memory. */
|
|
108
|
+
admits(row: Record<string, unknown>): boolean | Promise<boolean>;
|
|
109
|
+
/** Column permissions onto one row. */
|
|
110
|
+
shape<R extends Record<string, unknown>>(row: R): R;
|
|
111
|
+
/** Whether the caller may read — and so filter, sort or join on — this column. */
|
|
112
|
+
readable(column: string): boolean;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* The filter operators the engine's query compiler understands — the vocabulary
|
|
116
|
+
* `buildCondition` accepts.
|
|
117
|
+
*
|
|
118
|
+
* Declared here rather than in the engine because this is the file an extension
|
|
119
|
+
* author compiles against, and the engine imports it back (as it already does
|
|
120
|
+
* for `RlsFilter`). One list: a repeated one is how this codebase's dominant
|
|
121
|
+
* defect shape starts.
|
|
122
|
+
*/
|
|
123
|
+
export type FilterOp = 'eq' | 'neq' | 'lt' | 'lte' | 'gt' | 'gte' | 'like' | 'ilike' | 'not_contains' | 'starts_with' | 'ends_with' | 'in' | 'not_in' | 'null' | 'not_null'
|
|
124
|
+
/** `location` only: `{ lat, lng, radius }`, radius in metres (ADR 0019). */
|
|
125
|
+
| 'near'
|
|
126
|
+
/** `location` only: `{ minLat, minLng, maxLat, maxLng }` (ADR 0019). */
|
|
127
|
+
| 'within';
|
|
128
|
+
/**
|
|
129
|
+
* The actor a data-path call is made on behalf of.
|
|
130
|
+
*
|
|
131
|
+
* Declared here for the same reason as `RlsFilter` and `FilterOp`: it is part
|
|
132
|
+
* of what `ctx.internals.checkAccess` asks an extension for, and the engine
|
|
133
|
+
* re-exports it rather than keeping a second copy.
|
|
134
|
+
*/
|
|
135
|
+
export interface RequestUser {
|
|
136
|
+
id: string;
|
|
137
|
+
name: string;
|
|
138
|
+
role: string;
|
|
139
|
+
/** Present only for API-key auth — collection/action scopes. */
|
|
140
|
+
scopes?: unknown;
|
|
141
|
+
/** Present for session auth. */
|
|
142
|
+
email?: string;
|
|
143
|
+
/** API-key auth only: this key is exempt from row-level security. */
|
|
144
|
+
rlsBypass?: boolean;
|
|
145
|
+
/** API-key auth only: the `user` row authorship is recorded against. */
|
|
146
|
+
authorUserId?: string | null;
|
|
147
|
+
}
|
|
4
148
|
export interface FieldTypeRegistryAPI {
|
|
5
149
|
register(definition: any): void;
|
|
6
150
|
get(type: string): any;
|
|
@@ -21,6 +165,68 @@ export interface FieldTypeRegistryAPI {
|
|
|
21
165
|
/** Coerce a value FROM its TS shape INTO the database representation. */
|
|
22
166
|
serialize(type: string, value: any): any;
|
|
23
167
|
}
|
|
168
|
+
/**
|
|
169
|
+
* Object storage settings, handed to extensions that declare the `storage`
|
|
170
|
+
* capability. `undefined` on `ExtensionConfig` means the instance has no object
|
|
171
|
+
* storage configured — degrade (keep metadata, skip the bytes), don't throw.
|
|
172
|
+
*
|
|
173
|
+
* Resolved from the same source the engine uses, which includes the admin's
|
|
174
|
+
* Studio settings. Reading `S3_*` from the environment instead misses that
|
|
175
|
+
* overlay entirely and sees an unconfigured instance.
|
|
176
|
+
*/
|
|
177
|
+
export interface ObjectStorageConfig {
|
|
178
|
+
/** Endpoint origin, no trailing slash. */
|
|
179
|
+
readonly endpoint: string;
|
|
180
|
+
readonly region: string;
|
|
181
|
+
readonly bucket: string;
|
|
182
|
+
/** Public base URL for reads, when the deployment serves one. */
|
|
183
|
+
readonly publicUrl?: string;
|
|
184
|
+
readonly accessKeyId: string;
|
|
185
|
+
readonly secretAccessKey: string;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* The configuration an extension may read — `ctx.config`.
|
|
189
|
+
*
|
|
190
|
+
* Use this instead of `process.env`. An in-process extension reading the
|
|
191
|
+
* environment gets the whole ENGINE environment (database credentials, the auth
|
|
192
|
+
* secret, the field-encryption key), which is both more than any extension
|
|
193
|
+
* needs and a way around the capability gate on `ctx.internals`.
|
|
194
|
+
*
|
|
195
|
+
* Values are live: read them when you need them rather than caching at module
|
|
196
|
+
* scope, because an administrator can change storage settings at runtime.
|
|
197
|
+
*/
|
|
198
|
+
export interface ExtensionConfig {
|
|
199
|
+
/**
|
|
200
|
+
* This extension's own slice of the environment.
|
|
201
|
+
*
|
|
202
|
+
* Everything the deployment set as `ZVELTIO_EXT_<NAME>_<KEY>` appears here as
|
|
203
|
+
* `<KEY>`, and nothing else does. `search` reading `vars.MEILISEARCH_URL` gets
|
|
204
|
+
* `ZVELTIO_EXT_SEARCH_MEILISEARCH_URL`; it cannot see `DATABASE_URL`,
|
|
205
|
+
* `BETTER_AUTH_SECRET`, or another extension's keys.
|
|
206
|
+
*
|
|
207
|
+
* Use this instead of `process.env`, which from inside an in-process extension
|
|
208
|
+
* is the ENGINE's environment in full.
|
|
209
|
+
*
|
|
210
|
+
* Values are strings — coerce at the point of use, and treat a missing key as
|
|
211
|
+
* "not configured" rather than defaulting to something that half-works.
|
|
212
|
+
*/
|
|
213
|
+
readonly vars: Readonly<Record<string, string>>;
|
|
214
|
+
readonly env: 'production' | 'development' | 'test';
|
|
215
|
+
readonly isProduction: boolean;
|
|
216
|
+
/** The engine's public base URL, when the deployment sets one. */
|
|
217
|
+
readonly publicUrl?: string;
|
|
218
|
+
/**
|
|
219
|
+
* Whether the instance has a field-encryption key configured. A boolean by
|
|
220
|
+
* design — to encrypt something use `ctx.internals.encryptSecret`, which is
|
|
221
|
+
* gated by the `secrets` capability. Extensions do not hold key material.
|
|
222
|
+
*/
|
|
223
|
+
readonly encryptionConfigured: boolean;
|
|
224
|
+
readonly crossDomainAuth: boolean;
|
|
225
|
+
/** Permits plaintext LDAP binds. Development only. */
|
|
226
|
+
readonly allowInsecureLdap: boolean;
|
|
227
|
+
/** Present only with the `storage` capability, and only when configured. */
|
|
228
|
+
readonly objectStorage?: ObjectStorageConfig;
|
|
229
|
+
}
|
|
24
230
|
/**
|
|
25
231
|
* Context injected into every extension's `register()` call.
|
|
26
232
|
*
|
|
@@ -29,12 +235,53 @@ export interface FieldTypeRegistryAPI {
|
|
|
29
235
|
* Default `any` keeps legacy extensions compiling untouched. Migrated
|
|
30
236
|
* extensions get full Kysely autocomplete + typo detection.
|
|
31
237
|
*/
|
|
32
|
-
|
|
238
|
+
/**
|
|
239
|
+
* `C` — the capabilities this extension declared, when it says so through
|
|
240
|
+
* `defineExtension`. It narrows `internals` to the members those capabilities
|
|
241
|
+
* unlock and `adminDb` to `db:admin`, so an undeclared capability is a compile
|
|
242
|
+
* error rather than a `CapabilityDeniedError` on the first request that needs
|
|
243
|
+
* it. Defaults to every capability: code that does not opt in keeps today's type.
|
|
244
|
+
*/
|
|
245
|
+
export interface ExtensionContext<DB = any, C extends string = Capability> {
|
|
33
246
|
/**
|
|
34
247
|
* Kysely database instance (restricted — cannot query zv_* system tables).
|
|
35
248
|
* Typed via the `DB` generic; use `ZveltioExtension<MySchema>` to opt in.
|
|
249
|
+
*
|
|
250
|
+
* TENANT-SCOPED (since H-12): queries run against the current request/job
|
|
251
|
+
* tenant's transaction (so the `zveltio.current_tenant` GUC is set and
|
|
252
|
+
* FORCE-RLS rows are isolated), or the global pool outside any tenant context
|
|
253
|
+
* (boot/migrations). You no longer need `ctx.reqDb(c)` for isolation — `ctx.db`
|
|
254
|
+
* is safe by default. For explicit CROSS-tenant access, see `ctx.adminDb`.
|
|
36
255
|
*/
|
|
37
256
|
db: Kysely<DB>;
|
|
257
|
+
/**
|
|
258
|
+
* Configuration this extension may read. Use it instead of `process.env` —
|
|
259
|
+
* see `ExtensionConfig`.
|
|
260
|
+
*
|
|
261
|
+
* Typed optional so partial/bootstrap contexts type-check; always present on
|
|
262
|
+
* the context the engine hands a loaded extension.
|
|
263
|
+
*/
|
|
264
|
+
config?: ExtensionConfig;
|
|
265
|
+
/**
|
|
266
|
+
* Explicit CROSS-TENANT database handle (the global pool). Present ONLY when
|
|
267
|
+
* the manifest declares the `db:admin` permission — otherwise any query throws.
|
|
268
|
+
* Use for legitimately global operations (platform-wide reporting, backup).
|
|
269
|
+
* Declaring `db:admin` surfaces the cross-tenant access at review + install.
|
|
270
|
+
*/
|
|
271
|
+
adminDb?: 'db:admin' extends C ? Kysely<DB> : never;
|
|
272
|
+
/**
|
|
273
|
+
* Per-request, tenant-scoped database. Returns the request's tenant
|
|
274
|
+
* transaction (so the `zveltio.current_tenant` GUC is set and FORCE-RLS rows
|
|
275
|
+
* are visible + isolated), wrapped in the same table-restriction guard as
|
|
276
|
+
* `ctx.db`. Pass the route's Hono context: `const db = ctx.reqDb(c)`.
|
|
277
|
+
* Throws when the request has no tenant transaction; `ctx.db` resolves the
|
|
278
|
+
* tenant wherever there is one.
|
|
279
|
+
*
|
|
280
|
+
* Always present on the context the engine hands to a loaded extension; typed
|
|
281
|
+
* optional only so partial/bootstrap contexts type-check. In a data handler
|
|
282
|
+
* use it directly — `ctx.reqDb(c)`.
|
|
283
|
+
*/
|
|
284
|
+
reqDb?: (c: any) => Kysely<DB>;
|
|
38
285
|
/** Better-Auth instance — use `ctx.auth.api.getSession({ headers })` in route handlers. */
|
|
39
286
|
auth: any;
|
|
40
287
|
/** Field type registry — register custom field types here. */
|
|
@@ -87,6 +334,31 @@ export interface ExtensionContext<DB = any> {
|
|
|
87
334
|
* `EntityAccessScope` for an example.
|
|
88
335
|
*/
|
|
89
336
|
entityAccess: EntityAccessScope;
|
|
337
|
+
/**
|
|
338
|
+
* Register a subsystem health check surfaced at `GET /api/health/deep` and
|
|
339
|
+
* `GET /api/health/<name>`. Use it to report the liveness of anything your
|
|
340
|
+
* extension owns (an external API, a worker, a provider):
|
|
341
|
+
*
|
|
342
|
+
* ctx.onHealthCheck('smtp', async () => {
|
|
343
|
+
* const ok = await pingSmtp();
|
|
344
|
+
* return { ok, detail: { host: SMTP_HOST } };
|
|
345
|
+
* });
|
|
346
|
+
*
|
|
347
|
+
* Checks are namespaced `ext:<yourExtension>:<name>` and cleared on reload.
|
|
348
|
+
* Mark `{ critical: true }` only if your extension being down should fail the
|
|
349
|
+
* engine's readiness probe (rarely — most extensions are optional).
|
|
350
|
+
*/
|
|
351
|
+
onHealthCheck?: (name: string, run: () => Promise<{
|
|
352
|
+
ok: boolean;
|
|
353
|
+
error?: string;
|
|
354
|
+
detail?: Record<string, unknown>;
|
|
355
|
+
}> | {
|
|
356
|
+
ok: boolean;
|
|
357
|
+
error?: string;
|
|
358
|
+
detail?: Record<string, unknown>;
|
|
359
|
+
}, opts?: {
|
|
360
|
+
critical?: boolean;
|
|
361
|
+
}) => void;
|
|
90
362
|
/**
|
|
91
363
|
* Register a route on the engine's GLOBAL app, outside the extension's
|
|
92
364
|
* `/ext/<name>/` namespace. Use sparingly — most routes should live on
|
|
@@ -111,50 +383,473 @@ export interface ExtensionContext<DB = any> {
|
|
|
111
383
|
* });
|
|
112
384
|
*/
|
|
113
385
|
registerPublicRoute(spec: PublicRouteSpec): void;
|
|
386
|
+
/**
|
|
387
|
+
* Tell every engine replica, this one included, that something this
|
|
388
|
+
* extension caches changed. Engine 3.0.0-beta.90 and later; refused to a
|
|
389
|
+
* worker-isolated extension. See `ExtensionBroadcast`.
|
|
390
|
+
*/
|
|
391
|
+
broadcast?: ExtensionBroadcast;
|
|
114
392
|
/**
|
|
115
393
|
* Engine-internal helpers. Stable across patch versions but may break across
|
|
116
394
|
* minor versions. First-party extensions only.
|
|
117
395
|
*/
|
|
118
|
-
internals: ExtensionInternals
|
|
396
|
+
internals: Omit<ExtensionInternals<DB>, MembersLockedFor<C>>;
|
|
119
397
|
}
|
|
120
398
|
/**
|
|
121
399
|
* Engine-internal helpers passed via `ctx.internals.*`.
|
|
122
400
|
* Each field is the live engine singleton or function — extensions should never
|
|
123
401
|
* import these directly from `../../../packages/engine/src/...` paths.
|
|
124
402
|
*/
|
|
125
|
-
export interface ExtensionInternals {
|
|
126
|
-
/**
|
|
403
|
+
export interface ExtensionInternals<DB = unknown> {
|
|
404
|
+
/**
|
|
405
|
+
* Insert one row into a collection table (`zvd_<name>`). The row goes
|
|
406
|
+
* through the engine's field pipeline first, as a `ctx.db` insert does: type
|
|
407
|
+
* validation, deserialization, field encryption and the collection's
|
|
408
|
+
* validation rules. Pass RAW values — do not deserialize or encrypt them
|
|
409
|
+
* yourself. A row the pipeline refuses throws and nothing is written.
|
|
410
|
+
*/
|
|
127
411
|
dynamicInsert: (db: any, collection: string, values: Record<string, unknown>) => Promise<unknown>;
|
|
412
|
+
/**
|
|
413
|
+
* The three an extension needs to render a collection the way the engine's
|
|
414
|
+
* own data routes do: the access check, the column mask, and the filter
|
|
415
|
+
* compiler. `content/pages` renders arbitrary collections for a portal
|
|
416
|
+
* audience and has to apply exactly the rules `/api/data` applies —
|
|
417
|
+
* reimplementing them would be a second, quietly diverging copy of the
|
|
418
|
+
* authorisation path.
|
|
419
|
+
*/
|
|
420
|
+
checkAccess: (db: Kysely<DB>, user: Pick<RequestUser, 'id' | 'scopes'> & {
|
|
421
|
+
role?: string;
|
|
422
|
+
}, collection: string, action: string) => Promise<boolean>;
|
|
423
|
+
applyColumnAccess: (record: Record<string, unknown>, access: {
|
|
424
|
+
hidden: Set<string>;
|
|
425
|
+
readOnly: Set<string>;
|
|
426
|
+
}) => Record<string, unknown>;
|
|
427
|
+
/**
|
|
428
|
+
* Compile one filter into a SQL condition, over the operators in `FilterOp`.
|
|
429
|
+
*/
|
|
430
|
+
buildCondition: (key: string, condition: {
|
|
431
|
+
op: FilterOp;
|
|
432
|
+
value?: unknown;
|
|
433
|
+
}) => RawBuilder<boolean>;
|
|
128
434
|
/** Introspect a Postgres schema — returns tables, columns, types, indexes, FKs. */
|
|
129
435
|
introspectSchema: (db: any, schemaName?: string, excludePatterns?: string[], dryRun?: boolean) => Promise<any[]>;
|
|
130
|
-
/** Run a data-quality scan over a collection. */
|
|
131
|
-
runQualityScan: (...args: any[]) => Promise<unknown>;
|
|
132
436
|
/** Invalidate the cached validation rules for a collection. */
|
|
133
437
|
invalidateRulesCache: (collection: string) => void;
|
|
438
|
+
/**
|
|
439
|
+
* Evaluate a user-authored validation expression, safely.
|
|
440
|
+
*
|
|
441
|
+
* `refused` is distinct from `failed` on purpose: an expression the engine
|
|
442
|
+
* declines to run has not passed and has not failed, and a rule editor that
|
|
443
|
+
* reports either would be lying to whoever is writing the rule.
|
|
444
|
+
*
|
|
445
|
+
* Use this instead of `new Function` or `eval`. A Function body closes over
|
|
446
|
+
* the global scope, so an expression stored by any tenant admin could reach
|
|
447
|
+
* `process` and `Bun` from inside the engine process.
|
|
448
|
+
*/
|
|
449
|
+
evaluateExpressionRule: (expression: string, value: unknown) => {
|
|
450
|
+
status: 'passed';
|
|
451
|
+
} | {
|
|
452
|
+
status: 'failed';
|
|
453
|
+
} | {
|
|
454
|
+
status: 'refused';
|
|
455
|
+
reason: string;
|
|
456
|
+
};
|
|
457
|
+
/**
|
|
458
|
+
* The same, for a `transition` rule: `value` is being written, `previous` is
|
|
459
|
+
* the stored value (`null` on create). Engine 3.0.0-beta.85 and later.
|
|
460
|
+
*/
|
|
461
|
+
evaluateTransitionRule: (expression: string, value: unknown, previous: unknown) => {
|
|
462
|
+
status: 'passed';
|
|
463
|
+
} | {
|
|
464
|
+
status: 'failed';
|
|
465
|
+
} | {
|
|
466
|
+
status: 'refused';
|
|
467
|
+
reason: string;
|
|
468
|
+
};
|
|
469
|
+
/** Vet an expression before storing it. A `transition` rule also sees `previous`. */
|
|
470
|
+
checkValidationExpression: (expression: string, ruleType?: string) => {
|
|
471
|
+
ok: true;
|
|
472
|
+
} | {
|
|
473
|
+
ok: false;
|
|
474
|
+
reason: string;
|
|
475
|
+
};
|
|
476
|
+
/**
|
|
477
|
+
* Create, toggle or delete a validation rule. `ctx.db` only reads
|
|
478
|
+
* `zv_validation_rules`; this writes it as the engine for the caller the
|
|
479
|
+
* `/ext/*` gate admitted for `c`. An instance rule (`tenant_id` null) binds
|
|
480
|
+
* every tenant's writes and only an instance admin writes one; a tenant admin
|
|
481
|
+
* writes rules of the request's tenant only (the engine sets `tenant_id`),
|
|
482
|
+
* which add to the instance rules and never relax one, and toggles or deletes
|
|
483
|
+
* only those. Anyone else (an API key, a member) throws. Answers the stored
|
|
484
|
+
* row (the removed one for `delete`), or `null` when no rule the caller may
|
|
485
|
+
* write has that id. A `custom`, `nlp` or `transition` rule whose expression
|
|
486
|
+
* does not compile throws, as does a second instance rule with the same
|
|
487
|
+
* field, rule type and config (SQLSTATE 23505 on `errno`). Audited: an
|
|
488
|
+
* instance rule as an instance event, a tenant rule in its tenant. Engine
|
|
489
|
+
* 3.0.0-beta.88 and later.
|
|
490
|
+
*/
|
|
491
|
+
writeValidationRule: (c: Context, write: ValidationRuleWrite) => Promise<Record<string, unknown> | null>;
|
|
492
|
+
/**
|
|
493
|
+
* Create or delete a rule group (`AND` / `OR` over a field's rules). Groups
|
|
494
|
+
* are instance-wide like the rules they combine, so the same caller rule
|
|
495
|
+
* applies: an instance admin only, written as the engine, audited. A second
|
|
496
|
+
* group with the same name on a collection throws (SQLSTATE 23505 on
|
|
497
|
+
* `errno`). Answers the stored row (the removed one for `delete`), or `null`
|
|
498
|
+
* when no group has that id. Engine 3.0.0-beta.88 and later.
|
|
499
|
+
*/
|
|
500
|
+
writeValidationRuleGroup: (c: Context, write: ValidationRuleGroupWrite) => Promise<Record<string, unknown> | null>;
|
|
501
|
+
/**
|
|
502
|
+
* Run a callback inside a tenant transaction, outside any request.
|
|
503
|
+
*
|
|
504
|
+
* `ctx.reqDb(c)` covers request handlers. Background work — scheduled tasks,
|
|
505
|
+
* queue workers, fire-and-forget jobs — has no `c` and so had nothing: it ran
|
|
506
|
+
* on the engine's global pool with no tenant context at all. `data/export`
|
|
507
|
+
* and `data/import` documented that in a comment and called the fix a
|
|
508
|
+
* follow-up.
|
|
509
|
+
*
|
|
510
|
+
* The tenant must come from wherever the work was ENQUEUED; a job has no
|
|
511
|
+
* caller to inherit one from. Inside the callback the handle behaves exactly
|
|
512
|
+
* like a request's: the tenant GUC is set and `SET LOCAL ROLE` applied, so
|
|
513
|
+
* the isolation policies bind.
|
|
514
|
+
*
|
|
515
|
+
* Only the tenant the work already runs as — the request's, or the job's —
|
|
516
|
+
* is entered without a capability. Another tenant, or any tenant where none
|
|
517
|
+
* runs (load time, a timer), needs `tenant:enter` (or `db:admin`, which
|
|
518
|
+
* implies it); without it the promise rejects.
|
|
519
|
+
* A fire-and-forget job started from a handler keeps the handler's tenant.
|
|
520
|
+
*
|
|
521
|
+
* await ctx.internals.withTenantIsolation(tenantId, async (db) => {
|
|
522
|
+
* await db.selectFrom('zvd_things').selectAll().execute();
|
|
523
|
+
* });
|
|
524
|
+
*/
|
|
525
|
+
withTenantIsolation: <T>(tenantId: string, fn: (db: Kysely<DB>) => Promise<T>) => Promise<T>;
|
|
526
|
+
/**
|
|
527
|
+
* The instance's own read policies, so an extension can honour them.
|
|
528
|
+
*
|
|
529
|
+
* `ctx.db` gives an extension the TENANT boundary — the Postgres policies
|
|
530
|
+
* bind, and rows from another company are unreachable. It gives nothing for
|
|
531
|
+
* the two access rules an operator writes inside a tenant: the RLS rules at
|
|
532
|
+
* `/api/rls`, which hide rows from a user, and the column permissions that
|
|
533
|
+
* hide a field from a role. Those live in the engine and, until now, only the
|
|
534
|
+
* engine could read them.
|
|
535
|
+
*
|
|
536
|
+
* So an extension serving the same data as a core route enforced strictly
|
|
537
|
+
* less, and nothing said so. `data/export` is the worked example: the engine's
|
|
538
|
+
* `/api/export` gained both guards, its own copy kept `selectAll()` inside a
|
|
539
|
+
* tenant transaction, and the Studio calls the extension. The fix was
|
|
540
|
+
* impossible to write on that side — not overlooked, unavailable.
|
|
541
|
+
*
|
|
542
|
+
* Ungated, deliberately. Every other guarded member of this bag grants
|
|
543
|
+
* authority; these only ever remove rows and columns from a result. An
|
|
544
|
+
* extension that cannot call them does not become safer, it becomes the
|
|
545
|
+
* loophole.
|
|
546
|
+
*
|
|
547
|
+
* const cols = await ctx.internals.getColumnAccess(coll, role);
|
|
548
|
+
* const q = ctx.internals.applyRlsFilters(base, filters);
|
|
549
|
+
*/
|
|
550
|
+
/**
|
|
551
|
+
* Apply field encryption to a value the operator marked `encrypted: true`.
|
|
552
|
+
* No-op when `isEncrypted` is false, when the value is not a string, or when
|
|
553
|
+
* it is already encrypted.
|
|
554
|
+
*
|
|
555
|
+
* Not `encryptSecret`: that is gated behind the `secrets` capability, which
|
|
556
|
+
* also hands over `decryptSecret`. Writing a row correctly should not cost the
|
|
557
|
+
* power to read every stored secret — and that trade is why `data/import`
|
|
558
|
+
* stored marked columns in PLAINTEXT rather than declaring the capability.
|
|
559
|
+
*
|
|
560
|
+
* Throws when `FIELD_ENCRYPTION_KEY` is unset and the field is marked, which
|
|
561
|
+
* is the engine's posture on the same path: a column an operator marked
|
|
562
|
+
* sensitive is not silently downgraded.
|
|
563
|
+
*/
|
|
564
|
+
maybeEncrypt: (value: unknown, isEncrypted: boolean) => Promise<unknown>;
|
|
565
|
+
/**
|
|
566
|
+
* The other half. Without it an extension can write a secret it cannot read
|
|
567
|
+
* back, so it stores plaintext instead — which is how a signing secret ends
|
|
568
|
+
* up readable by anyone with database access.
|
|
569
|
+
*
|
|
570
|
+
* Passes through values that do not carry the `enc:v1:` prefix, so adopting
|
|
571
|
+
* encryption on an existing column is safe: rows written before keep working,
|
|
572
|
+
* rows written after are encrypted at rest.
|
|
573
|
+
*/
|
|
574
|
+
maybeDecrypt: (value: unknown, isEncrypted: boolean) => Promise<unknown>;
|
|
575
|
+
/**
|
|
576
|
+
* `role` is optional because the engine does not depend on it: the roles a
|
|
577
|
+
* policy matches come from `getUserRoles(user.id)`, and Better-Auth does not
|
|
578
|
+
* populate `role` on a session at all. The engine's own callers cast it in
|
|
579
|
+
* rather than having one. Demanding it here only made every extension invent
|
|
580
|
+
* a value the engine ignores.
|
|
581
|
+
*/
|
|
582
|
+
getRlsFilters: (collection: string, user: {
|
|
583
|
+
id: string;
|
|
584
|
+
email?: string;
|
|
585
|
+
role?: string;
|
|
586
|
+
rlsBypass?: boolean;
|
|
587
|
+
authorUserId?: string | null;
|
|
588
|
+
}, authType: 'session' | 'api_key') => Promise<RlsFilter[]>;
|
|
589
|
+
/** Apply what `getRlsFilters` returned to a query builder. */
|
|
590
|
+
applyRlsFilters: <Q>(query: Q, filters: RlsFilter[]) => Q;
|
|
591
|
+
/**
|
|
592
|
+
* Columns this role may not read, and may not write.
|
|
593
|
+
*
|
|
594
|
+
* No db parameter: the host resolves the handle. Column permissions are
|
|
595
|
+
* instance configuration rather than tenant rows, so letting each extension
|
|
596
|
+
* pick a handle would only be a way to get it wrong.
|
|
597
|
+
*/
|
|
598
|
+
getColumnAccess: (collection: string, role: string,
|
|
599
|
+
/**
|
|
600
|
+
* The acting user's id. Optional, and additive — omitting it means no
|
|
601
|
+
* exemption, which is the refusing direction, so an extension written
|
|
602
|
+
* against the two-argument form keeps working and keeps masking.
|
|
603
|
+
*
|
|
604
|
+
* Pass it to have the host resolve `data:view_all_columns` for that
|
|
605
|
+
* identity. That permission is how "god sees everything" is expressed for
|
|
606
|
+
* columns: `checkPermission` returns true for a god user before consulting
|
|
607
|
+
* any policy, and everything else is deny-by-default. Without the id there
|
|
608
|
+
* is no identity to resolve it for, so even a god is masked.
|
|
609
|
+
*
|
|
610
|
+
* For an API key pass the principal itself (`c.get('user')`): its bare
|
|
611
|
+
* `apikey:<id>` names no issuer, and a key's columns are bounded by its
|
|
612
|
+
* issuer's, so a bare key id sees none.
|
|
613
|
+
*/
|
|
614
|
+
userId?: string | {
|
|
615
|
+
id: string;
|
|
616
|
+
authorUserId?: string | null;
|
|
617
|
+
}) => Promise<{
|
|
618
|
+
hidden: Set<string>;
|
|
619
|
+
readOnly: Set<string>;
|
|
620
|
+
}>;
|
|
621
|
+
/**
|
|
622
|
+
* The single role behind a user — what `getColumnAccess` keys on. Drawn from
|
|
623
|
+
* Casbin, the one source of roles: `god` (the instance attribute) > `member`
|
|
624
|
+
* (the `g <user> member *` row every account gets) > `public`. A user's full
|
|
625
|
+
* role set is `getUserRoles`.
|
|
626
|
+
*/
|
|
627
|
+
resolveUserRole: (user: {
|
|
628
|
+
id?: string;
|
|
629
|
+
role?: string;
|
|
630
|
+
}) => Promise<string>;
|
|
631
|
+
/**
|
|
632
|
+
* The engine's whole read gate for one caller on one collection: row policies,
|
|
633
|
+
* extension query alters, entity-access checks (`view`) and column
|
|
634
|
+
* permissions, resolved together — what every engine read path uses. Prefer it
|
|
635
|
+
* to composing `getRlsFilters` + `getColumnAccess`, which leaves out the alters
|
|
636
|
+
* and entity checks another extension registered.
|
|
637
|
+
*
|
|
638
|
+
* const scope = await ctx.internals.readScope(coll, user, 'session');
|
|
639
|
+
* const rows = await scope.keep(await scope.query(db.selectFrom(t).selectAll()).execute());
|
|
640
|
+
* return rows.map(scope.shape);
|
|
641
|
+
*/
|
|
642
|
+
readScope: (collection: string, user: {
|
|
643
|
+
id: string;
|
|
644
|
+
email?: string;
|
|
645
|
+
role?: string;
|
|
646
|
+
rlsBypass?: boolean;
|
|
647
|
+
}, authType: 'session' | 'api_key') => Promise<ReadScope>;
|
|
648
|
+
/**
|
|
649
|
+
* Write one record exactly as `POST /api/data/:collection` does — access check,
|
|
650
|
+
* column permissions, hooks, then revision, webhooks, flows and realtime — and
|
|
651
|
+
* answer with that route's status and JSON body (201 and the row on success).
|
|
652
|
+
*
|
|
653
|
+
* Acts as the caller the engine authenticated for `c`, the handler's own
|
|
654
|
+
* request context: session or API key, with the key's scopes and authorship.
|
|
655
|
+
* There is no way to name another identity. Throws outside that request (a
|
|
656
|
+
* job, a listener, a context kept from an earlier request). Needs `data:write`.
|
|
657
|
+
*/
|
|
658
|
+
createRecord: (c: Context, collection: string, data: Record<string, unknown>) => Promise<DataApiAnswer>;
|
|
659
|
+
/**
|
|
660
|
+
* `PATCH /api/data/:collection/:id`, as `createRecord`: 404 for a row the
|
|
661
|
+
* caller cannot see, 403 for one they may not change. With `expect`, as
|
|
662
|
+
* `host.collections` `update`: the write happens only if each listed field
|
|
663
|
+
* currently holds one of the given values, checked on the locked row;
|
|
664
|
+
* otherwise 409, code `precondition_failed`.
|
|
665
|
+
*/
|
|
666
|
+
updateRecord: (c: Context, collection: string, id: string, data: Record<string, unknown>, options?: {
|
|
667
|
+
expect?: UpdateExpect;
|
|
668
|
+
}) => Promise<DataApiAnswer>;
|
|
669
|
+
/** `DELETE /api/data/:collection/:id`, as `updateRecord`. */
|
|
670
|
+
deleteRecord: (c: Context, collection: string, id: string) => Promise<DataApiAnswer>;
|
|
671
|
+
/**
|
|
672
|
+
* Read one record exactly as `GET /api/data/:collection/:id` does — permission,
|
|
673
|
+
* RLS, column rules — as the same caller as `createRecord`. 200 and the record,
|
|
674
|
+
* 404 for one the caller cannot see. Throws outside the request.
|
|
675
|
+
*
|
|
676
|
+
* In one of the extension's `publicRoutes` the caller is the anonymous
|
|
677
|
+
* visitor: the tenant's `public` role, as `GET /api/data` serves it, whatever
|
|
678
|
+
* session the request carries; it holds no grant until an operator gives one.
|
|
679
|
+
* The request is charged once to the anonymous read rate limit; over it, the
|
|
680
|
+
* read throws the 429 (ADR 0020, 3.0.0-beta.99; it threw there before).
|
|
681
|
+
*/
|
|
682
|
+
readRecord: (c: Context, collection: string, id: string) => Promise<DataApiAnswer>;
|
|
683
|
+
/** `GET /api/data/:collection` with the route's own query parameters, as `readRecord`. */
|
|
684
|
+
listRecords: (c: Context, collection: string, query?: DataApiReadQuery) => Promise<DataApiAnswer>;
|
|
685
|
+
/** Is this user an administrator of the current tenant? */
|
|
686
|
+
/**
|
|
687
|
+
* The tenant to add as an explicit `tenant_id =` beside the RLS policy, or
|
|
688
|
+
* `null` when one must not be added.
|
|
689
|
+
*
|
|
690
|
+
* The policy reads `tenant_id = ANY (…)` over an array the planner does not
|
|
691
|
+
* see until execution, so it cannot drive an ordered index scan: a read that
|
|
692
|
+
* filters and orders walks `created_at` and discards whatever the policy
|
|
693
|
+
* excludes. Measured on 300 000 rows: 46 ms, every row discarded to return 25.
|
|
694
|
+
*
|
|
695
|
+
* Performance only — the policy still decides what may be seen, and an
|
|
696
|
+
* equality can only narrow what it already allows. `null` whenever the reach
|
|
697
|
+
* is wider than one tenant, so the safe shape is:
|
|
698
|
+
*
|
|
699
|
+
* const t = ctx.internals.getSingleTenantId();
|
|
700
|
+
* if (t) q = q.where('tenant_id', '=', t);
|
|
701
|
+
*/
|
|
702
|
+
getSingleTenantId: () => string | null;
|
|
703
|
+
/**
|
|
704
|
+
* Display names for a set of user ids, as `{ [id]: name }`. Ids with no row,
|
|
705
|
+
* or with a null name, are absent — render the id instead.
|
|
706
|
+
*
|
|
707
|
+
* Extensions cannot read the Better-Auth `user` table, and rendering "who
|
|
708
|
+
* asked for this" is a real need: `workflow/approvals` had been joining that
|
|
709
|
+
* table directly through a gap in the table guard. This hands over names and
|
|
710
|
+
* nothing else, so printing a name never requires a grant on a table that
|
|
711
|
+
* also holds emails and roles.
|
|
712
|
+
*/
|
|
713
|
+
getUserNames: (userIds: string[]) => Promise<Record<string, string>>;
|
|
714
|
+
isTenantAdmin: (userId: string) => Promise<boolean>;
|
|
715
|
+
/**
|
|
716
|
+
* Facts about the tenant this work runs as, scoped by the engine — the path
|
|
717
|
+
* in place of raw SQL on `"user"`, `zv_tenant_users`, `zv_tenants`,
|
|
718
|
+
* `pg_class`, `zvd_permissions` and `zv_settings`, which `ctx.db` refuses.
|
|
719
|
+
*/
|
|
720
|
+
/** People with a membership in force in the running tenant, and its owners/admins. */
|
|
721
|
+
countMembers: () => Promise<{
|
|
722
|
+
total: number;
|
|
723
|
+
admins: number;
|
|
724
|
+
}>;
|
|
725
|
+
/** Collection count, and a planner row estimate (`null` on a multi-tenant instance). */
|
|
726
|
+
getDataStats: () => Promise<{
|
|
727
|
+
collections: number;
|
|
728
|
+
records_estimate: number | null;
|
|
729
|
+
}>;
|
|
730
|
+
/** Role names granted in the running tenant or in every tenant. */
|
|
731
|
+
listRoles: () => Promise<string[]>;
|
|
732
|
+
/** A setting the instance marks public (`is_public`); `null` otherwise. */
|
|
733
|
+
getPublicSetting: (key: string) => Promise<unknown>;
|
|
734
|
+
/** Append to the audit log, as a row of the running tenant (instance-level where none runs). The engine stamps `metadata.extension` with the caller. */
|
|
735
|
+
audit: (event: {
|
|
736
|
+
type: string;
|
|
737
|
+
userId?: string;
|
|
738
|
+
resourceId?: string;
|
|
739
|
+
resourceType?: string;
|
|
740
|
+
metadata?: Record<string, unknown>;
|
|
741
|
+
ip?: string;
|
|
742
|
+
}) => Promise<void>;
|
|
743
|
+
/**
|
|
744
|
+
* Run `fn` acting as the system inside the running tenant, for the named
|
|
745
|
+
* collections (`['products']`, not `zvd_products`): collection permissions
|
|
746
|
+
* stand down for `ctx.db` during the call; tenant isolation and the table
|
|
747
|
+
* guard do not. Needs the `data:system` capability. Every call is audited
|
|
748
|
+
* with the extension, the user, the collections and `reason`.
|
|
749
|
+
*/
|
|
750
|
+
asSystem: <T>(collections: readonly string[], fn: () => Promise<T>, opts?: {
|
|
751
|
+
reason?: string;
|
|
752
|
+
}) => Promise<T>;
|
|
753
|
+
/**
|
|
754
|
+
* Queue one of this extension's jobs from a handler of one of its
|
|
755
|
+
* `publicRoutes` — an inbound signed webhook verifies the signature, stores
|
|
756
|
+
* the raw event, enqueues, and the job does the writes through
|
|
757
|
+
* `host.collections` (ADR 0018). `c` is the handler's request context. The job
|
|
758
|
+
* lists the route in its manifest `fromPublicRoutes`; `input` must match its
|
|
759
|
+
* schema. The enqueue joins the request transaction: it rolls back with the
|
|
760
|
+
* request. The job has no author. Needs `data:system`; audited. Throws
|
|
761
|
+
* anywhere else. Absent before 3.0.0-beta.97.
|
|
762
|
+
*/
|
|
763
|
+
enqueue?: (c: Context, job: string, input: unknown) => Promise<string>;
|
|
764
|
+
/**
|
|
765
|
+
* The running tenant's recent audit rows, newest first — never another
|
|
766
|
+
* tenant's, never instance-level events. `limit` defaults to 20, capped at
|
|
767
|
+
* 100. No `metadata` or `ip`. Needs the `audit:read` capability.
|
|
768
|
+
*/
|
|
769
|
+
readAuditActivity: (query?: {
|
|
770
|
+
limit?: number;
|
|
771
|
+
eventType?: string;
|
|
772
|
+
resourceType?: string;
|
|
773
|
+
since?: Date | string;
|
|
774
|
+
}) => Promise<{
|
|
775
|
+
id: string;
|
|
776
|
+
event_type: string;
|
|
777
|
+
user_id: string | null;
|
|
778
|
+
resource_type: string | null;
|
|
779
|
+
resource_id: string | null;
|
|
780
|
+
created_at: Date;
|
|
781
|
+
}[]>;
|
|
782
|
+
/**
|
|
783
|
+
* How many of the running tenant's audit rows match, from `since` on. Same
|
|
784
|
+
* scope as `readAuditActivity`; a number, so ungated.
|
|
785
|
+
*/
|
|
786
|
+
countAuditActivity: (query: {
|
|
787
|
+
since: Date | string;
|
|
788
|
+
eventType?: string;
|
|
789
|
+
resourceType?: string;
|
|
790
|
+
}) => Promise<number>;
|
|
791
|
+
/**
|
|
792
|
+
* Instance-level admin, as distinct from admin-within-a-tenant.
|
|
793
|
+
*
|
|
794
|
+
* `checkPermission(userId, 'admin', '*')` is TRUE for a delegated tenant
|
|
795
|
+
* owner inside their own domain — the `tenant_owner` policy is `('*','*','*')`
|
|
796
|
+
* there. That is the right answer for tenant-scoped screens and the wrong one
|
|
797
|
+
* for anything that reaches the instance: raw SQL, schema changes, role
|
|
798
|
+
* grants. Use this for those.
|
|
799
|
+
*/
|
|
800
|
+
requireInstanceAdmin: (userId: string) => Promise<boolean>;
|
|
134
801
|
/** Run an Edge Function in the sandbox (used by developer/edge-functions). */
|
|
135
802
|
runEdgeFunction: (...args: any[]) => Promise<unknown>;
|
|
136
803
|
/** Cross-extension hook registry (e.g. trash purge, scheduled cleanups). */
|
|
137
804
|
extensionRegistry: any;
|
|
138
805
|
/** Queue an HTML→PDF render via the worker pool. */
|
|
139
806
|
generatePDFAsync: (html: string, options?: Record<string, unknown>) => Promise<unknown>;
|
|
140
|
-
/**
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
/** Move a file to the trash bucket (soft delete with TTL). */
|
|
807
|
+
/**
|
|
808
|
+
* Move a file to the trash bucket (soft delete with TTL): `(db, fileId, deletedBy)`.
|
|
809
|
+
* Only a file of the tenant the request or job runs as; outside one it rejects.
|
|
810
|
+
*/
|
|
145
811
|
moveToTrash: (...args: any[]) => Promise<unknown>;
|
|
146
|
-
/** Schedule async indexing for a newly uploaded file. */
|
|
147
|
-
scheduleFileIndexing: (...args: any[]) => Promise<unknown>;
|
|
148
|
-
/** GraphQL DataLoader registry — N+1 query batching. */
|
|
149
|
-
DataLoaderRegistry: any;
|
|
150
|
-
/** Validate GraphQL query depth. Returns an error message if too deep, null otherwise. */
|
|
151
|
-
checkQueryDepth: (query: string, maxDepth?: number) => string | null;
|
|
152
812
|
/** Enqueue an asynchronous DDL job (Ghost Tables, large alters). */
|
|
153
813
|
enqueueDDLJob: (...args: any[]) => Promise<unknown>;
|
|
154
|
-
/**
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
814
|
+
/**
|
|
815
|
+
* Validate that a URL targets a public, non-internal address (SSRF safety).
|
|
816
|
+
* Synchronous — throws on a blocked URL and returns nothing. Safe to call from
|
|
817
|
+
* a sync context such as a zod `superRefine`. This checks only the literal
|
|
818
|
+
* host text; prefer {@link assertPublicUrl} wherever you can await.
|
|
819
|
+
*/
|
|
820
|
+
validatePublicUrl: (url: string) => void;
|
|
821
|
+
/**
|
|
822
|
+
* DNS-aware SSRF check: everything `validatePublicUrl` does, plus rejecting
|
|
823
|
+
* hostnames that RESOLVE into private space (an attacker-owned name with an A
|
|
824
|
+
* record pointing at cloud metadata). MUST be awaited.
|
|
825
|
+
*/
|
|
826
|
+
/**
|
|
827
|
+
* Resolves to the address to connect to, or null when there is nothing to pin
|
|
828
|
+
* (an IP literal, or a name that did not resolve). Ignoring the value keeps
|
|
829
|
+
* the previous behaviour; using it closes the DNS rebinding race, which is
|
|
830
|
+
* what the host's own `safeFetch` does.
|
|
831
|
+
*/
|
|
832
|
+
assertPublicUrl: (url: string) => Promise<string | null>;
|
|
833
|
+
/**
|
|
834
|
+
* `fetch` with the SSRF guard applied where it has to be.
|
|
835
|
+
*
|
|
836
|
+
* Validating a URL before calling `fetch` is not enough on its own: fetch
|
|
837
|
+
* follows redirects, so a public host answering 302 to 169.254.169.254
|
|
838
|
+
* walks past a check performed on the original URL. This re-validates
|
|
839
|
+
* every redirect target, under a hop limit. Prefer it over `fetch` for
|
|
840
|
+
* any URL a user or a stored record can influence.
|
|
841
|
+
*/
|
|
842
|
+
safeFetch: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
843
|
+
/**
|
|
844
|
+
* SSRF guard for an admin-configured endpoint that is ALLOWED to be
|
|
845
|
+
* self-hosted (local Ollama on `http://localhost:11434`, an internal
|
|
846
|
+
* Meilisearch, on-prem object storage). Permits private ranges but rejects
|
|
847
|
+
* cloud-metadata hosts such as 169.254.169.254. Use this — NOT
|
|
848
|
+
* `validatePublicUrl` / `assertPublicUrl` — for provider "base URL" settings,
|
|
849
|
+
* otherwise every self-hosted deployment breaks. Synchronous; throws when
|
|
850
|
+
* the URL is blocked.
|
|
851
|
+
*/
|
|
852
|
+
assertNonMetadataUrl: (url: string, label?: string) => void;
|
|
158
853
|
/** Send an in-app notification to a user (writes to zv_notifications system table). */
|
|
159
854
|
sendNotification: (db: any, input: {
|
|
160
855
|
user_id: string;
|
|
@@ -164,23 +859,24 @@ export interface ExtensionInternals {
|
|
|
164
859
|
data?: unknown;
|
|
165
860
|
}) => Promise<void>;
|
|
166
861
|
/**
|
|
167
|
-
*
|
|
862
|
+
* Sign in a user your extension has already verified (SSO bridge: LDAP,
|
|
863
|
+
* SAML, OIDC). The session is written by the engine's better-auth — its pool
|
|
864
|
+
* and, with Valkey, its session cache — so `auth.api.getSession` accepts the
|
|
865
|
+
* cookie; `ctx.db` cannot reach the `session` table. Refuses a deactivated
|
|
866
|
+
* user with an error whose `code` is `'account_disabled'`.
|
|
168
867
|
*
|
|
169
|
-
*
|
|
170
|
-
*
|
|
171
|
-
*
|
|
172
|
-
*
|
|
173
|
-
*
|
|
174
|
-
*
|
|
175
|
-
* Returns the `Set-Cookie` header value — the route handler attaches it to
|
|
176
|
-
* its Response. Pass `crossDomain: true` to emit `SameSite=None; Secure`
|
|
177
|
-
* (needed when Studio runs on a different origin than the engine).
|
|
868
|
+
* `db` is your transaction: pass the one that provisioned the user. A user it
|
|
869
|
+
* created gets their session when it commits, and none if it rolls back.
|
|
870
|
+
* `replaceExisting` ends the user's other sessions once this one is written
|
|
871
|
+
* and your request commits. Returns the `Set-Cookie` header value for your
|
|
872
|
+
* Response. Needs `auth:session`.
|
|
178
873
|
*/
|
|
179
874
|
createBetterAuthSession: (db: any, userId: string, opts?: {
|
|
180
875
|
ipAddress?: string;
|
|
181
876
|
userAgent?: string;
|
|
182
877
|
ttlSeconds?: number;
|
|
183
878
|
crossDomain?: boolean;
|
|
879
|
+
replaceExisting?: boolean;
|
|
184
880
|
}) => Promise<{
|
|
185
881
|
token: string;
|
|
186
882
|
setCookie: string;
|
|
@@ -193,12 +889,203 @@ export interface ExtensionInternals {
|
|
|
193
889
|
* extensions should refuse the write rather than persist plaintext.
|
|
194
890
|
*/
|
|
195
891
|
encryptSecret: (plaintext: string) => Promise<string>;
|
|
892
|
+
/**
|
|
893
|
+
* HMAC-SHA256 under the instance auth secret, hex encoded. A compatibility
|
|
894
|
+
* surface for `auth/scim`'s stored bearer-token hashes — not a general MAC.
|
|
895
|
+
*/
|
|
896
|
+
deriveTokenHash: (raw: string) => Promise<string>;
|
|
897
|
+
/**
|
|
898
|
+
* Quoted, formula-safe CSV cell. Ungated: a pure string function with no
|
|
899
|
+
* authority. Every extension that exports CSV was writing its own escaping,
|
|
900
|
+
* and quoting alone does not stop a spreadsheet executing a cell that starts
|
|
901
|
+
* with `=`.
|
|
902
|
+
*/
|
|
903
|
+
csvCell: (value: unknown) => string;
|
|
904
|
+
/** Rows → CSV document, using `csvCell` for every cell. */
|
|
905
|
+
recordsToCsv: (records: Record<string, unknown>[]) => string;
|
|
196
906
|
/**
|
|
197
907
|
* Reverse of `encryptSecret`. Returns the plaintext if the value has
|
|
198
908
|
* the `enc:v1:` prefix; otherwise returns the value as-is so reads of
|
|
199
909
|
* legacy unencrypted rows still work during a rolling encryption rollout.
|
|
200
910
|
*/
|
|
201
911
|
decryptSecret: (value: string) => Promise<string>;
|
|
912
|
+
/**
|
|
913
|
+
* Delete a user exactly as `DELETE /api/users/:id` does: revoke their
|
|
914
|
+
* sessions (database AND cache), drop their grants, delete the row and audit
|
|
915
|
+
* `user.deleted` with `who`. `db` is the handle the row delete and the audit
|
|
916
|
+
* row run on — pass your transaction so they commit with it. Resolves `false`
|
|
917
|
+
* when there is no such user. Needs the `auth:users` capability.
|
|
918
|
+
*
|
|
919
|
+
* `actorUserId` must be a real user id (the audit column references "user");
|
|
920
|
+
* a non-user actor — a SCIM token, the erased subject — goes in `actor`.
|
|
921
|
+
*/
|
|
922
|
+
deleteUser: (db: unknown, userId: string, who: {
|
|
923
|
+
actorUserId?: string | null;
|
|
924
|
+
actor?: string;
|
|
925
|
+
reason: string;
|
|
926
|
+
metadata?: Record<string, unknown>;
|
|
927
|
+
}) => Promise<boolean>;
|
|
928
|
+
/**
|
|
929
|
+
* End every session a user has, in the database AND the cache — `ctx.db`
|
|
930
|
+
* cannot reach either. Needs the `auth:users` capability.
|
|
931
|
+
*/
|
|
932
|
+
revokeUserSessions: (userId: string) => Promise<void>;
|
|
933
|
+
/**
|
|
934
|
+
* What the engine's own tables hold about a user — profile, their audit
|
|
935
|
+
* rows in every tenant and at instance level, notifications, the API keys
|
|
936
|
+
* they created (names, never secrets) and their approval requests — for a
|
|
937
|
+
* data-subject access request. `null` when there is no such user. Needs the
|
|
938
|
+
* `auth:users` capability.
|
|
939
|
+
*/
|
|
940
|
+
exportUserData: (userId: string) => Promise<{
|
|
941
|
+
profile: {
|
|
942
|
+
id: string;
|
|
943
|
+
name: string | null;
|
|
944
|
+
email: string;
|
|
945
|
+
created_at: string;
|
|
946
|
+
} | null;
|
|
947
|
+
audit_log: Array<{
|
|
948
|
+
action: string;
|
|
949
|
+
collection: string | null;
|
|
950
|
+
record_id: string | null;
|
|
951
|
+
created_at: string;
|
|
952
|
+
}>;
|
|
953
|
+
notifications: Array<{
|
|
954
|
+
title: string;
|
|
955
|
+
message: string | null;
|
|
956
|
+
type: string | null;
|
|
957
|
+
is_read: boolean;
|
|
958
|
+
created_at: string;
|
|
959
|
+
}>;
|
|
960
|
+
api_keys: Array<{
|
|
961
|
+
name: string;
|
|
962
|
+
key_prefix: string | null;
|
|
963
|
+
scopes: unknown;
|
|
964
|
+
created_at: string;
|
|
965
|
+
}>;
|
|
966
|
+
approval_requests: Array<{
|
|
967
|
+
id: string;
|
|
968
|
+
collection: string;
|
|
969
|
+
record_id: string | null;
|
|
970
|
+
status: string;
|
|
971
|
+
requested_at: string;
|
|
972
|
+
}>;
|
|
973
|
+
} | null>;
|
|
974
|
+
/**
|
|
975
|
+
* `false` stops the user signing in by ANY method (password, magic link,
|
|
976
|
+
* passkey, OAuth, SSO) and revokes their sessions; `true` lets them back in
|
|
977
|
+
* with the credentials they had. Instance-wide: a user has one sign-in, not
|
|
978
|
+
* one per tenant. `db` is your transaction — pass the one that may already
|
|
979
|
+
* have written the user's row. Needs the `auth:users` capability.
|
|
980
|
+
*
|
|
981
|
+
* A ban records your extension as its source (`"user".ban_source =
|
|
982
|
+
* 'ext:<your name>'`, taken by the host, not from you). Banning an account
|
|
983
|
+
* that is already banned keeps the first source. `true` lifts ANY ban,
|
|
984
|
+
* an administrator's included — kept for extensions written before
|
|
985
|
+
* `liftOwnBan`; to undo your own ban, use `liftOwnBan`.
|
|
986
|
+
*/
|
|
987
|
+
setUserActive: (db: unknown, userId: string, active: boolean) => Promise<void>;
|
|
988
|
+
/**
|
|
989
|
+
* Lift the user's ban only if YOUR extension placed it (through
|
|
990
|
+
* `setUserActive(…, false)`); resolves whether it did. A ban an
|
|
991
|
+
* administrator, another extension or raw SQL placed stays. Needs the
|
|
992
|
+
* `auth:users` capability.
|
|
993
|
+
*/
|
|
994
|
+
liftOwnBan: (db: unknown, userId: string) => Promise<boolean>;
|
|
995
|
+
/** Whether at most one tenant exists — then every user belongs to it. Ungated. */
|
|
996
|
+
isSingleTenantInstance: () => Promise<boolean>;
|
|
997
|
+
/**
|
|
998
|
+
* The account for `email` (case-insensitive), created when there is none:
|
|
999
|
+
* verified, no password, never god, in no tenant. Works while
|
|
1000
|
+
* self-registration is off. Inside `withTenantIsolation` it is created in
|
|
1001
|
+
* that transaction, and a rollback takes it back. An account that already
|
|
1002
|
+
* exists comes back only if the running tenant has a claim to it: a member
|
|
1003
|
+
* here with no power elsewhere beyond plain membership, any account but god
|
|
1004
|
+
* and the instance admins on a single-tenant instance, or a bare record (no
|
|
1005
|
+
* credential, membership or grant). Anyone else is `account_exists`: they join
|
|
1006
|
+
* through an invitation, which proves they control the address.
|
|
1007
|
+
*/
|
|
1008
|
+
provisionUser: (input: {
|
|
1009
|
+
email: string;
|
|
1010
|
+
name?: string;
|
|
1011
|
+
}) => Promise<{
|
|
1012
|
+
user: ProvisionedUser;
|
|
1013
|
+
created: boolean;
|
|
1014
|
+
}>;
|
|
1015
|
+
/**
|
|
1016
|
+
* Users of the running tenant — a membership there, lapsed included — or
|
|
1017
|
+
* every user on a single-tenant instance (`membership: null`). By creation
|
|
1018
|
+
* order; `limit` defaults to 100, at most 1000.
|
|
1019
|
+
*/
|
|
1020
|
+
listTenantUsers: (db: unknown, query?: {
|
|
1021
|
+
email?: string;
|
|
1022
|
+
userId?: string;
|
|
1023
|
+
limit?: number;
|
|
1024
|
+
offset?: number;
|
|
1025
|
+
}) => Promise<Array<ProvisionedUser & {
|
|
1026
|
+
membership: TenantMembershipInfo | null;
|
|
1027
|
+
}>>;
|
|
1028
|
+
/**
|
|
1029
|
+
* Rename or re-address a user the running tenant ALONE holds: a membership
|
|
1030
|
+
* here (any user on a single-tenant instance), not god, not an instance admin,
|
|
1031
|
+
* no membership or grant in any other tenant (`user_not_owned` otherwise).
|
|
1032
|
+
* `db` is your transaction.
|
|
1033
|
+
*/
|
|
1034
|
+
updateUserProfile: (db: unknown, userId: string, patch: {
|
|
1035
|
+
name?: string;
|
|
1036
|
+
email?: string;
|
|
1037
|
+
}) => Promise<ProvisionedUser>;
|
|
1038
|
+
/**
|
|
1039
|
+
* Make the user a `member` (default) or `viewer` of the running tenant, or
|
|
1040
|
+
* switch between the two, with the matching tenant role. Dates are kept: a
|
|
1041
|
+
* membership that ended is not reopened. An `owner`/`admin` is refused.
|
|
1042
|
+
*/
|
|
1043
|
+
addTenantMember: (db: unknown, userId: string, role?: 'member' | 'viewer') => Promise<'added' | 'role_changed' | 'unchanged'>;
|
|
1044
|
+
/**
|
|
1045
|
+
* Remove the user from the running tenant with every role they hold in it.
|
|
1046
|
+
* `orphaned`: no tenant and nothing else holds the account now — deleting it
|
|
1047
|
+
* (`deleteUser`, `auth:users`) is your call. `inForceAnywhere`: a membership
|
|
1048
|
+
* in force remains in some tenant. An owner or admin of the tenant (in the
|
|
1049
|
+
* default tenant, an instance admin) is refused, `role_not_allowed`.
|
|
1050
|
+
*/
|
|
1051
|
+
removeTenantMember: (db: unknown, userId: string) => Promise<{
|
|
1052
|
+
removed: boolean;
|
|
1053
|
+
orphaned: boolean;
|
|
1054
|
+
inForceAnywhere: boolean;
|
|
1055
|
+
}>;
|
|
1056
|
+
/**
|
|
1057
|
+
* Set when the user's membership of the running tenant ends: `'now'`, an
|
|
1058
|
+
* ISO-8601 instant, or `null` (open-ended). `ifInForce` changes only a
|
|
1059
|
+
* membership in force; `ifValidTo` only one whose end is still exactly that
|
|
1060
|
+
* value. `null` when the user is no member here. An owner or admin is
|
|
1061
|
+
* refused, `role_not_allowed`.
|
|
1062
|
+
*/
|
|
1063
|
+
setTenantMembershipEnd: (db: unknown, userId: string, validTo: string | null, guard?: {
|
|
1064
|
+
ifInForce?: boolean;
|
|
1065
|
+
ifValidTo?: string | null;
|
|
1066
|
+
}) => Promise<{
|
|
1067
|
+
changed: boolean;
|
|
1068
|
+
previousValidTo: string | null;
|
|
1069
|
+
validTo: string | null;
|
|
1070
|
+
inForceAnywhere: boolean;
|
|
1071
|
+
} | null>;
|
|
1072
|
+
}
|
|
1073
|
+
/** A user as `ctx.internals` identity provisioning returns it. */
|
|
1074
|
+
export interface ProvisionedUser {
|
|
1075
|
+
id: string;
|
|
1076
|
+
email: string;
|
|
1077
|
+
name: string;
|
|
1078
|
+
emailVerified: boolean;
|
|
1079
|
+
createdAt: string;
|
|
1080
|
+
updatedAt: string;
|
|
1081
|
+
}
|
|
1082
|
+
/** A user's membership of the running tenant. */
|
|
1083
|
+
export interface TenantMembershipInfo {
|
|
1084
|
+
role: 'owner' | 'admin' | 'member' | 'viewer';
|
|
1085
|
+
validFrom: string;
|
|
1086
|
+
/** `null`: open-ended. */
|
|
1087
|
+
validTo: string | null;
|
|
1088
|
+
inForce: boolean;
|
|
202
1089
|
}
|
|
203
1090
|
/**
|
|
204
1091
|
* Entity-access scope handed to each extension via `ctx.entityAccess`.
|
|
@@ -273,18 +1160,59 @@ export interface QueryAlterScope {
|
|
|
273
1160
|
* `register()` is idempotent within a scope (replaces on duplicate), so an
|
|
274
1161
|
* extension's `register()` can safely run multiple times during hot-reload.
|
|
275
1162
|
*/
|
|
1163
|
+
/**
|
|
1164
|
+
* A manifest `dependencies` / `optionalDependencies` entry. A required one must be
|
|
1165
|
+
* installed for this extension to load; an optional one need not be — its
|
|
1166
|
+
* services then read as `null`. Either way, the extensions named in these two
|
|
1167
|
+
* lists are the only ones whose services `ctx.services` hands this one.
|
|
1168
|
+
*/
|
|
1169
|
+
export interface ManifestDependency {
|
|
1170
|
+
name: string;
|
|
1171
|
+
minVersion?: string;
|
|
1172
|
+
}
|
|
1173
|
+
/**
|
|
1174
|
+
* Cross-replica messages, scoped to the extension that holds them: `publish`
|
|
1175
|
+
* sends under its name and `on` hears only its own, so no extension can speak
|
|
1176
|
+
* for another or for the engine.
|
|
1177
|
+
*
|
|
1178
|
+
* Meant for invalidation — "firm X's providers changed, read them again" — not
|
|
1179
|
+
* for data: send an id, let each replica read the rest from the database.
|
|
1180
|
+
*/
|
|
1181
|
+
export interface ExtensionBroadcast {
|
|
1182
|
+
/**
|
|
1183
|
+
* Deliver `data` to this extension's `on(name)` handlers on every replica,
|
|
1184
|
+
* this one included, once the current transaction commits (at once outside
|
|
1185
|
+
* one; never after a rollback). Each handler runs in the publisher's tenant
|
|
1186
|
+
* transaction, so `ctx.db` there is that tenant's. Rejects a `name` outside
|
|
1187
|
+
* `[A-Za-z0-9._:-]{1,64}` and a message over the bus limit (~7.9 KB of JSON).
|
|
1188
|
+
* Delivery is at most once: see `onMissed`.
|
|
1189
|
+
*/
|
|
1190
|
+
publish(name: string, data?: unknown): Promise<void>;
|
|
1191
|
+
/** Run `handler` for each `name` message; it receives `data` as JSON gave it back. */
|
|
1192
|
+
on(name: string, handler: (data: unknown) => void | Promise<void>): () => void;
|
|
1193
|
+
/**
|
|
1194
|
+
* Run `handler` when this replica may have missed messages (its bus
|
|
1195
|
+
* connection came back), outside any tenant: drop every cache the messages
|
|
1196
|
+
* keep fresh.
|
|
1197
|
+
*/
|
|
1198
|
+
onMissed(handler: () => void | Promise<void>): () => void;
|
|
1199
|
+
}
|
|
276
1200
|
export interface ServiceRegistry {
|
|
277
1201
|
/**
|
|
278
|
-
* Publish a service under a name
|
|
1202
|
+
* Publish a service under a name, which must be `<this extension's name>.<x>`.
|
|
279
1203
|
* Idempotent: re-registering the same name from the same extension replaces.
|
|
280
1204
|
* Throws if a different extension already owns that name.
|
|
281
1205
|
*/
|
|
282
1206
|
register<T = unknown>(name: string, value: T): void;
|
|
283
1207
|
/** Remove a service this extension previously registered. No-op if not owned. */
|
|
284
1208
|
unregister(name: string): void;
|
|
285
|
-
/**
|
|
1209
|
+
/**
|
|
1210
|
+
* Get a service. Returns `null` if not registered (an optional dependency
|
|
1211
|
+
* that is not installed). Throws if its owner is not this extension or one in
|
|
1212
|
+
* its manifest `dependencies` / `optionalDependencies`.
|
|
1213
|
+
*/
|
|
286
1214
|
get<T = unknown>(name: string): T | null;
|
|
287
|
-
/** Check if a service is registered. */
|
|
1215
|
+
/** Check if a service is registered. Throws as `get` does for an undeclared owner. */
|
|
288
1216
|
has(name: string): boolean;
|
|
289
1217
|
/**
|
|
290
1218
|
* Wait for a service to be registered. Resolves immediately if already there.
|
|
@@ -364,6 +1292,15 @@ export interface ExtensionSchedule<DB = any> {
|
|
|
364
1292
|
};
|
|
365
1293
|
/** Reserved — single-engine assumption today. Documented behaviour. */
|
|
366
1294
|
singleton?: boolean;
|
|
1295
|
+
/**
|
|
1296
|
+
* Run once per active tenant where this extension is active, each run inside
|
|
1297
|
+
* that tenant's transaction, so `ctx.db` sees that tenant's rows. Without it
|
|
1298
|
+
* the handler runs once with no tenant in scope, and a table under tenant RLS
|
|
1299
|
+
* answers for the root tenant only. A tenant that fails does not stop the
|
|
1300
|
+
* others; the run then fails naming it, and a retry runs every tenant again,
|
|
1301
|
+
* so the handler must be safe to repeat.
|
|
1302
|
+
*/
|
|
1303
|
+
perTenant?: boolean;
|
|
367
1304
|
}
|
|
368
1305
|
/**
|
|
369
1306
|
* Spec for a route registered on the engine's global app via
|
|
@@ -409,7 +1346,7 @@ export type MountStrategy = 'global' | 'subapp';
|
|
|
409
1346
|
* }
|
|
410
1347
|
* };
|
|
411
1348
|
*/
|
|
412
|
-
export interface ZveltioExtension<DB = any> {
|
|
1349
|
+
export interface ZveltioExtension<DB = any, C extends string = Capability> {
|
|
413
1350
|
/** Unique name — must match manifest.json `name` exactly (e.g. `'hr/employees'`). */
|
|
414
1351
|
name: string;
|
|
415
1352
|
/** Category shown in the marketplace (e.g. `'hr'`, `'finance'`, `'content'`). */
|
|
@@ -424,7 +1361,7 @@ export interface ZveltioExtension<DB = any> {
|
|
|
424
1361
|
* Called once when the extension is activated.
|
|
425
1362
|
* Register Hono routes, subscribe to events, etc.
|
|
426
1363
|
*/
|
|
427
|
-
register: (app: Hono, ctx: ExtensionContext<DB>) => Promise<void>;
|
|
1364
|
+
register: (app: Hono, ctx: ExtensionContext<DB, C>) => Promise<void>;
|
|
428
1365
|
/** Register custom Studio field types contributed by this extension. */
|
|
429
1366
|
registerFieldTypes?: (registry: FieldTypeRegistryAPI) => void;
|
|
430
1367
|
/** Return absolute paths to SQL migration files, run in order on first activation. */
|
|
@@ -440,6 +1377,101 @@ export interface ZveltioExtension<DB = any> {
|
|
|
440
1377
|
* Note: Hono routes cannot be de-registered at runtime — they persist until restart.
|
|
441
1378
|
*/
|
|
442
1379
|
cleanup?: () => Promise<void>;
|
|
1380
|
+
/**
|
|
1381
|
+
* The implementations of the manifest's `actions`, by name — one each, and no
|
|
1382
|
+
* more: the engine refuses to load an extension whose two lists differ. The
|
|
1383
|
+
* engine serves each at `POST /ext/<name>/actions/<action>`: it checks the
|
|
1384
|
+
* declared permission, validates the body against the declared `input`, and
|
|
1385
|
+
* runs the function with that body inside the request's transaction. A throw
|
|
1386
|
+
* fails the request and rolls back everything the action wrote.
|
|
1387
|
+
*/
|
|
1388
|
+
actions?: Record<string, ExtensionAction>;
|
|
1389
|
+
/**
|
|
1390
|
+
* The implementations of the manifest's `jobs`, by name — one each, and no
|
|
1391
|
+
* more, as for `actions`. An action enqueues one (`ActionHost.enqueue`) inside
|
|
1392
|
+
* its request transaction, so a job whose action failed never runs. The engine
|
|
1393
|
+
* runs it after that commits, out of any request, in the enqueuing tenant; a
|
|
1394
|
+
* throw fails the run, which is retried as the manifest's `retry` says.
|
|
1395
|
+
*/
|
|
1396
|
+
jobs?: Record<string, ExtensionJob>;
|
|
1397
|
+
}
|
|
1398
|
+
/**
|
|
1399
|
+
* One action: business logic over the input the engine validated. Returns the
|
|
1400
|
+
* response's `result`; throws `ActionRefusal` to answer the caller with a 4xx.
|
|
1401
|
+
*/
|
|
1402
|
+
export type ExtensionAction = (input: unknown, host: ActionHost) => Promise<unknown>;
|
|
1403
|
+
/**
|
|
1404
|
+
* How an action reaches data: the data API, as the caller, inside the request's
|
|
1405
|
+
* transaction — permissions, RLS, column rules, hooks and audit are the route's.
|
|
1406
|
+
* Only the collections the manifest declares for the action: `reads` for
|
|
1407
|
+
* `read`/`list`, `writes` for `insert`/`update`/`delete` (which also need
|
|
1408
|
+
* `data:write`). A refused write throws with the data API's status, and the
|
|
1409
|
+
* request fails with it.
|
|
1410
|
+
*/
|
|
1411
|
+
export interface ActionHost {
|
|
1412
|
+
collections: HostCollections;
|
|
1413
|
+
/**
|
|
1414
|
+
* The IANA zone "today" means for the request's tenant: the tenant's own
|
|
1415
|
+
* setting, else the instance's, else `UTC`. Pair with `todayIn`.
|
|
1416
|
+
*/
|
|
1417
|
+
timezone: string;
|
|
1418
|
+
/**
|
|
1419
|
+
* Queue one of the jobs this action's manifest entry lists in `enqueues`, with
|
|
1420
|
+
* an `input` its schema accepts — anything else throws. Written in the request
|
|
1421
|
+
* transaction: the job exists only if the request commits. Needs `data:system`.
|
|
1422
|
+
* Resolves to the job's id.
|
|
1423
|
+
*/
|
|
1424
|
+
enqueue(job: string, input: unknown): Promise<string>;
|
|
1425
|
+
/**
|
|
1426
|
+
* Run an action of an extension this one depends on (ADR 0014). The calling
|
|
1427
|
+
* action's manifest entry lists it in `calls` as `<extension>.<action>`; the
|
|
1428
|
+
* engine checks the caller holds that action's permission, validates `input`
|
|
1429
|
+
* against its schema, and runs it in the same request transaction, its writes
|
|
1430
|
+
* carrying the called extension's name. Resolves to what the action returns; a
|
|
1431
|
+
* refusal it throws reaches the caller unchanged. An action run this way cannot
|
|
1432
|
+
* run another. Absent on engines before 3.0.0-beta.94.
|
|
1433
|
+
*/
|
|
1434
|
+
actions?: {
|
|
1435
|
+
run(extension: string, action: string, input: unknown): Promise<unknown>;
|
|
1436
|
+
};
|
|
1437
|
+
}
|
|
1438
|
+
/** The data API, through `ActionHost` or `JobHost`, for the collections the manifest declares. */
|
|
1439
|
+
export interface HostCollections {
|
|
1440
|
+
/** The record, or `null` when the caller cannot see one with this id. */
|
|
1441
|
+
read(collection: string, id: string): Promise<Record<string, unknown> | null>;
|
|
1442
|
+
/** `GET /api/data/:collection`'s body: `{ records, … }`. */
|
|
1443
|
+
list(collection: string, query?: DataApiReadQuery): Promise<Record<string, unknown>>;
|
|
1444
|
+
insert(collection: string, data: Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
1445
|
+
/**
|
|
1446
|
+
* With `expect`, the update happens only if the row's current value of each
|
|
1447
|
+
* listed field is one of the given values — checked on the row locked for the
|
|
1448
|
+
* write, so a concurrent update waits and is then tested against the new row.
|
|
1449
|
+
* Otherwise it throws with status 409, code `precondition_failed`. Each field
|
|
1450
|
+
* must be one the caller can read.
|
|
1451
|
+
*/
|
|
1452
|
+
update(collection: string, id: string, data: Record<string, unknown>, options?: {
|
|
1453
|
+
expect?: UpdateExpect;
|
|
1454
|
+
}): Promise<Record<string, unknown>>;
|
|
1455
|
+
delete(collection: string, id: string): Promise<void>;
|
|
1456
|
+
}
|
|
1457
|
+
/**
|
|
1458
|
+
* A precondition on an update: field name to the values it may currently hold.
|
|
1459
|
+
* Values compare as text (`String(value)`), `null` as SQL NULL.
|
|
1460
|
+
*/
|
|
1461
|
+
export type UpdateExpect = Record<string, readonly (string | number | boolean | null)[]>;
|
|
1462
|
+
/** One job: work over the input the engine validated when it was enqueued. */
|
|
1463
|
+
export type ExtensionJob = (input: unknown, host: JobHost) => Promise<void>;
|
|
1464
|
+
/**
|
|
1465
|
+
* How a job reaches data. A job has no caller: it acts as the extension, with
|
|
1466
|
+
* exactly the job's declared `reads` (read) and `writes` (create, update,
|
|
1467
|
+
* delete) — the data API's checks, as for an API key holding those scopes — in
|
|
1468
|
+
* the tenant it was enqueued in, in a transaction of its own. Rows it writes are
|
|
1469
|
+
* authored by the user whose action enqueued it.
|
|
1470
|
+
*/
|
|
1471
|
+
export interface JobHost {
|
|
1472
|
+
collections: HostCollections;
|
|
1473
|
+
/** As `ActionHost.timezone`, for the tenant that enqueued the job. */
|
|
1474
|
+
timezone: string;
|
|
443
1475
|
}
|
|
444
1476
|
export interface StudioExtensionAPI {
|
|
445
1477
|
registerRoute(route: StudioRoute): void;
|
|
@@ -554,5 +1586,21 @@ export interface AssetPreviewHandler {
|
|
|
554
1586
|
}) => boolean;
|
|
555
1587
|
component: any;
|
|
556
1588
|
}
|
|
1589
|
+
/**
|
|
1590
|
+
* Declare an extension together with the capabilities it uses, so `ctx` is typed
|
|
1591
|
+
* by them (roadmap R8). The list must match `permissions` in manifest.json —
|
|
1592
|
+
* the manifest is what the engine enforces and an administrator approves;
|
|
1593
|
+
* `zveltio extension validate` reports a difference.
|
|
1594
|
+
*
|
|
1595
|
+
* export default defineExtension(['secrets'], { name, category, register });
|
|
1596
|
+
*
|
|
1597
|
+
* Returns the extension unchanged, with the list attached as `capabilities`.
|
|
1598
|
+
*/
|
|
1599
|
+
/** `ZveltioExtension`'s own default schema type, without spelling it again. */
|
|
1600
|
+
type DefaultExtensionDB = ZveltioExtension extends ZveltioExtension<infer D> ? D : never;
|
|
1601
|
+
export declare function defineExtension<const C extends readonly Capability[], DB = DefaultExtensionDB>(capabilities: C, extension: ZveltioExtension<DB, C[number]>): ZveltioExtension<DB, C[number]> & {
|
|
1602
|
+
readonly capabilities: C;
|
|
1603
|
+
};
|
|
557
1604
|
export type { Hono };
|
|
1605
|
+
export * from './capabilities.js';
|
|
558
1606
|
//# sourceMappingURL=index.d.ts.map
|