@zjazj/server 0.0.8 → 0.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api-keys-BY7RCE9v.d.ts +215 -0
- package/dist/{chunk-NMKEVYGN.js → chunk-3X4RSAM6.js} +20 -1
- package/dist/{chunk-EIZ24ILA.js → chunk-7FPH47F6.js} +25 -4
- package/dist/chunk-OBKMOVBA.js +345 -0
- package/dist/{chunk-26AAYRI3.js → chunk-VJRJ53T2.js} +1 -0
- package/dist/chunk-XWJAL6GX.js +291 -0
- package/dist/{db-Dp7BB3Kc.d.ts → db-NCwvoAnt.d.ts} +9 -2
- package/dist/db.d.ts +1 -1
- package/dist/db.js +14 -259
- package/dist/dev.d.ts +20 -2
- package/dist/dev.js +7 -1
- package/dist/index.d.ts +245 -37
- package/dist/index.js +687 -110
- package/dist/log.js +1 -1
- package/dist/{mcp-UM4G354G.js → mcp-6W7AB46O.js} +14 -8
- package/dist/objects.d.ts +225 -0
- package/dist/objects.js +371 -0
- package/dist/testing.d.ts +20 -4
- package/dist/testing.js +33 -3
- package/package.json +5 -1
- package/dist/auth-Ckmm4C6y.d.ts +0 -81
- package/dist/chunk-UWDDQH25.js +0 -146
package/dist/log.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import {
|
|
2
2
|
log
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-VJRJ53T2.js";
|
|
4
4
|
import {
|
|
5
5
|
bearerToken,
|
|
6
6
|
getUser,
|
|
7
7
|
hasPermissions
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-7FPH47F6.js";
|
|
9
9
|
import {
|
|
10
10
|
AppError
|
|
11
|
-
} from "./chunk-
|
|
12
|
-
import "./chunk-
|
|
11
|
+
} from "./chunk-OBKMOVBA.js";
|
|
12
|
+
import "./chunk-3X4RSAM6.js";
|
|
13
13
|
import {
|
|
14
14
|
getRequestId
|
|
15
15
|
} from "./chunk-ERGI2X5S.js";
|
|
@@ -59,10 +59,16 @@ function createMcpRoute(options) {
|
|
|
59
59
|
const inTenant = async (c, work) => {
|
|
60
60
|
if (!options.database) return work();
|
|
61
61
|
const { withTenant } = await import("./db.js");
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
62
|
+
const user = getUser(c);
|
|
63
|
+
return withTenant(
|
|
64
|
+
await options.database(),
|
|
65
|
+
user.tenantId,
|
|
66
|
+
async (tx) => {
|
|
67
|
+
c.set("db", tx);
|
|
68
|
+
return work();
|
|
69
|
+
},
|
|
70
|
+
{ userId: user.id }
|
|
71
|
+
);
|
|
66
72
|
};
|
|
67
73
|
const serverFor = (request) => {
|
|
68
74
|
const c = contextOf(request);
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import * as drizzle_orm from 'drizzle-orm';
|
|
2
|
+
import { SQL } from 'drizzle-orm';
|
|
3
|
+
import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
|
|
4
|
+
import { PgTable, AnyPgColumn, PgSchema } from 'drizzle-orm/pg-core';
|
|
5
|
+
import { Context } from 'hono';
|
|
6
|
+
import { T as TenantTable } from './db-NCwvoAnt.js';
|
|
7
|
+
|
|
8
|
+
/** Who sees an object besides its owner and those it is granted to. */
|
|
9
|
+
type ObjectVisibility = 'private' | 'tenant';
|
|
10
|
+
/** What a grant lets its user or role do: see, change as well, or share as well. */
|
|
11
|
+
type GrantLevel = 'viewer' | 'editor' | 'manager';
|
|
12
|
+
type PrincipalType = 'user' | 'role';
|
|
13
|
+
/**
|
|
14
|
+
* What is done to an object:
|
|
15
|
+
* - `view`: open it or see it in a list;
|
|
16
|
+
* - `edit`: change it;
|
|
17
|
+
* - `share`: change who sees it;
|
|
18
|
+
* - `delete`: mark it deleted;
|
|
19
|
+
* - `transfer`: pass ownership on;
|
|
20
|
+
* - `restore`: undo a delete within 30 days.
|
|
21
|
+
*/
|
|
22
|
+
type ObjectAction = 'view' | 'edit' | 'share' | 'delete' | 'transfer' | 'restore';
|
|
23
|
+
/** The caller's access to one object, from the most to the least. */
|
|
24
|
+
type AccessLevel = 'override' | 'owner' | GrantLevel;
|
|
25
|
+
declare const OBJECT_VISIBILITIES: readonly ObjectVisibility[];
|
|
26
|
+
declare const GRANT_LEVELS: readonly GrantLevel[];
|
|
27
|
+
/** How long a deleted object can be restored. */
|
|
28
|
+
declare const OBJECT_RESTORE_DAYS = 30;
|
|
29
|
+
/** The most grants one object may have. */
|
|
30
|
+
declare const MAX_OBJECT_GRANTS = 200;
|
|
31
|
+
/** The code that acts on every object of the app's kinds. The SDK declares it by itself. */
|
|
32
|
+
declare function objectAdminCode(appName: string): string;
|
|
33
|
+
interface ObjectColumnsOptions {
|
|
34
|
+
/** Who sees a new object of the kind. Defaults to `private`. */
|
|
35
|
+
visibility?: ObjectVisibility;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The columns of a table whose rows are objects with an owner: spread them into
|
|
39
|
+
* `tenantTable`. The owner fills itself from the request, as `tenant_id` does. A row is
|
|
40
|
+
* deleted by marking it (`deleted_at`), and can be restored for 30 days.
|
|
41
|
+
*
|
|
42
|
+
* ```ts
|
|
43
|
+
* export const reports = tenantTable(schema, 'reports', {
|
|
44
|
+
* name: text('name').notNull(),
|
|
45
|
+
* ...objectColumns({ visibility: 'private' }),
|
|
46
|
+
* })
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
declare function objectColumns(options?: ObjectColumnsOptions): {
|
|
50
|
+
ownerId: drizzle_orm.HasDefault<drizzle_orm_pg_core.PgTextBuilderInitial<"owner_id", [string, ...string[]]>>;
|
|
51
|
+
visibility: drizzle_orm.HasDefault<drizzle_orm.NotNull<drizzle_orm_pg_core.PgTextBuilderInitial<"visibility", ["private", "tenant"]>>>;
|
|
52
|
+
deletedAt: drizzle_orm_pg_core.PgTimestampBuilderInitial<"deleted_at">;
|
|
53
|
+
deletedBy: drizzle_orm_pg_core.PgTextBuilderInitial<"deleted_by", [string, ...string[]]>;
|
|
54
|
+
};
|
|
55
|
+
declare function grantColumns(): {
|
|
56
|
+
objectType: drizzle_orm.NotNull<drizzle_orm_pg_core.PgTextBuilderInitial<"object_type", [string, ...string[]]>>;
|
|
57
|
+
objectId: drizzle_orm.NotNull<drizzle_orm_pg_core.PgUUIDBuilderInitial<"object_id">>;
|
|
58
|
+
principalType: drizzle_orm.NotNull<drizzle_orm_pg_core.PgTextBuilderInitial<"principal_type", ["user", "role"]>>;
|
|
59
|
+
principalId: drizzle_orm.NotNull<drizzle_orm_pg_core.PgTextBuilderInitial<"principal_id", [string, ...string[]]>>;
|
|
60
|
+
level: drizzle_orm.NotNull<drizzle_orm_pg_core.PgTextBuilderInitial<"level", ["viewer", "editor", "manager"]>>;
|
|
61
|
+
grantedBy: drizzle_orm_pg_core.PgTextBuilderInitial<"granted_by", [string, ...string[]]>;
|
|
62
|
+
};
|
|
63
|
+
/** The table of grants: who besides the owner may see, change or share one object. */
|
|
64
|
+
type ObjectGrantsTable = TenantTable<'object_grants', ReturnType<typeof grantColumns>>;
|
|
65
|
+
/** The name of the grants table in the app's schema. */
|
|
66
|
+
declare const OBJECT_GRANTS_TABLE = "object_grants";
|
|
67
|
+
/**
|
|
68
|
+
* The grants of every object kind of the app. Export it from `service/schema.ts`, so that
|
|
69
|
+
* `drizzle-kit generate` makes it, when the app has object kinds:
|
|
70
|
+
*
|
|
71
|
+
* ```ts
|
|
72
|
+
* export const objectGrants = objectGrantsTable(schema)
|
|
73
|
+
* ```
|
|
74
|
+
*/
|
|
75
|
+
declare function objectGrantsTable(schema: PgSchema<string>): ObjectGrantsTable;
|
|
76
|
+
/** A table with `objectColumns`. */
|
|
77
|
+
type ObjectTable = PgTable & {
|
|
78
|
+
id: AnyPgColumn;
|
|
79
|
+
ownerId: AnyPgColumn;
|
|
80
|
+
visibility: AnyPgColumn;
|
|
81
|
+
deletedAt: AnyPgColumn;
|
|
82
|
+
deletedBy: AnyPgColumn;
|
|
83
|
+
};
|
|
84
|
+
/** One kind of object of the app. */
|
|
85
|
+
interface ObjectKind {
|
|
86
|
+
table: ObjectTable;
|
|
87
|
+
/**
|
|
88
|
+
* The code a user needs to see and change who an object of this kind is shared with
|
|
89
|
+
* through the platform's routes, which the Share dialog calls. Usually the kind's write
|
|
90
|
+
* code, such as `bi:report:write`. It must be in the app's catalog.
|
|
91
|
+
*/
|
|
92
|
+
permission: string;
|
|
93
|
+
/** A manager may delete as well as the owner, as for a task space. Defaults to false. */
|
|
94
|
+
managersDelete?: boolean;
|
|
95
|
+
}
|
|
96
|
+
declare const KINDS: unique symbol;
|
|
97
|
+
/** What `defineObjects` returns. Pass it to `createApp({ objects })`. */
|
|
98
|
+
interface ObjectKinds {
|
|
99
|
+
readonly [KINDS]: true;
|
|
100
|
+
readonly kinds: Readonly<Record<string, ObjectKind>>;
|
|
101
|
+
}
|
|
102
|
+
/** An object kind's name: lower case letters, digits and dashes. */
|
|
103
|
+
declare const OBJECT_TYPE_PATTERN: RegExp;
|
|
104
|
+
/**
|
|
105
|
+
* Declare the app's object kinds: each name with its table and the code that shares it.
|
|
106
|
+
*
|
|
107
|
+
* ```ts
|
|
108
|
+
* export const objects = defineObjects({
|
|
109
|
+
* report: { table: reports, permission: 'bi:report:write' },
|
|
110
|
+
* })
|
|
111
|
+
* ```
|
|
112
|
+
*/
|
|
113
|
+
declare function defineObjects(kinds: Record<string, ObjectKind>): ObjectKinds;
|
|
114
|
+
/** True for what `defineObjects` returned. */
|
|
115
|
+
declare function isObjectKinds(value: unknown): value is ObjectKinds;
|
|
116
|
+
/** What `createApp` puts on every request of an app with object kinds. */
|
|
117
|
+
interface ObjectRegistry {
|
|
118
|
+
appName: string;
|
|
119
|
+
/** The app id, which is the schema of the grants table. */
|
|
120
|
+
schema: string;
|
|
121
|
+
kinds: Readonly<Record<string, ObjectKind>>;
|
|
122
|
+
}
|
|
123
|
+
/** True when the request's caller holds the app's override code. */
|
|
124
|
+
declare function isObjectAdmin(c: Context): boolean;
|
|
125
|
+
/**
|
|
126
|
+
* The filter of a list query: the objects of a kind the caller may see, not deleted.
|
|
127
|
+
*
|
|
128
|
+
* ```ts
|
|
129
|
+
* const rows = await db(c).select().from(reports).where(and(visibleTo(c, 'report'), ...))
|
|
130
|
+
* ```
|
|
131
|
+
*
|
|
132
|
+
* The app's override code sees every object of the tenant.
|
|
133
|
+
*/
|
|
134
|
+
declare function visibleTo(c: Context, type: string): SQL;
|
|
135
|
+
/**
|
|
136
|
+
* The filter of the deleted objects of a kind that the caller may restore: those deleted
|
|
137
|
+
* in the last 30 days, for the app's override code only. Nobody else sees them.
|
|
138
|
+
*/
|
|
139
|
+
declare function restorableBy(c: Context, type: string): SQL;
|
|
140
|
+
/** The caller's access to one object, and what the object says of itself. */
|
|
141
|
+
interface ObjectAccess {
|
|
142
|
+
level: AccessLevel;
|
|
143
|
+
ownerId: string | null;
|
|
144
|
+
visibility: ObjectVisibility;
|
|
145
|
+
/** Set for an object that is deleted. Only the override reaches one, to restore it. */
|
|
146
|
+
deletedAt: Date | null;
|
|
147
|
+
}
|
|
148
|
+
/** True when `level` allows `action` on an object of `kind`. */
|
|
149
|
+
declare function allows(level: AccessLevel, action: ObjectAction, kind?: Pick<ObjectKind, 'managersDelete'>): boolean;
|
|
150
|
+
/**
|
|
151
|
+
* The caller's access to one object, or undefined when the caller may not see it, it does
|
|
152
|
+
* not exist, or it is deleted (except for the override). Use it to tell the screen what
|
|
153
|
+
* the caller may do.
|
|
154
|
+
*/
|
|
155
|
+
declare function accessTo(c: Context, type: string, id: string): Promise<ObjectAccess | undefined>;
|
|
156
|
+
/**
|
|
157
|
+
* Refuses an action on one object the caller may not take. An object the caller may not
|
|
158
|
+
* see is 404, as one that does not exist, so its existence is not told. One the caller
|
|
159
|
+
* sees but may not act on is 403 `object_access_denied`. A deleted object is 404 to every
|
|
160
|
+
* action but `restore`. The kind's permission is checked apart, with `requirePermission`.
|
|
161
|
+
*
|
|
162
|
+
* ```ts
|
|
163
|
+
* app.api.put('/reports/:id', requirePermission('bi:report:write'), async (c) => {
|
|
164
|
+
* await assertCan(c, 'report', c.req.param('id'), 'edit')
|
|
165
|
+
* ...
|
|
166
|
+
* })
|
|
167
|
+
* ```
|
|
168
|
+
*/
|
|
169
|
+
declare function assertCan(c: Context, type: string, id: string, action: ObjectAction): Promise<ObjectAccess>;
|
|
170
|
+
/**
|
|
171
|
+
* Deletes one object by marking it, after `assertCan(..., 'delete')`. The app's override
|
|
172
|
+
* can restore it for 30 days. Refuse first, in the route, while something uses it.
|
|
173
|
+
*/
|
|
174
|
+
declare function deleteObject(c: Context, type: string, id: string): Promise<void>;
|
|
175
|
+
/** Restores an object deleted in the last 30 days. The app's override code only. */
|
|
176
|
+
declare function restoreObject(c: Context, type: string, id: string): Promise<void>;
|
|
177
|
+
/**
|
|
178
|
+
* Passes ownership of one object on, after `assertCan(..., 'transfer')`: its owner or the
|
|
179
|
+
* app's override. The one who gives it up keeps no access unless a grant gives it.
|
|
180
|
+
*/
|
|
181
|
+
declare function transferObject(c: Context, type: string, id: string, ownerId: string): Promise<void>;
|
|
182
|
+
/** One grant: a user or a role, and what it may do. */
|
|
183
|
+
interface ObjectGrant {
|
|
184
|
+
principalType: PrincipalType;
|
|
185
|
+
principalId: string;
|
|
186
|
+
level: GrantLevel;
|
|
187
|
+
}
|
|
188
|
+
/** Who sees an object: its owner, its visibility and its grants. */
|
|
189
|
+
interface ObjectSharing {
|
|
190
|
+
ownerId: string | null;
|
|
191
|
+
visibility: ObjectVisibility;
|
|
192
|
+
grants: ObjectGrant[];
|
|
193
|
+
}
|
|
194
|
+
/** The sharing of one object, for anyone who may see it. */
|
|
195
|
+
declare function getSharing(c: Context, type: string, id: string): Promise<ObjectSharing & {
|
|
196
|
+
level: AccessLevel;
|
|
197
|
+
}>;
|
|
198
|
+
/** Reads a list of grants from a request body. Throws 422 with the field `grants`. */
|
|
199
|
+
declare function parseGrants(value: unknown): ObjectGrant[];
|
|
200
|
+
/**
|
|
201
|
+
* Replaces who an object is shared with: its visibility and all its grants, after
|
|
202
|
+
* `assertCan(..., 'share')`. A change is an audit event with what it was and what it is.
|
|
203
|
+
*/
|
|
204
|
+
declare function setSharing(c: Context, type: string, id: string, sharing: {
|
|
205
|
+
visibility: ObjectVisibility;
|
|
206
|
+
grants: readonly ObjectGrant[];
|
|
207
|
+
}): Promise<void>;
|
|
208
|
+
declare module 'hono' {
|
|
209
|
+
interface ContextVariableMap {
|
|
210
|
+
/** The app's object kinds, set by `createApp({ objects })`. */
|
|
211
|
+
platformObjects: ObjectRegistry;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Throws when the app has object kinds and its schema has no grants table, with what to
|
|
216
|
+
* add. `createApp` calls it once the migrations ran.
|
|
217
|
+
*/
|
|
218
|
+
declare function assertObjectTables(database: {
|
|
219
|
+
schema: string;
|
|
220
|
+
drizzle: {
|
|
221
|
+
execute(query: SQL): Promise<unknown>;
|
|
222
|
+
};
|
|
223
|
+
}): Promise<void>;
|
|
224
|
+
|
|
225
|
+
export { type AccessLevel, GRANT_LEVELS, type GrantLevel, MAX_OBJECT_GRANTS, OBJECT_GRANTS_TABLE, OBJECT_RESTORE_DAYS, OBJECT_TYPE_PATTERN, OBJECT_VISIBILITIES, type ObjectAccess, type ObjectAction, type ObjectColumnsOptions, type ObjectGrant, type ObjectGrantsTable, type ObjectKind, type ObjectKinds, type ObjectRegistry, type ObjectSharing, type ObjectTable, type ObjectVisibility, type PrincipalType, accessTo, allows, assertCan, assertObjectTables, defineObjects, deleteObject, getSharing, isObjectAdmin, isObjectKinds, objectAdminCode, objectColumns, objectGrantsTable, parseGrants, restorableBy, restoreObject, setSharing, transferObject, visibleTo };
|
package/dist/objects.js
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
import {
|
|
2
|
+
db,
|
|
3
|
+
tenantTable
|
|
4
|
+
} from "./chunk-XWJAL6GX.js";
|
|
5
|
+
import {
|
|
6
|
+
audit
|
|
7
|
+
} from "./chunk-VJRJ53T2.js";
|
|
8
|
+
import {
|
|
9
|
+
getUser,
|
|
10
|
+
hasPermissions
|
|
11
|
+
} from "./chunk-7FPH47F6.js";
|
|
12
|
+
import {
|
|
13
|
+
AppError,
|
|
14
|
+
ForbiddenError,
|
|
15
|
+
NotFoundError,
|
|
16
|
+
ValidationError,
|
|
17
|
+
isUuid
|
|
18
|
+
} from "./chunk-OBKMOVBA.js";
|
|
19
|
+
import "./chunk-3X4RSAM6.js";
|
|
20
|
+
import "./chunk-ERGI2X5S.js";
|
|
21
|
+
|
|
22
|
+
// src/objects.ts
|
|
23
|
+
import { and, eq, gt, inArray, isNotNull, isNull, or, sql } from "drizzle-orm";
|
|
24
|
+
import {
|
|
25
|
+
index,
|
|
26
|
+
pgSchema,
|
|
27
|
+
text,
|
|
28
|
+
timestamp,
|
|
29
|
+
uniqueIndex,
|
|
30
|
+
uuid
|
|
31
|
+
} from "drizzle-orm/pg-core";
|
|
32
|
+
var OBJECT_VISIBILITIES = ["private", "tenant"];
|
|
33
|
+
var GRANT_LEVELS = ["viewer", "editor", "manager"];
|
|
34
|
+
var OBJECT_RESTORE_DAYS = 30;
|
|
35
|
+
var MAX_OBJECT_GRANTS = 200;
|
|
36
|
+
function objectAdminCode(appName) {
|
|
37
|
+
return `${appName}:object:admin`;
|
|
38
|
+
}
|
|
39
|
+
function objectColumns(options = {}) {
|
|
40
|
+
return {
|
|
41
|
+
ownerId: text("owner_id").default(sql`nullif(current_setting('app.user_id', true), '')`),
|
|
42
|
+
visibility: text("visibility", { enum: ["private", "tenant"] }).notNull().default(options.visibility ?? "private"),
|
|
43
|
+
deletedAt: timestamp("deleted_at", { withTimezone: true }),
|
|
44
|
+
deletedBy: text("deleted_by")
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function grantColumns() {
|
|
48
|
+
return {
|
|
49
|
+
objectType: text("object_type").notNull(),
|
|
50
|
+
objectId: uuid("object_id").notNull(),
|
|
51
|
+
principalType: text("principal_type", { enum: ["user", "role"] }).notNull(),
|
|
52
|
+
principalId: text("principal_id").notNull(),
|
|
53
|
+
level: text("level", { enum: ["viewer", "editor", "manager"] }).notNull(),
|
|
54
|
+
grantedBy: text("granted_by")
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
var OBJECT_GRANTS_TABLE = "object_grants";
|
|
58
|
+
function objectGrantsTable(schema) {
|
|
59
|
+
return tenantTable(schema, OBJECT_GRANTS_TABLE, grantColumns(), (table) => [
|
|
60
|
+
uniqueIndex("object_grants_principal_key").on(
|
|
61
|
+
table.tenantId,
|
|
62
|
+
table.objectType,
|
|
63
|
+
table.objectId,
|
|
64
|
+
table.principalType,
|
|
65
|
+
table.principalId
|
|
66
|
+
),
|
|
67
|
+
index("object_grants_holder_idx").on(table.tenantId, table.principalType, table.principalId)
|
|
68
|
+
]);
|
|
69
|
+
}
|
|
70
|
+
var grantTables = /* @__PURE__ */ new Map();
|
|
71
|
+
function grantsOf(schemaName) {
|
|
72
|
+
let table = grantTables.get(schemaName);
|
|
73
|
+
if (!table) {
|
|
74
|
+
table = objectGrantsTable(pgSchema(schemaName));
|
|
75
|
+
grantTables.set(schemaName, table);
|
|
76
|
+
}
|
|
77
|
+
return table;
|
|
78
|
+
}
|
|
79
|
+
var KINDS = /* @__PURE__ */ Symbol.for("zjazj.platform.objectKinds");
|
|
80
|
+
var OBJECT_TYPE_PATTERN = /^[a-z][a-z0-9-]*$/;
|
|
81
|
+
function defineObjects(kinds) {
|
|
82
|
+
for (const [type, kind] of Object.entries(kinds)) {
|
|
83
|
+
if (!OBJECT_TYPE_PATTERN.test(type)) {
|
|
84
|
+
throw new Error(`defineObjects: ${type} is not a kind name such as report or task-space`);
|
|
85
|
+
}
|
|
86
|
+
for (const column of ["id", "ownerId", "visibility", "deletedAt", "deletedBy"]) {
|
|
87
|
+
if (!kind.table?.[column]) {
|
|
88
|
+
throw new Error(
|
|
89
|
+
`defineObjects: the table of ${type} has no ${column}. Spread objectColumns() into it.`
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (typeof kind.permission !== "string" || kind.permission === "") {
|
|
94
|
+
throw new Error(`defineObjects: ${type} needs the permission that shares it`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return { [KINDS]: true, kinds: { ...kinds } };
|
|
98
|
+
}
|
|
99
|
+
function isObjectKinds(value) {
|
|
100
|
+
return typeof value === "object" && value !== null && value[KINDS] === true;
|
|
101
|
+
}
|
|
102
|
+
function resolve(c, type) {
|
|
103
|
+
const registry = c.get("platformObjects");
|
|
104
|
+
if (!registry) {
|
|
105
|
+
throw new AppError("This app declares no object kinds: pass `objects` to createApp", {
|
|
106
|
+
code: "objects_not_configured",
|
|
107
|
+
status: 500
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
const kind = Object.hasOwn(registry.kinds, type) ? registry.kinds[type] : void 0;
|
|
111
|
+
if (!kind) {
|
|
112
|
+
throw new AppError(`Unknown object kind: ${type}`, { code: "unknown_object_kind", status: 500 });
|
|
113
|
+
}
|
|
114
|
+
const user = getUser(c);
|
|
115
|
+
return {
|
|
116
|
+
type,
|
|
117
|
+
kind,
|
|
118
|
+
table: kind.table,
|
|
119
|
+
grants: grantsOf(registry.schema),
|
|
120
|
+
user,
|
|
121
|
+
override: hasPermissions(user.permissions, [objectAdminCode(registry.appName)])
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
function isObjectAdmin(c) {
|
|
125
|
+
const registry = c.get("platformObjects");
|
|
126
|
+
return registry ? hasPermissions(getUser(c).permissions, [objectAdminCode(registry.appName)]) : false;
|
|
127
|
+
}
|
|
128
|
+
function grantsOfCaller(grants, user) {
|
|
129
|
+
const asUser = and(eq(grants.principalType, "user"), eq(grants.principalId, user.id));
|
|
130
|
+
if (user.roles.length === 0) return asUser;
|
|
131
|
+
return or(
|
|
132
|
+
asUser,
|
|
133
|
+
and(eq(grants.principalType, "role"), inArray(grants.principalId, user.roles))
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
function visibleTo(c, type) {
|
|
137
|
+
const { table, grants, user, override } = resolve(c, type);
|
|
138
|
+
const live = isNull(table.deletedAt);
|
|
139
|
+
if (override) return live;
|
|
140
|
+
const granted = sql`exists (select 1 from ${grants} where ${and(
|
|
141
|
+
eq(grants.objectType, type),
|
|
142
|
+
eq(grants.objectId, table.id),
|
|
143
|
+
grantsOfCaller(grants, user)
|
|
144
|
+
)})`;
|
|
145
|
+
return and(live, or(eq(table.visibility, "tenant"), eq(table.ownerId, user.id), granted));
|
|
146
|
+
}
|
|
147
|
+
function restorableBy(c, type) {
|
|
148
|
+
const { table, override } = resolve(c, type);
|
|
149
|
+
if (!override) return sql`false`;
|
|
150
|
+
const since = new Date(Date.now() - OBJECT_RESTORE_DAYS * 24 * 3600 * 1e3);
|
|
151
|
+
return and(isNotNull(table.deletedAt), gt(table.deletedAt, since));
|
|
152
|
+
}
|
|
153
|
+
var RANK = {
|
|
154
|
+
viewer: 1,
|
|
155
|
+
editor: 2,
|
|
156
|
+
manager: 3,
|
|
157
|
+
owner: 4,
|
|
158
|
+
override: 5
|
|
159
|
+
};
|
|
160
|
+
async function readAccess(c, resolved, id) {
|
|
161
|
+
if (!isUuid(id)) return void 0;
|
|
162
|
+
const { table, grants, user, override, type } = resolved;
|
|
163
|
+
const [row] = await db(c).select({ ownerId: table.ownerId, visibility: table.visibility, deletedAt: table.deletedAt }).from(table).where(eq(table.id, id)).limit(1);
|
|
164
|
+
if (!row) return void 0;
|
|
165
|
+
const object = {
|
|
166
|
+
ownerId: row.ownerId,
|
|
167
|
+
visibility: row.visibility === "tenant" ? "tenant" : "private",
|
|
168
|
+
deletedAt: row.deletedAt
|
|
169
|
+
};
|
|
170
|
+
let level;
|
|
171
|
+
if (override) level = "override";
|
|
172
|
+
else if (row.deletedAt) return void 0;
|
|
173
|
+
else if (row.ownerId !== null && row.ownerId === user.id) level = "owner";
|
|
174
|
+
else {
|
|
175
|
+
const held = await db(c).select({ level: grants.level }).from(grants).where(
|
|
176
|
+
and(eq(grants.objectType, type), eq(grants.objectId, id), grantsOfCaller(grants, user))
|
|
177
|
+
);
|
|
178
|
+
for (const grant of held) {
|
|
179
|
+
if (!level || RANK[grant.level] > RANK[level]) level = grant.level;
|
|
180
|
+
}
|
|
181
|
+
if (!level && object.visibility === "tenant") level = "viewer";
|
|
182
|
+
}
|
|
183
|
+
return level ? { level, ...object } : void 0;
|
|
184
|
+
}
|
|
185
|
+
function allows(level, action, kind) {
|
|
186
|
+
switch (action) {
|
|
187
|
+
case "view":
|
|
188
|
+
return true;
|
|
189
|
+
case "edit":
|
|
190
|
+
return RANK[level] >= RANK.editor;
|
|
191
|
+
case "share":
|
|
192
|
+
return RANK[level] >= RANK.manager;
|
|
193
|
+
case "delete":
|
|
194
|
+
return RANK[level] >= (kind?.managersDelete ? RANK.manager : RANK.owner);
|
|
195
|
+
case "transfer":
|
|
196
|
+
return RANK[level] >= RANK.owner;
|
|
197
|
+
case "restore":
|
|
198
|
+
return level === "override";
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
async function accessTo(c, type, id) {
|
|
202
|
+
return readAccess(c, resolve(c, type), id);
|
|
203
|
+
}
|
|
204
|
+
async function assertCan(c, type, id, action) {
|
|
205
|
+
const resolved = resolve(c, type);
|
|
206
|
+
const access = await readAccess(c, resolved, id);
|
|
207
|
+
if (!access || access.deletedAt && action !== "restore") {
|
|
208
|
+
throw new NotFoundError(`No ${type} with this id`);
|
|
209
|
+
}
|
|
210
|
+
if (!allows(access.level, action, resolved.kind)) {
|
|
211
|
+
throw new ForbiddenError(`You may not ${action} this ${type}`, {
|
|
212
|
+
code: "object_access_denied"
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
if (action === "restore") {
|
|
216
|
+
if (!access.deletedAt) throw new NotFoundError(`No deleted ${type} with this id`);
|
|
217
|
+
if (access.deletedAt.getTime() < Date.now() - OBJECT_RESTORE_DAYS * 24 * 3600 * 1e3) {
|
|
218
|
+
throw new AppError(`This ${type} was deleted more than ${OBJECT_RESTORE_DAYS} days ago`, {
|
|
219
|
+
code: "restore_expired",
|
|
220
|
+
status: 409
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return access;
|
|
225
|
+
}
|
|
226
|
+
async function deleteObject(c, type, id) {
|
|
227
|
+
const resolved = resolve(c, type);
|
|
228
|
+
await assertCan(c, type, id, "delete");
|
|
229
|
+
const { table, user } = resolved;
|
|
230
|
+
await db(c).update(table).set({ deletedAt: /* @__PURE__ */ new Date(), deletedBy: user.id }).where(eq(table.id, id));
|
|
231
|
+
audit("object.delete", { target: { type, id } });
|
|
232
|
+
}
|
|
233
|
+
async function restoreObject(c, type, id) {
|
|
234
|
+
const resolved = resolve(c, type);
|
|
235
|
+
await assertCan(c, type, id, "restore");
|
|
236
|
+
const { table } = resolved;
|
|
237
|
+
await db(c).update(table).set({ deletedAt: null, deletedBy: null }).where(eq(table.id, id));
|
|
238
|
+
audit("object.restore", { target: { type, id } });
|
|
239
|
+
}
|
|
240
|
+
async function transferObject(c, type, id, ownerId) {
|
|
241
|
+
if (typeof ownerId !== "string" || ownerId === "" || ownerId.length > 200) {
|
|
242
|
+
throw new ValidationError("owner_id must be the id of a member", "owner_id");
|
|
243
|
+
}
|
|
244
|
+
const resolved = resolve(c, type);
|
|
245
|
+
const access = await assertCan(c, type, id, "transfer");
|
|
246
|
+
if (access.ownerId === ownerId) return;
|
|
247
|
+
await db(c).update(resolved.table).set({ ownerId }).where(eq(resolved.table.id, id));
|
|
248
|
+
const { grants } = resolved;
|
|
249
|
+
await db(c).delete(grants).where(
|
|
250
|
+
and(
|
|
251
|
+
eq(grants.objectType, type),
|
|
252
|
+
eq(grants.objectId, id),
|
|
253
|
+
eq(grants.principalType, "user"),
|
|
254
|
+
eq(grants.principalId, ownerId)
|
|
255
|
+
)
|
|
256
|
+
);
|
|
257
|
+
audit("object.owner", { target: { type, id }, from: access.ownerId, to: ownerId });
|
|
258
|
+
}
|
|
259
|
+
async function getSharing(c, type, id) {
|
|
260
|
+
const resolved = resolve(c, type);
|
|
261
|
+
const access = await assertCan(c, type, id, "view");
|
|
262
|
+
const { grants } = resolved;
|
|
263
|
+
const rows = await db(c).select({
|
|
264
|
+
principalType: grants.principalType,
|
|
265
|
+
principalId: grants.principalId,
|
|
266
|
+
level: grants.level
|
|
267
|
+
}).from(grants).where(and(eq(grants.objectType, type), eq(grants.objectId, id))).orderBy(grants.principalType, grants.principalId);
|
|
268
|
+
return {
|
|
269
|
+
ownerId: access.ownerId,
|
|
270
|
+
visibility: access.visibility,
|
|
271
|
+
grants: rows,
|
|
272
|
+
level: access.level
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
function parseGrants(value) {
|
|
276
|
+
if (!Array.isArray(value)) throw new ValidationError("grants must be a list", "grants");
|
|
277
|
+
if (value.length > MAX_OBJECT_GRANTS) {
|
|
278
|
+
throw new ValidationError(`An object takes at most ${MAX_OBJECT_GRANTS} grants`, "grants");
|
|
279
|
+
}
|
|
280
|
+
const seen = /* @__PURE__ */ new Set();
|
|
281
|
+
return value.map((item) => {
|
|
282
|
+
const fields = item && typeof item === "object" ? item : {};
|
|
283
|
+
const principalType = fields.principalType ?? fields.principal_type;
|
|
284
|
+
const principalId = fields.principalId ?? fields.principal_id;
|
|
285
|
+
const { level } = fields;
|
|
286
|
+
if (principalType !== "user" && principalType !== "role") {
|
|
287
|
+
throw new ValidationError("A grant is to a user or a role", "grants");
|
|
288
|
+
}
|
|
289
|
+
if (typeof principalId !== "string" || principalId === "" || principalId.length > 200) {
|
|
290
|
+
throw new ValidationError("A grant names the id of a user or the code of a role", "grants");
|
|
291
|
+
}
|
|
292
|
+
if (!GRANT_LEVELS.includes(level)) {
|
|
293
|
+
throw new ValidationError("A grant is viewer, editor or manager", "grants");
|
|
294
|
+
}
|
|
295
|
+
const key = `${principalType}:${principalId}`;
|
|
296
|
+
if (seen.has(key)) throw new ValidationError(`${principalId} is granted twice`, "grants");
|
|
297
|
+
seen.add(key);
|
|
298
|
+
return { principalType, principalId, level };
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
async function setSharing(c, type, id, sharing) {
|
|
302
|
+
if (!OBJECT_VISIBILITIES.includes(sharing.visibility)) {
|
|
303
|
+
throw new ValidationError("visibility is private or tenant", "visibility");
|
|
304
|
+
}
|
|
305
|
+
const grantsAfter = parseGrants(sharing.grants);
|
|
306
|
+
const before = await getSharing(c, type, id);
|
|
307
|
+
const resolved = resolve(c, type);
|
|
308
|
+
if (!allows(before.level, "share", resolved.kind)) {
|
|
309
|
+
throw new ForbiddenError(`You may not share this ${type}`, { code: "object_access_denied" });
|
|
310
|
+
}
|
|
311
|
+
const { table, grants, user } = resolved;
|
|
312
|
+
if (before.visibility !== sharing.visibility) {
|
|
313
|
+
await db(c).update(table).set({ visibility: sharing.visibility }).where(eq(table.id, id));
|
|
314
|
+
}
|
|
315
|
+
await db(c).delete(grants).where(and(eq(grants.objectType, type), eq(grants.objectId, id)));
|
|
316
|
+
if (grantsAfter.length > 0) {
|
|
317
|
+
await db(c).insert(grants).values(
|
|
318
|
+
grantsAfter.map((grant) => ({
|
|
319
|
+
objectType: type,
|
|
320
|
+
objectId: id,
|
|
321
|
+
principalType: grant.principalType,
|
|
322
|
+
principalId: grant.principalId,
|
|
323
|
+
level: grant.level,
|
|
324
|
+
grantedBy: user.id
|
|
325
|
+
}))
|
|
326
|
+
);
|
|
327
|
+
}
|
|
328
|
+
const brief = (list) => list.map((grant) => `${grant.principalType}:${grant.principalId}:${grant.level}`);
|
|
329
|
+
audit("object.share", {
|
|
330
|
+
target: { type, id },
|
|
331
|
+
before: { visibility: before.visibility, grants: brief(before.grants) },
|
|
332
|
+
after: { visibility: sharing.visibility, grants: brief(grantsAfter) }
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
async function assertObjectTables(database) {
|
|
336
|
+
const result = await database.drizzle.execute(
|
|
337
|
+
sql`select 1 from information_schema.tables where table_schema = ${database.schema} and table_name = ${OBJECT_GRANTS_TABLE}`
|
|
338
|
+
);
|
|
339
|
+
const rows = Array.isArray(result) ? result : result.rows ?? [];
|
|
340
|
+
if (rows.length === 0) {
|
|
341
|
+
throw new Error(
|
|
342
|
+
`The app has object kinds and no ${OBJECT_GRANTS_TABLE} table. Add \`export const objectGrants = objectGrantsTable(schema)\` to service/schema.ts and run \`pnpm db:generate\`.`
|
|
343
|
+
);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
export {
|
|
347
|
+
GRANT_LEVELS,
|
|
348
|
+
MAX_OBJECT_GRANTS,
|
|
349
|
+
OBJECT_GRANTS_TABLE,
|
|
350
|
+
OBJECT_RESTORE_DAYS,
|
|
351
|
+
OBJECT_TYPE_PATTERN,
|
|
352
|
+
OBJECT_VISIBILITIES,
|
|
353
|
+
accessTo,
|
|
354
|
+
allows,
|
|
355
|
+
assertCan,
|
|
356
|
+
assertObjectTables,
|
|
357
|
+
defineObjects,
|
|
358
|
+
deleteObject,
|
|
359
|
+
getSharing,
|
|
360
|
+
isObjectAdmin,
|
|
361
|
+
isObjectKinds,
|
|
362
|
+
objectAdminCode,
|
|
363
|
+
objectColumns,
|
|
364
|
+
objectGrantsTable,
|
|
365
|
+
parseGrants,
|
|
366
|
+
restorableBy,
|
|
367
|
+
restoreObject,
|
|
368
|
+
setSharing,
|
|
369
|
+
transferObject,
|
|
370
|
+
visibleTo
|
|
371
|
+
};
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { V as Verifier } from './
|
|
1
|
+
import { V as Verifier, f as ApiKeyVerification, K as KeyVerifier } from './api-keys-BY7RCE9v.js';
|
|
2
2
|
import 'hono';
|
|
3
3
|
import 'jose';
|
|
4
4
|
|
|
@@ -22,16 +22,32 @@ declare const TEST_TENANT_ID = "0190a000-0000-7000-8000-0000000000a1";
|
|
|
22
22
|
* network call.
|
|
23
23
|
*/
|
|
24
24
|
declare function createTestIssuer(issuer?: string): Promise<TestIssuer>;
|
|
25
|
+
/**
|
|
26
|
+
* A key verifier that knows only the keys given, for tests that run without the dev
|
|
27
|
+
* identity: pass it to `createApp({ keyVerifier })` and call with `Bearer <key>`. Each key
|
|
28
|
+
* starts with `pk_` and maps to the parts of the control plane's answer that differ from
|
|
29
|
+
* a user key of `TEST_TENANT_ID` with no roles and no permissions. Any other key is
|
|
30
|
+
* refused with 401 `invalid_key`. Nothing is kept, so each request asks again.
|
|
31
|
+
*
|
|
32
|
+
* ```ts
|
|
33
|
+
* const keyVerifier = createTestKeyVerifier({
|
|
34
|
+
* pk_test_reader: { permissions: ['stock:item:read'] },
|
|
35
|
+
* pk_test_tenant: { kind: 'tenant', roles: ['sync'], permissions: ['stock:item:write'] },
|
|
36
|
+
* })
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
declare function createTestKeyVerifier(keys: Record<string, Partial<ApiKeyVerification>>): KeyVerifier;
|
|
25
40
|
/** The MCP revision `mcpRequest` speaks. */
|
|
26
41
|
declare const MCP_PROTOCOL_VERSION = "2026-07-28";
|
|
27
42
|
/**
|
|
28
43
|
* One request to an app's MCP endpoint, as a client of MCP 2026-07-28 sends it: the
|
|
29
44
|
* method and its name in headers, the revision and the client's capabilities in `_meta`.
|
|
30
|
-
*
|
|
31
|
-
* `error`.
|
|
45
|
+
* `token` is sent as `Authorization: Bearer`: a token, a dev token or an API key, as an
|
|
46
|
+
* agent sends its key. Read the answer with `await response.json()`: `result` or `error`.
|
|
32
47
|
*/
|
|
33
48
|
declare function mcpRequest(url: string, method: string, params?: Record<string, unknown>, init?: {
|
|
49
|
+
token?: string;
|
|
34
50
|
headers?: Record<string, string>;
|
|
35
51
|
}): Request;
|
|
36
52
|
|
|
37
|
-
export { MCP_PROTOCOL_VERSION, type SignOptions, TEST_TENANT_ID, type TestIssuer, createTestIssuer, mcpRequest };
|
|
53
|
+
export { MCP_PROTOCOL_VERSION, type SignOptions, TEST_TENANT_ID, type TestIssuer, createTestIssuer, createTestKeyVerifier, mcpRequest };
|