monorise 1.15.0-dev.0 → 2.0.0-dev.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/base/index.d.ts +10 -2
- package/dist/base/index.js +3 -1
- package/dist/base/index.js.map +1 -1
- package/dist/cli/cli.js +4 -0
- package/dist/cli/cli.js.map +1 -1
- package/dist/cli/templates/files/api-keys.ts +12 -0
- package/dist/cli/templates/files/monorise.config.ts +2 -0
- package/dist/core/index.d.ts +8 -16
- package/dist/core/index.js +42 -82
- package/dist/core/index.js.map +1 -1
- package/dist/index.d.ts +1 -7
- package/dist/proxy/index.d.ts +5 -0
- package/dist/proxy/index.js +64 -13
- package/dist/proxy/index.js.map +1 -1
- package/dist/react/index.d.ts +2 -164
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/index.js +46 -188
- package/dist/react/index.js.map +1 -1
- package/dist/react/lib/api.d.ts +1 -2
- package/dist/react/lib/api.d.ts.map +1 -1
- package/dist/react/store/monorise.store.d.ts +0 -54
- package/dist/react/store/monorise.store.d.ts.map +1 -1
- package/dist/sst/components/monorise-core.d.ts.map +1 -1
- package/dist/sst/index.js +4 -1
- package/dist/sst/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/react/actions/auth.action.d.ts +0 -24
- package/dist/react/actions/auth.action.d.ts.map +0 -1
- package/dist/react/services/auth.service.d.ts +0 -21
- package/dist/react/services/auth.service.d.ts.map +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -54,6 +54,7 @@ export {
|
|
|
54
54
|
ApiKeySystemField,
|
|
55
55
|
CompiledApiKeyPolicy,
|
|
56
56
|
CreatedEntity,
|
|
57
|
+
DEFAULT_API_KEY_POLICY,
|
|
57
58
|
DraftEntity,
|
|
58
59
|
EntitySchemaMap,
|
|
59
60
|
FULL_API_KEY_POLICY,
|
|
@@ -76,7 +77,6 @@ export {
|
|
|
76
77
|
export {
|
|
77
78
|
store,
|
|
78
79
|
axios,
|
|
79
|
-
authService,
|
|
80
80
|
filestoreService,
|
|
81
81
|
coreService,
|
|
82
82
|
setConfig,
|
|
@@ -93,12 +93,6 @@ export {
|
|
|
93
93
|
useInterruptiveLoadStore,
|
|
94
94
|
useErrorStore,
|
|
95
95
|
useModalStore,
|
|
96
|
-
requestLogin,
|
|
97
|
-
useProfile,
|
|
98
|
-
getProfile,
|
|
99
|
-
useIsUnauthorized,
|
|
100
|
-
setIsUnauthorized,
|
|
101
|
-
logout,
|
|
102
96
|
listMoreEntities,
|
|
103
97
|
createEntity,
|
|
104
98
|
upsertEntity,
|
package/dist/proxy/index.d.ts
CHANGED
|
@@ -36,6 +36,11 @@ type EntityOperation<T extends string = string, A extends EntityAction = EntityA
|
|
|
36
36
|
entityId?: string;
|
|
37
37
|
/** The fields a `create` or `update` sets. */
|
|
38
38
|
payload?: A extends 'adjust' ? never : EntityPayload<T>;
|
|
39
|
+
/**
|
|
40
|
+
* The named condition an `update` or `adjust` must meet: the body's
|
|
41
|
+
* `$condition`, or a transaction entry's `condition`.
|
|
42
|
+
*/
|
|
43
|
+
condition?: string;
|
|
39
44
|
/** The amount an `adjust` adds to each numeric field. */
|
|
40
45
|
adjustments?: 'adjust' extends A ? EntityAdjustments<T> : never;
|
|
41
46
|
/**
|
package/dist/proxy/index.js
CHANGED
|
@@ -64,7 +64,7 @@ var relationshipFieldOperations = (entityConfig, entityType, entityId, payload,
|
|
|
64
64
|
}
|
|
65
65
|
return operations;
|
|
66
66
|
};
|
|
67
|
-
var entityWrite = (entityConfig, actions, entityType, entityId, payload, operationIndex) => {
|
|
67
|
+
var entityWrite = (entityConfig, actions, entityType, entityId, payload, operationIndex, condition) => {
|
|
68
68
|
const index = operationIndex === void 0 ? {} : { operationIndex };
|
|
69
69
|
return [
|
|
70
70
|
...actions.map(
|
|
@@ -74,6 +74,7 @@ var entityWrite = (entityConfig, actions, entityType, entityId, payload, operati
|
|
|
74
74
|
entityType,
|
|
75
75
|
...entityId === void 0 ? {} : { entityId },
|
|
76
76
|
...payload === void 0 ? {} : { payload },
|
|
77
|
+
...condition === void 0 ? {} : { condition },
|
|
77
78
|
...index
|
|
78
79
|
})
|
|
79
80
|
),
|
|
@@ -101,6 +102,7 @@ var transactionOperations = (entityConfig, body) => {
|
|
|
101
102
|
const { entityType } = entry;
|
|
102
103
|
const entityId = typeof entry.entityId === "string" ? entry.entityId : void 0;
|
|
103
104
|
const payload = isRecord(entry.payload) ? entry.payload : void 0;
|
|
105
|
+
const condition = typeof entry.condition === "string" ? entry.condition : void 0;
|
|
104
106
|
switch (entry.operation) {
|
|
105
107
|
case "createEntity":
|
|
106
108
|
case "updateEntity":
|
|
@@ -111,7 +113,8 @@ var transactionOperations = (entityConfig, body) => {
|
|
|
111
113
|
entityType,
|
|
112
114
|
entityId,
|
|
113
115
|
payload,
|
|
114
|
-
operationIndex
|
|
116
|
+
operationIndex,
|
|
117
|
+
condition
|
|
115
118
|
)
|
|
116
119
|
);
|
|
117
120
|
break;
|
|
@@ -122,6 +125,7 @@ var transactionOperations = (entityConfig, body) => {
|
|
|
122
125
|
entityType,
|
|
123
126
|
...entityId === void 0 ? {} : { entityId },
|
|
124
127
|
...isRecord(entry.adjustments) ? { adjustments: entry.adjustments } : {},
|
|
128
|
+
...condition === void 0 ? {} : { condition },
|
|
125
129
|
operationIndex
|
|
126
130
|
});
|
|
127
131
|
break;
|
|
@@ -229,24 +233,27 @@ var parseOperations = ({
|
|
|
229
233
|
});
|
|
230
234
|
}
|
|
231
235
|
if (rest.length === 3 && third === "adjust" && verb === "POST") {
|
|
232
|
-
const { $condition:
|
|
236
|
+
const { $condition: condition, ...adjustments } = payload ?? {};
|
|
233
237
|
return one({
|
|
234
238
|
kind: "entity",
|
|
235
239
|
action: "adjust",
|
|
236
240
|
entityType,
|
|
237
241
|
entityId: second,
|
|
238
|
-
...payload === void 0 ? {} : { adjustments }
|
|
242
|
+
...payload === void 0 ? {} : { adjustments },
|
|
243
|
+
...typeof condition === "string" ? { condition } : {}
|
|
239
244
|
});
|
|
240
245
|
}
|
|
241
246
|
if (rest.length === 2) {
|
|
242
|
-
const write = (actions, data = payload) => ({
|
|
247
|
+
const write = (actions, data = payload, condition) => ({
|
|
243
248
|
ok: true,
|
|
244
249
|
operations: entityWrite(
|
|
245
250
|
entityConfig,
|
|
246
251
|
actions,
|
|
247
252
|
entityType,
|
|
248
253
|
second,
|
|
249
|
-
data
|
|
254
|
+
data,
|
|
255
|
+
void 0,
|
|
256
|
+
condition
|
|
250
257
|
)
|
|
251
258
|
});
|
|
252
259
|
if (verb === "GET") {
|
|
@@ -260,8 +267,12 @@ var parseOperations = ({
|
|
|
260
267
|
if (verb === "PUT") return write(["create", "update"]);
|
|
261
268
|
if (verb === "PATCH") {
|
|
262
269
|
if (payload === void 0) return write(["update"]);
|
|
263
|
-
const { $condition:
|
|
264
|
-
return write(
|
|
270
|
+
const { $condition: condition, $where: _, ...data } = payload;
|
|
271
|
+
return write(
|
|
272
|
+
["update"],
|
|
273
|
+
data,
|
|
274
|
+
typeof condition === "string" ? condition : void 0
|
|
275
|
+
);
|
|
265
276
|
}
|
|
266
277
|
if (verb === "DELETE") {
|
|
267
278
|
return one({
|
|
@@ -422,6 +433,14 @@ var forbidden = (message, operation) => new Response(
|
|
|
422
433
|
}),
|
|
423
434
|
{ status: 403, headers: { "content-type": "application/json" } }
|
|
424
435
|
);
|
|
436
|
+
var proxyError = (message, operation) => new Response(
|
|
437
|
+
JSON.stringify({
|
|
438
|
+
code: "PROXY_ERROR",
|
|
439
|
+
message,
|
|
440
|
+
...operation && "operationIndex" in operation && operation.operationIndex !== void 0 ? { operationIndex: operation.operationIndex } : {}
|
|
441
|
+
}),
|
|
442
|
+
{ status: 500, headers: { "content-type": "application/json" } }
|
|
443
|
+
);
|
|
425
444
|
var checkOperations = async ({
|
|
426
445
|
operations,
|
|
427
446
|
rules,
|
|
@@ -442,7 +461,14 @@ var checkOperations = async ({
|
|
|
442
461
|
operation
|
|
443
462
|
);
|
|
444
463
|
}
|
|
445
|
-
|
|
464
|
+
let result;
|
|
465
|
+
try {
|
|
466
|
+
result = await found.rule(found.operation, context);
|
|
467
|
+
} catch (error) {
|
|
468
|
+
const what = `The rule for ${describeOperation(operation)}`;
|
|
469
|
+
console.error(`[monorise/proxy] ${what} threw`, error);
|
|
470
|
+
return proxyError(`${what} threw`, operation);
|
|
471
|
+
}
|
|
446
472
|
if (result instanceof Response) return result;
|
|
447
473
|
if (result !== true) {
|
|
448
474
|
return forbidden(
|
|
@@ -473,6 +499,21 @@ var json = (status, body) => new Response(JSON.stringify(body), {
|
|
|
473
499
|
status,
|
|
474
500
|
headers: { "content-type": "application/json" }
|
|
475
501
|
});
|
|
502
|
+
var NO_STORE = "private, no-store";
|
|
503
|
+
var withNoStore = (response) => {
|
|
504
|
+
if (response.headers.has("cache-control")) return response;
|
|
505
|
+
const headers = new Headers(response.headers);
|
|
506
|
+
headers.set("cache-control", NO_STORE);
|
|
507
|
+
return new Response(response.body, {
|
|
508
|
+
status: response.status,
|
|
509
|
+
statusText: response.statusText,
|
|
510
|
+
headers
|
|
511
|
+
});
|
|
512
|
+
};
|
|
513
|
+
var callbackThrew = (what, error) => {
|
|
514
|
+
console.error(`[monorise/proxy] ${what} threw`, error);
|
|
515
|
+
return proxyError(`${what} threw`);
|
|
516
|
+
};
|
|
476
517
|
var unauthorized = () => json(401, { code: "UNAUTHORIZED", message: "Unauthorized" });
|
|
477
518
|
var misconfigured = (message) => {
|
|
478
519
|
console.error(`[monorise/proxy] ${message}`);
|
|
@@ -502,13 +543,22 @@ var createProxyHandler = (options) => {
|
|
|
502
543
|
};
|
|
503
544
|
const prepare = async (request) => {
|
|
504
545
|
const body = request.method === "GET" || request.method === "HEAD" ? void 0 : await request.clone().arrayBuffer();
|
|
505
|
-
|
|
546
|
+
let authenticated;
|
|
547
|
+
try {
|
|
548
|
+
authenticated = options.authenticate ? await options.authenticate(request) : void 0;
|
|
549
|
+
} catch (error) {
|
|
550
|
+
return callbackThrew("authenticate", error);
|
|
551
|
+
}
|
|
506
552
|
if (authenticated instanceof Response) return authenticated;
|
|
507
553
|
const session = authenticated ?? void 0;
|
|
508
554
|
let caller;
|
|
509
555
|
let entry;
|
|
510
556
|
if (multiple) {
|
|
511
|
-
|
|
557
|
+
try {
|
|
558
|
+
caller = await options.caller?.({ session, request });
|
|
559
|
+
} catch (error) {
|
|
560
|
+
return callbackThrew("caller", error);
|
|
561
|
+
}
|
|
512
562
|
const callers = options.callers ?? {};
|
|
513
563
|
entry = caller !== void 0 && hasOwn3(callers, caller) ? callers[caller] : void 0;
|
|
514
564
|
} else if (!options.authenticate || session !== void 0) {
|
|
@@ -588,12 +638,13 @@ var createProxyHandler = (options) => {
|
|
|
588
638
|
const checkRequest = async (request) => {
|
|
589
639
|
const prepared = await prepare(request);
|
|
590
640
|
if (prepared instanceof Response) {
|
|
591
|
-
return { allowed: false, response: prepared };
|
|
641
|
+
return { allowed: false, response: withNoStore(prepared) };
|
|
592
642
|
}
|
|
593
643
|
const { caller, session, operations } = prepared;
|
|
594
644
|
return { allowed: true, caller, session, operations };
|
|
595
645
|
};
|
|
596
|
-
const handle = async (request) =>
|
|
646
|
+
const handle = async (request) => withNoStore(await forward(request));
|
|
647
|
+
const forward = async (request) => {
|
|
597
648
|
const prepared = await prepare(request);
|
|
598
649
|
if (prepared instanceof Response) return prepared;
|
|
599
650
|
const headers = new Headers();
|
package/dist/proxy/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../proxy/operations.ts","../proxy/rules.ts","../proxy/handler.ts","../index.ts"],"sourcesContent":["/**\n * A request to Monorise Core, described as the operations rules are written\n * against: one per thing it reads or writes. Rules on operations rather than\n * URLs can't be bypassed by a different request shape: a transaction's\n * `deleteEntity` and a `DELETE /entity/...` are the same operation.\n */\n\nimport type { ApiKeyMutualDataFields, EntitySchemaMap } from '@monorise/base';\n\n/**\n * `adjust` adds an amount to numeric fields (`POST /entity/:type/:id/adjust`).\n * API key policies count it as an update; rules keep it apart, so a rule\n * written for the values an update sets never approves an adjust.\n */\nexport type EntityAction =\n | 'get'\n | 'list'\n | 'create'\n | 'update'\n | 'adjust'\n | 'delete';\n\n/** Relationships have a single `read`: their listings are bounded by `byEntityId`. */\nexport type RelationshipAction = 'read' | 'create' | 'update' | 'delete';\n\n/**\n * An entity's fields, from the generated `EntitySchemaMap`. Rules see the\n * payload before Core validates it, so every field may be missing.\n */\nexport type EntityPayload<T extends string = string> = string extends T\n ? Record<string, unknown>\n : T extends keyof EntitySchemaMap\n ? Partial<EntitySchemaMap[T]>\n : Record<string, unknown>;\n\n/** An entity's numeric fields: what an `adjust` adds amounts to. */\nexport type EntityAdjustments<T extends string = string> = string extends T\n ? Record<string, number>\n : T extends keyof EntitySchemaMap\n ? {\n [K in keyof EntitySchemaMap[T] as NonNullable<\n EntitySchemaMap[T][K]\n > extends number\n ? K\n : never]?: number;\n }\n : Record<string, number>;\n\ntype MutualDataField<\n By extends string,\n To extends string,\n> = By extends keyof ApiKeyMutualDataFields\n ? To extends keyof ApiKeyMutualDataFields[By]\n ? Extract<ApiKeyMutualDataFields[By][To], string>\n : string\n : string;\n\n/** A relationship's `mutualData`, with the field names the generated config declares. */\nexport type MutualDataPayload<\n By extends string = string,\n To extends string = string,\n> = { [K in MutualDataField<By, To>]?: unknown };\n\nexport type EntityOperation<\n T extends string = string,\n A extends EntityAction = EntityAction,\n> = {\n kind: 'entity';\n action: A;\n entityType: T;\n entityId?: string;\n /** The fields a `create` or `update` sets. */\n payload?: A extends 'adjust' ? never : EntityPayload<T>;\n /** The amount an `adjust` adds to each numeric field. */\n adjustments?: 'adjust' extends A ? EntityAdjustments<T> : never;\n /**\n * The relationship this entity materializes, when creating the relationship\n * also creates it (`asEntity`).\n */\n asEntityOf?: Pick<\n RelationshipOperation,\n 'byEntityType' | 'byEntityId' | 'entityType' | 'entityId'\n >;\n /** The search term of a `list`, as Core receives it. */\n query?: string;\n /** The field and value of a get by unique field. */\n unique?: { field: string; value: string };\n /** The tag a `list` queries. */\n tag?: string;\n /** The tag group a tag listing reads, often what a rule scopes by. */\n group?: string;\n /** The range a `list` reads: Core's `start` and `end` query parameters. */\n start?: string;\n end?: string;\n /** Position in a transaction's `operations`. */\n operationIndex?: number;\n};\n\nexport type RelationshipOperation<\n By extends string = string,\n To extends string = string,\n A extends RelationshipAction = RelationshipAction,\n> = {\n kind: 'relationship';\n action: A;\n byEntityType: By;\n /**\n * Absent for a relationship field on an entity created without an ID, and\n * for every hop of a chain query after the first.\n */\n byEntityId?: string;\n entityType: To;\n /** Absent when listing, and for the relationships an update's new list removes. */\n entityId?: string;\n payload?: MutualDataPayload<By, To>;\n operationIndex?: number;\n};\n\nexport type RouteOperation = {\n kind: 'route';\n method: string;\n /** The path under `/core`, e.g. `/app/invite-casting`. */\n path: string;\n body?: unknown;\n /** Segments the matching route rule's `:param`s captured. */\n params?: Record<string, string>;\n};\n\nexport type ProxyOperation =\n | EntityOperation\n | RelationshipOperation\n | RouteOperation;\n\nexport type ParseResult =\n | { ok: true; operations: ProxyOperation[] }\n | { ok: false; status: 400 | 404; message: string };\n\n/**\n * The parts of the generated config the parser reads: which payload fields of\n * each entity are relationships, to which entity type, and which\n * relationships materialize an entity (`asEntity`).\n */\nexport type ProxyEntityConfig = Record<\n string,\n {\n mutual?: {\n mutualFields?: Record<\n string,\n { entityType: string; mutual?: { asEntity?: { name: string } } }\n >;\n };\n }\n>;\n\nconst hasOwn = (object: object, key: string) =>\n Object.prototype.hasOwnProperty.call(object, key);\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst notFound = (message: string): ParseResult => ({\n ok: false,\n status: 404,\n message,\n});\n\nconst invalid = (message: string): ParseResult => ({\n ok: false,\n status: 400,\n message,\n});\n\n// The entity type a relationship materializes (`asEntity`). Its mutual\n// config can sit on either side, as in Core.\nconst asEntityType = (\n entityConfig: ProxyEntityConfig | undefined,\n byEntityType: string,\n entityType: string,\n) => {\n const declared = (from: string, to: string) => {\n const fields =\n entityConfig && hasOwn(entityConfig, from)\n ? entityConfig[from].mutual?.mutualFields\n : undefined;\n return Object.values(fields ?? {}).find(\n (field) => field.entityType === to && field.mutual,\n )?.mutual?.asEntity?.name;\n };\n return (\n declared(byEntityType, entityType) ?? declared(entityType, byEntityType)\n );\n};\n\n/**\n * A relationship create, followed by a create of the entity it materializes\n * when it has an `asEntity`: the relationship's `mutualData` becomes that\n * entity's data. `requestedAsEntity` is one the request names, which wins\n * over the config's. Updates and deletes reach that entity by replication,\n * so only the create is described.\n */\nconst relationshipCreate = (\n entityConfig: ProxyEntityConfig | undefined,\n relationship: RelationshipOperation,\n requestedAsEntity?: string,\n): ProxyOperation[] => {\n const { byEntityType, byEntityId, entityType, entityId, payload } =\n relationship;\n const asEntity =\n requestedAsEntity || asEntityType(entityConfig, byEntityType, entityType);\n if (!asEntity) return [relationship];\n return [\n relationship,\n {\n kind: 'entity',\n action: 'create',\n entityType: asEntity,\n ...(payload === undefined ? {} : { payload }),\n asEntityOf: { byEntityType, byEntityId, entityType, entityId },\n ...(relationship.operationIndex === undefined\n ? {}\n : { operationIndex: relationship.operationIndex }),\n },\n ];\n};\n\n/**\n * A relationship field in an entity payload writes the relationship from that\n * entity to each listed ID. On create it only adds relationships. On update\n * the new list replaces the old one, so it can also remove relationships the\n * request doesn't name: one `delete` without an `entityId` stands for those.\n */\nconst relationshipFieldOperations = (\n entityConfig: ProxyEntityConfig | undefined,\n entityType: string,\n entityId: string | undefined,\n payload: Record<string, unknown> | undefined,\n write: 'create' | 'update',\n operationIndex: number | undefined,\n): ProxyOperation[] => {\n const config =\n entityConfig && hasOwn(entityConfig, entityType)\n ? entityConfig[entityType]\n : undefined;\n const fields = config?.mutual?.mutualFields;\n if (!payload || !fields) return [];\n\n const operations: ProxyOperation[] = [];\n for (const [field, value] of Object.entries(payload)) {\n if (!hasOwn(fields, field)) continue;\n const base = {\n kind: 'relationship' as const,\n byEntityType: entityType,\n byEntityId: entityId,\n entityType: fields[field].entityType,\n ...(operationIndex === undefined ? {} : { operationIndex }),\n };\n const ids = Array.isArray(value)\n ? value.filter((id): id is string => typeof id === 'string')\n : [];\n for (const id of ids) {\n operations.push(\n ...relationshipCreate(entityConfig, {\n ...base,\n action: 'create',\n entityId: id,\n }),\n );\n }\n if (write === 'update') operations.push({ ...base, action: 'delete' });\n }\n return operations;\n};\n\nconst entityWrite = (\n entityConfig: ProxyEntityConfig | undefined,\n actions: ('create' | 'update')[],\n entityType: string,\n entityId: string | undefined,\n payload: Record<string, unknown> | undefined,\n operationIndex?: number,\n): ProxyOperation[] => {\n const index = operationIndex === undefined ? {} : { operationIndex };\n return [\n ...actions.map(\n (action): EntityOperation => ({\n kind: 'entity',\n action,\n entityType,\n ...(entityId === undefined ? {} : { entityId }),\n ...(payload === undefined ? {} : { payload }),\n ...index,\n }),\n ),\n ...relationshipFieldOperations(\n entityConfig,\n entityType,\n entityId,\n payload,\n // An upsert can update, so its relationship fields count as an update's.\n actions.includes('update') ? 'update' : 'create',\n operationIndex,\n ),\n ];\n};\n\nconst transactionOperations = (\n entityConfig: ProxyEntityConfig | undefined,\n body: unknown,\n): ParseResult => {\n const entries = isRecord(body) ? body.operations : undefined;\n if (!Array.isArray(entries)) {\n return invalid('Request body must contain an \"operations\" array');\n }\n\n const operations: ProxyOperation[] = [];\n for (const [operationIndex, entry] of entries.entries()) {\n if (!isRecord(entry) || typeof entry.entityType !== 'string') {\n return invalid(`Operation ${operationIndex} has no entityType`);\n }\n const { entityType } = entry;\n const entityId =\n typeof entry.entityId === 'string' ? entry.entityId : undefined;\n const payload = isRecord(entry.payload) ? entry.payload : undefined;\n\n switch (entry.operation) {\n case 'createEntity':\n case 'updateEntity':\n operations.push(\n ...entityWrite(\n entityConfig,\n [entry.operation === 'createEntity' ? 'create' : 'update'],\n entityType,\n entityId,\n payload,\n operationIndex,\n ),\n );\n break;\n case 'adjustEntity':\n operations.push({\n kind: 'entity',\n action: 'adjust',\n entityType,\n ...(entityId === undefined ? {} : { entityId }),\n ...(isRecord(entry.adjustments)\n ? { adjustments: entry.adjustments as Record<string, number> }\n : {}),\n operationIndex,\n });\n break;\n case 'deleteEntity':\n operations.push({\n kind: 'entity',\n action: 'delete',\n entityType,\n ...(entityId === undefined ? {} : { entityId }),\n operationIndex,\n });\n break;\n case 'createMutual':\n case 'updateMutual':\n case 'deleteMutual': {\n if (\n typeof entry.byEntityType !== 'string' ||\n typeof entry.byEntityId !== 'string'\n ) {\n return invalid(\n `Operation ${operationIndex} needs byEntityType and byEntityId`,\n );\n }\n const relationship: RelationshipOperation = {\n kind: 'relationship',\n action:\n entry.operation === 'createMutual'\n ? 'create'\n : entry.operation === 'updateMutual'\n ? 'update'\n : 'delete',\n byEntityType: entry.byEntityType,\n byEntityId: entry.byEntityId,\n entityType,\n ...(entityId === undefined ? {} : { entityId }),\n ...(payload === undefined ? {} : { payload }),\n operationIndex,\n };\n // A transaction's createMutual uses only the config's asEntity.\n operations.push(\n ...(relationship.action === 'create'\n ? relationshipCreate(entityConfig, relationship)\n : [relationship]),\n );\n break;\n }\n default:\n return invalid(\n `Operation ${operationIndex} has an unknown operation '${String(entry.operation)}'`,\n );\n }\n }\n return { ok: true, operations };\n};\n\nconst decode = (segment: string) => {\n try {\n return decodeURIComponent(segment);\n } catch {\n return undefined;\n }\n};\n\n/**\n * Describes a request to Monorise Core as operations. `path` is the path\n * under `/core`, e.g. `/entity/order/123`. Paths Core doesn't serve, and the\n * WebSocket ticket route, which stays on its own route with a `full` key,\n * fail with 404 so no request reaches Core unchecked.\n */\nexport const parseOperations = ({\n method,\n path,\n searchParams,\n body,\n entityConfig,\n}: {\n method: string;\n path: string;\n searchParams: URLSearchParams;\n body: unknown;\n entityConfig?: ProxyEntityConfig;\n}): ParseResult => {\n // Core's router matches the raw path. A segment that decodes to contain\n // `/`, or an empty one, would be described as a different route than the\n // one Core runs, so neither is accepted.\n const decoded = (path === '/' ? [] : path.split('/').slice(1)).map(decode);\n if (decoded.some((segment) => !segment || segment.includes('/'))) {\n return invalid('Malformed path');\n }\n const [root, ...rest] = decoded as string[];\n const verb = method.toUpperCase();\n const payload = isRecord(body) ? body : undefined;\n const unknown = notFound(`Monorise Core has no route ${verb} ${path}`);\n const one = (operation: ProxyOperation): ParseResult => ({\n ok: true,\n operations: [operation],\n });\n // Present query parameters only, so operations stay comparable.\n const params = (...names: ('query' | 'group' | 'start' | 'end')[]) =>\n Object.fromEntries(\n names.flatMap((name) => {\n const value = searchParams.get(name);\n return value ? [[name, value]] : [];\n }),\n );\n\n if (root === 'entity') {\n const [entityType, second, third, fourth] = rest;\n if (rest.length === 1 && verb === 'GET') {\n return one({\n kind: 'entity',\n action: 'list',\n entityType,\n ...params('query', 'start', 'end'),\n });\n }\n if (rest.length === 1 && verb === 'POST') {\n const entityId =\n typeof payload?.entityId === 'string' ? payload.entityId : undefined;\n return {\n ok: true,\n operations: entityWrite(\n entityConfig,\n ['create'],\n entityType,\n entityId,\n payload,\n ),\n };\n }\n if (rest.length === 4 && second === 'unique' && verb === 'GET') {\n return one({\n kind: 'entity',\n action: 'get',\n entityType,\n unique: { field: third, value: fourth },\n });\n }\n if (rest.length === 3 && third === 'adjust' && verb === 'POST') {\n // As AdjustEntityController reads the body.\n const { $condition: _, ...adjustments } = payload ?? {};\n return one({\n kind: 'entity',\n action: 'adjust',\n entityType,\n entityId: second,\n ...(payload === undefined\n ? {}\n : { adjustments: adjustments as Record<string, number> }),\n });\n }\n if (rest.length === 2) {\n const write = (\n actions: ('create' | 'update')[],\n data = payload,\n ): ParseResult => ({\n ok: true,\n operations: entityWrite(\n entityConfig,\n actions,\n entityType,\n second,\n data,\n ),\n });\n if (verb === 'GET') {\n return one({\n kind: 'entity',\n action: 'get',\n entityType,\n entityId: second,\n });\n }\n if (verb === 'PUT') return write(['create', 'update']);\n if (verb === 'PATCH') {\n // As UpdateEntityController reads the body: these aren't data.\n if (payload === undefined) return write(['update']);\n const { $condition: _, $where: __, ...data } = payload;\n return write(['update'], data);\n }\n if (verb === 'DELETE') {\n return one({\n kind: 'entity',\n action: 'delete',\n entityType,\n entityId: second,\n });\n }\n }\n return unknown;\n }\n\n if (root === 'mutual') {\n const [byEntityType, byEntityId, entityType, entityId] = rest;\n if (rest.length === 3 && verb === 'GET') {\n // A chain query reads every relationship along the chain. Only the\n // first hop's byEntityId is known before Core runs the query.\n const chain = searchParams.get('chainEntityQuery');\n const types = [\n byEntityType,\n ...(chain ? chain.split(',') : []),\n entityType,\n ];\n return {\n ok: true,\n operations: types.slice(1).map(\n (to, hop): RelationshipOperation => ({\n kind: 'relationship',\n action: 'read',\n byEntityType: types[hop],\n ...(hop === 0 ? { byEntityId } : {}),\n entityType: to,\n }),\n ),\n };\n }\n if (rest.length === 4) {\n const action: RelationshipAction | undefined =\n verb === 'GET'\n ? 'read'\n : verb === 'POST'\n ? 'create'\n : verb === 'PATCH'\n ? 'update'\n : verb === 'DELETE'\n ? 'delete'\n : undefined;\n if (action) {\n const relationship: RelationshipOperation = {\n kind: 'relationship',\n action,\n byEntityType,\n byEntityId,\n entityType,\n entityId,\n ...(payload === undefined || action === 'read' || action === 'delete'\n ? {}\n : { payload }),\n };\n return {\n ok: true,\n operations:\n action === 'create'\n ? // CreateMutualController passes ?asEntity= to the service.\n relationshipCreate(\n entityConfig,\n relationship,\n searchParams.get('asEntity') ?? undefined,\n )\n : [relationship],\n };\n }\n }\n return unknown;\n }\n\n if (root === 'tag' && rest.length === 2 && verb === 'GET') {\n return one({\n kind: 'entity',\n action: 'list',\n entityType: rest[0],\n tag: rest[1],\n ...params('group', 'start', 'end'),\n });\n }\n\n if (root === 'transaction' && rest.length === 0 && verb === 'POST') {\n return transactionOperations(entityConfig, body);\n }\n\n if (root === 'app') {\n return one({\n kind: 'route',\n method: verb,\n path: `/${decoded.join('/')}`,\n ...(body === undefined ? {} : { body }),\n });\n }\n\n return unknown;\n};\n","import type { Entity } from '@monorise/base';\nimport type {\n EntityAction,\n EntityOperation,\n ProxyOperation,\n RelationshipAction,\n RelationshipOperation,\n RouteOperation,\n} from './operations';\n\n/** Calls Monorise Core with the request's key, for checks such as \"is this record in my organization?\". */\nexport type CoreClient = {\n /** A path under `/core`, e.g. `/mutual/hirer-organization/h1/project/p1`. */\n get(path: string): Promise<Response>;\n fetch(path: string, init?: RequestInit): Promise<Response>;\n};\n\nexport type RuleContext<Session = unknown> = {\n /** What `authenticate` returned; `undefined` for an anonymous visitor. */\n session: Session | undefined;\n request: Request;\n core: CoreClient;\n};\n\n/**\n * `true` forwards the operation; `false` refuses it with 403; a `Response`\n * is sent back as is. Only `true` forwards, so a rule that forgets to return\n * fails closed.\n */\nexport type RuleResult = boolean | Response;\n\n/**\n * Decides whether this user may perform one operation. Write shared rules\n * as `ProxyRule<Session>`; under an entity or action, the operation is\n * narrowed to that entity type and action.\n */\nexport type ProxyRule<Session = unknown, Operation = ProxyOperation> = (\n operation: Operation,\n context: RuleContext<Session>,\n) => RuleResult | Promise<RuleResult>;\n\n/** A rule for operations that need no ownership check: the key alone decides. */\nexport const allow = (): RuleResult => true;\n\n/** A rule that always refuses. */\nexport const deny = (): RuleResult => false;\n\n// biome-ignore lint/suspicious/noExplicitAny: a rule written for any operation or session\ntype AnyRule = ProxyRule<any, any>;\n\ntype HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n// The entity types rules can name: the generated `Entity`, or any string\n// until `monorise dev` generates it.\ntype EntityName = keyof typeof Entity extends never ? string : Entity;\n\n// `'*'` stands for every action.\ntype ActionOf<Key, All> = Key extends All ? Key : All;\n\n/** Rules for one direction of a relationship, e.g. learner→course. */\nexport type RelationshipRules<\n Session = unknown,\n By extends string = string,\n To extends string = string,\n> =\n | ProxyRule<Session, RelationshipOperation<By, To>>\n | {\n [A in RelationshipAction | '*']?: ProxyRule<\n Session,\n RelationshipOperation<By, To, ActionOf<A, RelationshipAction>>\n >;\n };\n\ntype MutualsRules<Session, By extends string> = {\n /** Every relationship from this entity that has no entry. */\n '*'?:\n | ProxyRule<Session, RelationshipOperation<By, EntityName>>\n | {\n [A in RelationshipAction]?: ProxyRule<\n Session,\n RelationshipOperation<By, EntityName, A>\n >;\n };\n} & { [To in EntityName]?: RelationshipRules<Session, By, To> };\n\n/**\n * Rules for one entity type. A single rule covers every action on the entity\n * and its relationships. An object names actions, with `'*'` for the rest of\n * the entity's actions, and `mutuals` for relationships from it.\n */\nexport type EntityRules<Session = unknown, T extends string = string> =\n | ProxyRule<\n Session,\n EntityOperation<T> | RelationshipOperation<T, EntityName>\n >\n | ({\n [A in EntityAction | '*']?: ProxyRule<\n Session,\n EntityOperation<T, ActionOf<A, EntityAction>>\n >;\n } & { mutuals?: MutualsRules<Session, T> });\n\ntype TableRules<Session> =\n | ProxyRule<Session>\n | {\n [A in EntityAction | RelationshipAction]?: ProxyRule<\n Session,\n | (A extends EntityAction ? EntityOperation<string, A> : never)\n | (A extends RelationshipAction\n ? RelationshipOperation<string, string, A>\n : never)\n >;\n };\n\n// Before `Entity` is generated, every entry takes rules on any operation.\ntype UntypedRules<Session> =\n | ProxyRule<Session>\n | ({\n [A in EntityAction | RelationshipAction | '*']?: ProxyRule<Session>;\n } & {\n mutuals?: Record<\n string,\n | ProxyRule<Session>\n | { [A in RelationshipAction | '*']?: ProxyRule<Session> }\n >;\n });\n\n/**\n * Rules keyed by entity type. `'*'` applies to anything the table doesn't\n * name: a single rule for every operation, or rules per action.\n */\nexport type ProxyRules<Session = unknown> = string extends EntityName\n ? Record<string, UntypedRules<Session>>\n : { '*'?: TableRules<Session> } & {\n [T in EntityName]?: EntityRules<Session, T>;\n };\n\n/**\n * Rules for custom routes, keyed by `'METHOD /app/path'`. A `:param` segment\n * matches any one segment and a trailing `*` matches the rest; `'*'` applies\n * to every route the table doesn't name.\n */\nexport type RouteRules<Session = unknown> = {\n [K in `${HttpMethod} /app/${string}` | '*']?: ProxyRule<\n Session,\n RouteOperation\n >;\n};\n\nconst hasOwn = (object: object, key: string) =>\n Object.prototype.hasOwnProperty.call(object, key);\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst own = (object: unknown, key: string): unknown =>\n isRecord(object) && hasOwn(object, key) ? object[key] : undefined;\n\nconst asRule = (value: unknown): AnyRule | undefined =>\n typeof value === 'function' ? (value as AnyRule) : undefined;\n\n// A single rule, or the rule an object of rules names for this action.\nconst ruleFor = (value: unknown, action: string) =>\n asRule(value) ?? asRule(own(value, action));\n\ntype RouteMatch = { rule: AnyRule; params: Record<string, string> };\n\n// The first position where two ranks differ decides; a tie keeps the earlier.\nconst outranks = (rank: number[], than: number[]) => {\n const index = rank.findIndex((value, at) => value !== than[at]);\n return index !== -1 && rank[index] > than[index];\n};\n\n/**\n * The most specific route rule wins, whatever order the table lists them in:\n * more literal segments first, then a pattern without a trailing `*`, then\n * fewer `:param`s. Declaration order only breaks ties.\n */\nconst matchRoute = (\n routes: object | undefined,\n operation: RouteOperation,\n): RouteMatch | undefined => {\n if (!routes) return undefined;\n\n const exact = asRule(own(routes, `${operation.method} ${operation.path}`));\n if (exact) return { rule: exact, params: {} };\n\n const segments = operation.path.split('/').filter(Boolean);\n let best: { match: RouteMatch; rank: number[] } | undefined;\n for (const [key, rule] of Object.entries(routes)) {\n const [method, pattern] = key.split(' ');\n if (method !== operation.method || !pattern || typeof rule !== 'function') {\n continue;\n }\n const parts = pattern.split('/').filter(Boolean);\n const params: Record<string, string> = {};\n const rest = parts.at(-1) === '*';\n const fixed = rest ? parts.slice(0, -1) : parts;\n if (\n rest ? segments.length < fixed.length : segments.length !== fixed.length\n ) {\n continue;\n }\n const matches = fixed.every((part, index) => {\n if (part.startsWith(':')) {\n params[part.slice(1)] = segments[index];\n return true;\n }\n return part === segments[index];\n });\n if (!matches) continue;\n\n const paramCount = fixed.filter((part) => part.startsWith(':')).length;\n // Compared in order; a higher number is more specific.\n const rank = [fixed.length - paramCount, rest ? 0 : 1, -paramCount];\n if (!best || outranks(rank, best.rank)) {\n best = { match: { rule, params }, rank };\n }\n }\n return best?.match;\n};\n\n/**\n * Finds the rule for an operation. The most specific match wins:\n *\n * | Entity operation | Relationship operation | Route |\n * | `rules[entity][action]` | `rules[by].mutuals[target][action]` | `routes['METHOD /app/…']` |\n * | `rules[entity]['*']`, or `rules[entity]` as a single rule | `rules[by].mutuals[target]['*']`, then `rules[by].mutuals['*']`, or `rules[by]` as a single rule | `routes['*']` |\n * | `rules['*'][action]`, or `rules['*']` as a single rule | the same | `rules['*']` as a single rule |\n *\n * `undefined` means no rule: the operation is refused.\n */\nexport const findRule = (\n rules: object | undefined,\n routes: object | undefined,\n operation: ProxyOperation,\n): { rule: AnyRule; operation: ProxyOperation } | undefined => {\n const tableFallback = own(rules, '*');\n const found = (rule: AnyRule | undefined, matched = operation) =>\n rule ? { rule, operation: matched } : undefined;\n\n if (operation.kind === 'entity') {\n const entity = own(rules, operation.entityType);\n return found(\n asRule(entity) ??\n asRule(own(entity, operation.action)) ??\n asRule(own(entity, '*')) ??\n ruleFor(tableFallback, operation.action),\n );\n }\n\n if (operation.kind === 'relationship') {\n const entity = own(rules, operation.byEntityType);\n const mutuals = own(entity, 'mutuals');\n return found(\n asRule(entity) ??\n ruleFor(own(mutuals, operation.entityType), operation.action) ??\n asRule(own(own(mutuals, operation.entityType), '*')) ??\n ruleFor(own(mutuals, '*'), operation.action) ??\n ruleFor(tableFallback, operation.action),\n );\n }\n\n const route = matchRoute(routes, operation);\n if (route) return found(route.rule, { ...operation, params: route.params });\n return found(asRule(own(routes, '*')) ?? asRule(tableFallback));\n};\n\n/** How a refusal names an operation, e.g. `delete on 'hirer-schedule'`. */\nexport const describeOperation = (operation: ProxyOperation) =>\n operation.kind === 'entity'\n ? `${operation.action} on '${operation.entityType}'`\n : operation.kind === 'relationship'\n ? `${operation.action} on ${operation.byEntityType}→${operation.entityType}`\n : `${operation.method} ${operation.path}`;\n\n// The rule to add, shaped for the operation, logged when one is missing.\nconst missingRuleHint = (operation: ProxyOperation) =>\n operation.kind === 'entity'\n ? `rules: { '${operation.entityType}': { ${operation.action}: (operation, { session }) => … } }`\n : operation.kind === 'relationship'\n ? `rules: { '${operation.byEntityType}': { mutuals: { '${operation.entityType}': { ${operation.action}: (operation, { session }) => … } } } }`\n : `routes: { '${operation.method} ${operation.path}': (operation, { session }) => … }`;\n\nconst forbidden = (message: string, operation: ProxyOperation) =>\n new Response(\n JSON.stringify({\n code: 'FORBIDDEN',\n message,\n ...('operationIndex' in operation &&\n operation.operationIndex !== undefined\n ? { operationIndex: operation.operationIndex }\n : {}),\n }),\n { status: 403, headers: { 'content-type': 'application/json' } },\n );\n\n/**\n * Runs the rule for every operation, in order, and stops at the first\n * refusal. `undefined` means every operation may go ahead.\n */\nexport const checkOperations = async <Session>({\n operations,\n rules,\n routes,\n context,\n logMissingRules = false,\n}: {\n operations: ProxyOperation[];\n rules?: ProxyRules<Session>;\n routes?: RouteRules<Session>;\n context: RuleContext<Session>;\n logMissingRules?: boolean;\n}): Promise<Response | undefined> => {\n for (const operation of operations) {\n const found = findRule(rules, routes, operation);\n if (!found) {\n if (logMissingRules) {\n console.warn(\n `[monorise/proxy] No rule for ${describeOperation(operation)}. Add one: ${missingRuleHint(operation)}`,\n );\n }\n return forbidden(\n `No proxy rule for ${describeOperation(operation)}`,\n operation,\n );\n }\n\n const result = await found.rule(found.operation, context);\n if (result instanceof Response) return result;\n if (result !== true) {\n return forbidden(\n `Proxy rule refused ${describeOperation(operation)}`,\n operation,\n );\n }\n }\n return undefined;\n};\n","import {\n type ProxyEntityConfig,\n type ProxyOperation,\n parseOperations,\n} from './operations';\nimport {\n type CoreClient,\n type ProxyRules,\n type RouteRules,\n type RuleContext,\n checkOperations,\n} from './rules';\n\n/** One kind of caller: the key it calls Core with, and the rules for its users. */\nexport type ProxyCaller<Session = unknown> = {\n /** A key in `API_KEYS`, usually mapped to a policy for this kind of caller. */\n apiKey: string | undefined;\n rules?: ProxyRules<Session>;\n routes?: RouteRules<Session>;\n};\n\ntype AuthenticateResult<Session> = Session | null | undefined | Response;\n\ntype SharedOptions<Session> = {\n /** The generated config, which says which payload fields are relationships. */\n config: { EntityConfig: ProxyEntityConfig };\n /**\n * Reads the session. `undefined` or `null` is an anonymous visitor; a\n * `Response`, such as a 401 that clears an expired cookie, is sent back as is.\n */\n authenticate?: (\n request: Request,\n ) => AuthenticateResult<Session> | Promise<AuthenticateResult<Session>>;\n /** The prefix stripped before forwarding. Defaults to `/api/core`. */\n basePath?: string;\n /** Core's URL. Defaults to `process.env.API_BASE_URL`. */\n apiBaseUrl?: string;\n /** Logs the rule to add when none matches. Defaults to on outside production. */\n logMissingRules?: boolean;\n};\n\nexport type ProxyHandlerOptions<Session = unknown> = SharedOptions<Session> &\n (\n | {\n /** Names the kind of caller for this request; `undefined` answers 401. */\n caller: (args: {\n session: Session | undefined;\n request: Request;\n }) => string | undefined | Promise<string | undefined>;\n callers: Record<string, ProxyCaller<Session>>;\n apiKey?: never;\n rules?: never;\n routes?: never;\n }\n | ({ caller?: never; callers?: never } & ProxyCaller<Session>)\n );\n\nexport type CheckResult<Session = unknown> =\n | {\n allowed: true;\n /** The kind of caller, or `undefined` for an app with one kind. */\n caller: string | undefined;\n session: Session | undefined;\n operations: ProxyOperation[];\n }\n | { allowed: false; response: Response };\n\ntype RequestHandler = (request: Request) => Promise<Response>;\n\nexport type ProxyHandler<Session = unknown> = {\n /** Checks a request to Core and forwards it, or answers with the refusal. */\n handle: RequestHandler;\n /** Runs every step but forwarding, so rules can be unit-tested. */\n checkRequest: (request: Request) => Promise<CheckResult<Session>>;\n GET: RequestHandler;\n POST: RequestHandler;\n PUT: RequestHandler;\n PATCH: RequestHandler;\n DELETE: RequestHandler;\n};\n\nconst FORWARDED_HEADERS = [\n 'content-type',\n 'accept',\n 'accept-language',\n 'x-request-id',\n];\n\n// fetch has already decoded the body and framed it for this hop.\nconst DROPPED_RESPONSE_HEADERS = [\n 'content-encoding',\n 'content-length',\n 'transfer-encoding',\n 'connection',\n];\n\nconst hasOwn = (object: object, key: string) =>\n Object.prototype.hasOwnProperty.call(object, key);\n\nconst env = (name: string) =>\n typeof process === 'undefined' ? undefined : process.env?.[name];\n\nconst json = (status: number, body: Record<string, unknown>) =>\n new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json' },\n });\n\nconst unauthorized = () =>\n json(401, { code: 'UNAUTHORIZED', message: 'Unauthorized' });\n\nconst misconfigured = (message: string) => {\n console.error(`[monorise/proxy] ${message}`);\n return json(500, { code: 'PROXY_MISCONFIGURED', message });\n};\n\ntype Prepared<Session> = {\n caller: string | undefined;\n session: Session | undefined;\n apiKey: string;\n apiBaseUrl: string;\n /** The path under `/core`, as the client encoded it, with its query. */\n target: string;\n body: ArrayBuffer | undefined;\n operations: ProxyOperation[];\n};\n\n/**\n * Puts Monorise Core behind your app's own route. Each request is checked\n * against the rules for its kind of caller, then forwarded with that\n * caller's key: the key decides what the caller can reach, and the rules\n * decide whose records.\n *\n * @example\n * ```ts\n * const proxy = createProxyHandler({\n * config,\n * authenticate: (request) => readSession(request),\n * caller: ({ session }) => session?.type ?? 'public',\n * callers: {\n * hirer: { apiKey: process.env.HIRER_API_KEY, rules: hirerRules },\n * public: { apiKey: process.env.PUBLIC_API_KEY, rules: publicRules },\n * },\n * });\n *\n * export const { GET, POST, PUT, PATCH, DELETE } = proxy;\n * ```\n */\nexport const createProxyHandler = <Session = unknown>(\n options: ProxyHandlerOptions<Session>,\n): ProxyHandler<Session> => {\n const multiple =\n options.callers !== undefined || options.caller !== undefined;\n if (\n multiple &&\n (typeof options.caller !== 'function' ||\n typeof options.callers !== 'object' ||\n options.apiKey !== undefined ||\n options.rules !== undefined ||\n options.routes !== undefined)\n ) {\n throw new Error(\n 'createProxyHandler takes either caller and callers, or apiKey and rules',\n );\n }\n\n const basePath = `/${(options.basePath ?? '/api/core').replace(/^\\/+|\\/+$/g, '')}`;\n const entityConfig = options.config?.EntityConfig;\n const logMissingRules =\n options.logMissingRules ?? env('NODE_ENV') !== 'production';\n\n const coreClient = (apiBaseUrl: string, apiKey: string): CoreClient => {\n const coreFetch = (path: string, init: RequestInit = {}) => {\n const headers = new Headers(init.headers);\n headers.set('x-api-key', apiKey);\n return fetch(`${apiBaseUrl}/core${path}`, {\n cache: 'no-store',\n ...init,\n headers,\n });\n };\n return { get: (path) => coreFetch(path), fetch: coreFetch };\n };\n\n const prepare = async (\n request: Request,\n ): Promise<Prepared<Session> | Response> => {\n // Read from a copy, so authenticate and rules can still read the request.\n const body =\n request.method === 'GET' || request.method === 'HEAD'\n ? undefined\n : await request.clone().arrayBuffer();\n\n // 1. Authenticate\n const authenticated = options.authenticate\n ? await options.authenticate(request)\n : undefined;\n if (authenticated instanceof Response) return authenticated;\n const session = authenticated ?? undefined;\n\n // 2. Choose the caller\n let caller: string | undefined;\n let entry: ProxyCaller<Session> | undefined;\n if (multiple) {\n caller = await options.caller?.({ session, request });\n const callers = options.callers ?? {};\n entry =\n caller !== undefined && hasOwn(callers, caller)\n ? callers[caller]\n : undefined;\n } else if (!options.authenticate || session !== undefined) {\n entry = options;\n }\n if (!entry) return unauthorized();\n if (!entry.apiKey) {\n return misconfigured(\n caller === undefined\n ? 'No apiKey is set'\n : `No apiKey is set for caller '${caller}'`,\n );\n }\n const apiBaseUrl = (options.apiBaseUrl ?? env('API_BASE_URL'))?.replace(\n /\\/+$/,\n '',\n );\n if (!apiBaseUrl) {\n return misconfigured('No apiBaseUrl is set, and API_BASE_URL is empty');\n }\n\n // 3. Parse into operations\n const url = new URL(request.url);\n if (url.pathname !== basePath && !url.pathname.startsWith(`${basePath}/`)) {\n return json(404, {\n code: 'NOT_FOUND',\n message: `The proxy serves paths under ${basePath}`,\n });\n }\n const path = url.pathname.slice(basePath.length) || '/';\n const text = body ? new TextDecoder().decode(body) : '';\n let parsed: unknown;\n if (text.trim()) {\n try {\n parsed = JSON.parse(text);\n } catch {\n // Custom routes may take other bodies; their rules see none.\n if (!path.startsWith('/app/')) {\n return json(400, {\n code: 'BAD_REQUEST',\n message: 'Request body must be JSON',\n });\n }\n }\n }\n const result = parseOperations({\n method: request.method,\n path,\n searchParams: url.searchParams,\n body: parsed,\n entityConfig,\n });\n if (!result.ok) {\n return json(result.status, {\n code: result.status === 404 ? 'NOT_FOUND' : 'BAD_REQUEST',\n message: result.message,\n });\n }\n\n // 4. Check rules\n const context: RuleContext<Session> = {\n session,\n request,\n core: coreClient(apiBaseUrl, entry.apiKey),\n };\n const refusal = await checkOperations({\n operations: result.operations,\n rules: entry.rules,\n routes: entry.routes,\n context,\n logMissingRules,\n });\n if (refusal) return refusal;\n\n return {\n caller,\n session,\n apiKey: entry.apiKey,\n apiBaseUrl,\n target: `${path}${url.search}`,\n body: body && body.byteLength > 0 ? body : undefined,\n operations: result.operations,\n };\n };\n\n const checkRequest = async (\n request: Request,\n ): Promise<CheckResult<Session>> => {\n const prepared = await prepare(request);\n if (prepared instanceof Response) {\n return { allowed: false, response: prepared };\n }\n const { caller, session, operations } = prepared;\n return { allowed: true, caller, session, operations };\n };\n\n const handle = async (request: Request): Promise<Response> => {\n const prepared = await prepare(request);\n if (prepared instanceof Response) return prepared;\n\n // 5. Forward, with only the headers Core needs and the caller's key\n const headers = new Headers();\n for (const name of FORWARDED_HEADERS) {\n const value = request.headers.get(name);\n if (value !== null) headers.set(name, value);\n }\n headers.set('x-api-key', prepared.apiKey);\n\n let response: Response;\n try {\n response = await fetch(`${prepared.apiBaseUrl}/core${prepared.target}`, {\n method: request.method,\n headers,\n body: prepared.body,\n cache: 'no-store',\n });\n } catch (error) {\n console.error('[monorise/proxy] Monorise Core is unreachable', error);\n return json(502, {\n code: 'BAD_GATEWAY',\n message: 'Monorise Core is unreachable',\n });\n }\n\n // 6. Respond with Core's status and body\n const responseHeaders = new Headers(response.headers);\n for (const name of DROPPED_RESPONSE_HEADERS) responseHeaders.delete(name);\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n });\n };\n\n const alias: RequestHandler = (request) => handle(request);\n return {\n handle,\n checkRequest,\n GET: alias,\n POST: alias,\n PUT: alias,\n PATCH: alias,\n DELETE: alias,\n };\n};\n","import type { Entity } from '@monorise/base';\n\ninterface GenerateTicketOptions {\n entityType: Entity;\n entityId: string;\n feedTypes?: Entity[];\n}\n\ninterface TicketResponse {\n ticket: string;\n wsUrl: string;\n expiresIn: number;\n}\n\nconst getApiBaseUrl = (): string => {\n const url = process.env.API_BASE_URL;\n if (!url) {\n throw new Error(\n 'API_BASE_URL environment variable is required for generateWebSocketTicket',\n );\n }\n return url;\n};\n\nconst getApiKey = (): string => {\n return process.env.MONORISE_API_KEY || process.env.API_KEY || '';\n};\n\n/**\n * Generate a WebSocket ticket for entity feed subscriptions.\n * Call this from your proxy route (e.g., Next.js API route) after validating auth.\n *\n * @example\n * ```ts\n * import { generateWebSocketTicket } from 'monorise/proxy';\n * import { Entity } from './monorise/entities';\n *\n * export async function POST(req) {\n * const session = await getSession(req);\n * const ticket = await generateWebSocketTicket({\n * entityType: Entity.USER,\n * entityId: session.userId,\n * feedTypes: [Entity.CHANNEL, Entity.MESSAGE],\n * });\n * return Response.json(ticket);\n * }\n * ```\n */\nexport const generateWebSocketTicket = async (\n options: GenerateTicketOptions,\n): Promise<TicketResponse> => {\n const apiBaseUrl = getApiBaseUrl();\n const apiKey = getApiKey();\n\n const { entityType, entityId, feedTypes } = options;\n\n const response = await fetch(\n // `/core` is monorise's own Hono basePath (packages/core/handles/app.ts),\n // not part of API_BASE_URL -- the React default endpoint spells the same\n // path as `/api/core/ws/ticket/...`.\n `${apiBaseUrl}/core/ws/ticket/${entityType}/${entityId}`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(apiKey && { 'x-api-key': apiKey }),\n },\n body: JSON.stringify({\n ...(feedTypes && { feedTypes }),\n }),\n },\n );\n\n if (!response.ok) {\n throw new Error(\n `Failed to generate WebSocket ticket: ${response.status} ${response.statusText}`,\n );\n }\n\n return response.json() as Promise<TicketResponse>;\n};\n\nexport {\n type CheckResult,\n type ProxyCaller,\n type ProxyHandler,\n type ProxyHandlerOptions,\n createProxyHandler,\n} from './proxy/handler';\nexport type {\n EntityAction,\n EntityOperation,\n ProxyEntityConfig,\n ProxyOperation,\n RelationshipAction,\n RelationshipOperation,\n RouteOperation,\n} from './proxy/operations';\nexport {\n type CoreClient,\n type EntityRules,\n type ProxyRule,\n type ProxyRules,\n type RelationshipRules,\n type RouteRules,\n type RuleContext,\n type RuleResult,\n allow,\n deny,\n} from './proxy/rules';\n"],"mappings":";AA0JA,IAAM,SAAS,CAAC,QAAgB,QAC9B,OAAO,UAAU,eAAe,KAAK,QAAQ,GAAG;AAElD,IAAM,WAAW,CAAC,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAErE,IAAM,WAAW,CAAC,aAAkC;AAAA,EAClD,IAAI;AAAA,EACJ,QAAQ;AAAA,EACR;AACF;AAEA,IAAM,UAAU,CAAC,aAAkC;AAAA,EACjD,IAAI;AAAA,EACJ,QAAQ;AAAA,EACR;AACF;AAIA,IAAM,eAAe,CACnB,cACA,cACA,eACG;AACH,QAAM,WAAW,CAAC,MAAc,OAAe;AAC7C,UAAM,SACJ,gBAAgB,OAAO,cAAc,IAAI,IACrC,aAAa,IAAI,EAAE,QAAQ,eAC3B;AACN,WAAO,OAAO,OAAO,UAAU,CAAC,CAAC,EAAE;AAAA,MACjC,CAAC,UAAU,MAAM,eAAe,MAAM,MAAM;AAAA,IAC9C,GAAG,QAAQ,UAAU;AAAA,EACvB;AACA,SACE,SAAS,cAAc,UAAU,KAAK,SAAS,YAAY,YAAY;AAE3E;AASA,IAAM,qBAAqB,CACzB,cACA,cACA,sBACqB;AACrB,QAAM,EAAE,cAAc,YAAY,YAAY,UAAU,QAAQ,IAC9D;AACF,QAAM,WACJ,qBAAqB,aAAa,cAAc,cAAc,UAAU;AAC1E,MAAI,CAAC,SAAU,QAAO,CAAC,YAAY;AACnC,SAAO;AAAA,IACL;AAAA,IACA;AAAA,MACE,MAAM;AAAA,MACN,QAAQ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W,MAAM;AAAA;AAAA;AAAA;AAAA,IAIrB,GAAG,UAAU,mBAAmB,UAAU,IAAI,QAAQ;AAAA,IACtD;AAAA,MACE,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,GAAI,UAAU,EAAE,aAAa,OAAO;AAAA,MACtC;AAAA,MACA,MAAM,KAAK,UAAU;AAAA,QACnB,GAAI,aAAa,EAAE,UAAU;AAAA,MAC/B,CAAC;AAAA,IACH;AAAA,EACF;AAEA,MAAI,CAAC,SAAS,IAAI;AAChB,UAAM,IAAI;AAAA,MACR,wCAAwC,SAAS,MAAM,IAAI,SAAS,UAAU;AAAA,IAChF;AAAA,EACF;AAEA,SAAO,SAAS,KAAK;AACvB;","names":["hasOwn","isRecord","hasOwn"]}
|
|
1
|
+
{"version":3,"sources":["../proxy/operations.ts","../proxy/rules.ts","../proxy/handler.ts","../index.ts"],"sourcesContent":["/**\n * A request to Monorise Core, described as the operations rules are written\n * against: one per thing it reads or writes. Rules on operations rather than\n * URLs can't be bypassed by a different request shape: a transaction's\n * `deleteEntity` and a `DELETE /entity/...` are the same operation.\n */\n\nimport type { ApiKeyMutualDataFields, EntitySchemaMap } from '@monorise/base';\n\n/**\n * `adjust` adds an amount to numeric fields (`POST /entity/:type/:id/adjust`).\n * API key policies count it as an update; rules keep it apart, so a rule\n * written for the values an update sets never approves an adjust.\n */\nexport type EntityAction =\n | 'get'\n | 'list'\n | 'create'\n | 'update'\n | 'adjust'\n | 'delete';\n\n/** Relationships have a single `read`: their listings are bounded by `byEntityId`. */\nexport type RelationshipAction = 'read' | 'create' | 'update' | 'delete';\n\n/**\n * An entity's fields, from the generated `EntitySchemaMap`. Rules see the\n * payload before Core validates it, so every field may be missing.\n */\nexport type EntityPayload<T extends string = string> = string extends T\n ? Record<string, unknown>\n : T extends keyof EntitySchemaMap\n ? Partial<EntitySchemaMap[T]>\n : Record<string, unknown>;\n\n/** An entity's numeric fields: what an `adjust` adds amounts to. */\nexport type EntityAdjustments<T extends string = string> = string extends T\n ? Record<string, number>\n : T extends keyof EntitySchemaMap\n ? {\n [K in keyof EntitySchemaMap[T] as NonNullable<\n EntitySchemaMap[T][K]\n > extends number\n ? K\n : never]?: number;\n }\n : Record<string, number>;\n\ntype MutualDataField<\n By extends string,\n To extends string,\n> = By extends keyof ApiKeyMutualDataFields\n ? To extends keyof ApiKeyMutualDataFields[By]\n ? Extract<ApiKeyMutualDataFields[By][To], string>\n : string\n : string;\n\n/** A relationship's `mutualData`, with the field names the generated config declares. */\nexport type MutualDataPayload<\n By extends string = string,\n To extends string = string,\n> = { [K in MutualDataField<By, To>]?: unknown };\n\nexport type EntityOperation<\n T extends string = string,\n A extends EntityAction = EntityAction,\n> = {\n kind: 'entity';\n action: A;\n entityType: T;\n entityId?: string;\n /** The fields a `create` or `update` sets. */\n payload?: A extends 'adjust' ? never : EntityPayload<T>;\n /**\n * The named condition an `update` or `adjust` must meet: the body's\n * `$condition`, or a transaction entry's `condition`.\n */\n condition?: string;\n /** The amount an `adjust` adds to each numeric field. */\n adjustments?: 'adjust' extends A ? EntityAdjustments<T> : never;\n /**\n * The relationship this entity materializes, when creating the relationship\n * also creates it (`asEntity`).\n */\n asEntityOf?: Pick<\n RelationshipOperation,\n 'byEntityType' | 'byEntityId' | 'entityType' | 'entityId'\n >;\n /** The search term of a `list`, as Core receives it. */\n query?: string;\n /** The field and value of a get by unique field. */\n unique?: { field: string; value: string };\n /** The tag a `list` queries. */\n tag?: string;\n /** The tag group a tag listing reads, often what a rule scopes by. */\n group?: string;\n /** The range a `list` reads: Core's `start` and `end` query parameters. */\n start?: string;\n end?: string;\n /** Position in a transaction's `operations`. */\n operationIndex?: number;\n};\n\nexport type RelationshipOperation<\n By extends string = string,\n To extends string = string,\n A extends RelationshipAction = RelationshipAction,\n> = {\n kind: 'relationship';\n action: A;\n byEntityType: By;\n /**\n * Absent for a relationship field on an entity created without an ID, and\n * for every hop of a chain query after the first.\n */\n byEntityId?: string;\n entityType: To;\n /** Absent when listing, and for the relationships an update's new list removes. */\n entityId?: string;\n payload?: MutualDataPayload<By, To>;\n operationIndex?: number;\n};\n\nexport type RouteOperation = {\n kind: 'route';\n method: string;\n /** The path under `/core`, e.g. `/app/invite-casting`. */\n path: string;\n body?: unknown;\n /** Segments the matching route rule's `:param`s captured. */\n params?: Record<string, string>;\n};\n\nexport type ProxyOperation =\n | EntityOperation\n | RelationshipOperation\n | RouteOperation;\n\nexport type ParseResult =\n | { ok: true; operations: ProxyOperation[] }\n | { ok: false; status: 400 | 404; message: string };\n\n/**\n * The parts of the generated config the parser reads: which payload fields of\n * each entity are relationships, to which entity type, and which\n * relationships materialize an entity (`asEntity`).\n */\nexport type ProxyEntityConfig = Record<\n string,\n {\n mutual?: {\n mutualFields?: Record<\n string,\n { entityType: string; mutual?: { asEntity?: { name: string } } }\n >;\n };\n }\n>;\n\nconst hasOwn = (object: object, key: string) =>\n Object.prototype.hasOwnProperty.call(object, key);\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst notFound = (message: string): ParseResult => ({\n ok: false,\n status: 404,\n message,\n});\n\nconst invalid = (message: string): ParseResult => ({\n ok: false,\n status: 400,\n message,\n});\n\n// The entity type a relationship materializes (`asEntity`). Its mutual\n// config can sit on either side, as in Core.\nconst asEntityType = (\n entityConfig: ProxyEntityConfig | undefined,\n byEntityType: string,\n entityType: string,\n) => {\n const declared = (from: string, to: string) => {\n const fields =\n entityConfig && hasOwn(entityConfig, from)\n ? entityConfig[from].mutual?.mutualFields\n : undefined;\n return Object.values(fields ?? {}).find(\n (field) => field.entityType === to && field.mutual,\n )?.mutual?.asEntity?.name;\n };\n return (\n declared(byEntityType, entityType) ?? declared(entityType, byEntityType)\n );\n};\n\n/**\n * A relationship create, followed by a create of the entity it materializes\n * when it has an `asEntity`: the relationship's `mutualData` becomes that\n * entity's data. `requestedAsEntity` is one the request names, which wins\n * over the config's. Updates and deletes reach that entity by replication,\n * so only the create is described.\n */\nconst relationshipCreate = (\n entityConfig: ProxyEntityConfig | undefined,\n relationship: RelationshipOperation,\n requestedAsEntity?: string,\n): ProxyOperation[] => {\n const { byEntityType, byEntityId, entityType, entityId, payload } =\n relationship;\n const asEntity =\n requestedAsEntity || asEntityType(entityConfig, byEntityType, entityType);\n if (!asEntity) return [relationship];\n return [\n relationship,\n {\n kind: 'entity',\n action: 'create',\n entityType: asEntity,\n ...(payload === undefined ? {} : { payload }),\n asEntityOf: { byEntityType, byEntityId, entityType, entityId },\n ...(relationship.operationIndex === undefined\n ? {}\n : { operationIndex: relationship.operationIndex }),\n },\n ];\n};\n\n/**\n * A relationship field in an entity payload writes the relationship from that\n * entity to each listed ID. On create it only adds relationships. On update\n * the new list replaces the old one, so it can also remove relationships the\n * request doesn't name: one `delete` without an `entityId` stands for those.\n */\nconst relationshipFieldOperations = (\n entityConfig: ProxyEntityConfig | undefined,\n entityType: string,\n entityId: string | undefined,\n payload: Record<string, unknown> | undefined,\n write: 'create' | 'update',\n operationIndex: number | undefined,\n): ProxyOperation[] => {\n const config =\n entityConfig && hasOwn(entityConfig, entityType)\n ? entityConfig[entityType]\n : undefined;\n const fields = config?.mutual?.mutualFields;\n if (!payload || !fields) return [];\n\n const operations: ProxyOperation[] = [];\n for (const [field, value] of Object.entries(payload)) {\n if (!hasOwn(fields, field)) continue;\n const base = {\n kind: 'relationship' as const,\n byEntityType: entityType,\n byEntityId: entityId,\n entityType: fields[field].entityType,\n ...(operationIndex === undefined ? {} : { operationIndex }),\n };\n const ids = Array.isArray(value)\n ? value.filter((id): id is string => typeof id === 'string')\n : [];\n for (const id of ids) {\n operations.push(\n ...relationshipCreate(entityConfig, {\n ...base,\n action: 'create',\n entityId: id,\n }),\n );\n }\n if (write === 'update') operations.push({ ...base, action: 'delete' });\n }\n return operations;\n};\n\nconst entityWrite = (\n entityConfig: ProxyEntityConfig | undefined,\n actions: ('create' | 'update')[],\n entityType: string,\n entityId: string | undefined,\n payload: Record<string, unknown> | undefined,\n operationIndex?: number,\n condition?: string,\n): ProxyOperation[] => {\n const index = operationIndex === undefined ? {} : { operationIndex };\n return [\n ...actions.map(\n (action): EntityOperation => ({\n kind: 'entity',\n action,\n entityType,\n ...(entityId === undefined ? {} : { entityId }),\n ...(payload === undefined ? {} : { payload }),\n ...(condition === undefined ? {} : { condition }),\n ...index,\n }),\n ),\n ...relationshipFieldOperations(\n entityConfig,\n entityType,\n entityId,\n payload,\n // An upsert can update, so its relationship fields count as an update's.\n actions.includes('update') ? 'update' : 'create',\n operationIndex,\n ),\n ];\n};\n\nconst transactionOperations = (\n entityConfig: ProxyEntityConfig | undefined,\n body: unknown,\n): ParseResult => {\n const entries = isRecord(body) ? body.operations : undefined;\n if (!Array.isArray(entries)) {\n return invalid('Request body must contain an \"operations\" array');\n }\n\n const operations: ProxyOperation[] = [];\n for (const [operationIndex, entry] of entries.entries()) {\n if (!isRecord(entry) || typeof entry.entityType !== 'string') {\n return invalid(`Operation ${operationIndex} has no entityType`);\n }\n const { entityType } = entry;\n const entityId =\n typeof entry.entityId === 'string' ? entry.entityId : undefined;\n const payload = isRecord(entry.payload) ? entry.payload : undefined;\n const condition =\n typeof entry.condition === 'string' ? entry.condition : undefined;\n\n switch (entry.operation) {\n case 'createEntity':\n case 'updateEntity':\n operations.push(\n ...entityWrite(\n entityConfig,\n [entry.operation === 'createEntity' ? 'create' : 'update'],\n entityType,\n entityId,\n payload,\n operationIndex,\n condition,\n ),\n );\n break;\n case 'adjustEntity':\n operations.push({\n kind: 'entity',\n action: 'adjust',\n entityType,\n ...(entityId === undefined ? {} : { entityId }),\n ...(isRecord(entry.adjustments)\n ? { adjustments: entry.adjustments as Record<string, number> }\n : {}),\n ...(condition === undefined ? {} : { condition }),\n operationIndex,\n });\n break;\n case 'deleteEntity':\n operations.push({\n kind: 'entity',\n action: 'delete',\n entityType,\n ...(entityId === undefined ? {} : { entityId }),\n operationIndex,\n });\n break;\n case 'createMutual':\n case 'updateMutual':\n case 'deleteMutual': {\n if (\n typeof entry.byEntityType !== 'string' ||\n typeof entry.byEntityId !== 'string'\n ) {\n return invalid(\n `Operation ${operationIndex} needs byEntityType and byEntityId`,\n );\n }\n const relationship: RelationshipOperation = {\n kind: 'relationship',\n action:\n entry.operation === 'createMutual'\n ? 'create'\n : entry.operation === 'updateMutual'\n ? 'update'\n : 'delete',\n byEntityType: entry.byEntityType,\n byEntityId: entry.byEntityId,\n entityType,\n ...(entityId === undefined ? {} : { entityId }),\n ...(payload === undefined ? {} : { payload }),\n operationIndex,\n };\n // A transaction's createMutual uses only the config's asEntity.\n operations.push(\n ...(relationship.action === 'create'\n ? relationshipCreate(entityConfig, relationship)\n : [relationship]),\n );\n break;\n }\n default:\n return invalid(\n `Operation ${operationIndex} has an unknown operation '${String(entry.operation)}'`,\n );\n }\n }\n return { ok: true, operations };\n};\n\nconst decode = (segment: string) => {\n try {\n return decodeURIComponent(segment);\n } catch {\n return undefined;\n }\n};\n\n/**\n * Describes a request to Monorise Core as operations. `path` is the path\n * under `/core`, e.g. `/entity/order/123`. Paths Core doesn't serve, and the\n * WebSocket ticket route, which stays on its own route with a `full` key,\n * fail with 404 so no request reaches Core unchecked.\n */\nexport const parseOperations = ({\n method,\n path,\n searchParams,\n body,\n entityConfig,\n}: {\n method: string;\n path: string;\n searchParams: URLSearchParams;\n body: unknown;\n entityConfig?: ProxyEntityConfig;\n}): ParseResult => {\n // Core's router matches the raw path. A segment that decodes to contain\n // `/`, or an empty one, would be described as a different route than the\n // one Core runs, so neither is accepted.\n const decoded = (path === '/' ? [] : path.split('/').slice(1)).map(decode);\n if (decoded.some((segment) => !segment || segment.includes('/'))) {\n return invalid('Malformed path');\n }\n const [root, ...rest] = decoded as string[];\n const verb = method.toUpperCase();\n const payload = isRecord(body) ? body : undefined;\n const unknown = notFound(`Monorise Core has no route ${verb} ${path}`);\n const one = (operation: ProxyOperation): ParseResult => ({\n ok: true,\n operations: [operation],\n });\n // Present query parameters only, so operations stay comparable.\n const params = (...names: ('query' | 'group' | 'start' | 'end')[]) =>\n Object.fromEntries(\n names.flatMap((name) => {\n const value = searchParams.get(name);\n return value ? [[name, value]] : [];\n }),\n );\n\n if (root === 'entity') {\n const [entityType, second, third, fourth] = rest;\n if (rest.length === 1 && verb === 'GET') {\n return one({\n kind: 'entity',\n action: 'list',\n entityType,\n ...params('query', 'start', 'end'),\n });\n }\n if (rest.length === 1 && verb === 'POST') {\n const entityId =\n typeof payload?.entityId === 'string' ? payload.entityId : undefined;\n return {\n ok: true,\n operations: entityWrite(\n entityConfig,\n ['create'],\n entityType,\n entityId,\n payload,\n ),\n };\n }\n if (rest.length === 4 && second === 'unique' && verb === 'GET') {\n return one({\n kind: 'entity',\n action: 'get',\n entityType,\n unique: { field: third, value: fourth },\n });\n }\n if (rest.length === 3 && third === 'adjust' && verb === 'POST') {\n // As AdjustEntityController reads the body.\n const { $condition: condition, ...adjustments } = payload ?? {};\n return one({\n kind: 'entity',\n action: 'adjust',\n entityType,\n entityId: second,\n ...(payload === undefined\n ? {}\n : { adjustments: adjustments as Record<string, number> }),\n ...(typeof condition === 'string' ? { condition } : {}),\n });\n }\n if (rest.length === 2) {\n const write = (\n actions: ('create' | 'update')[],\n data = payload,\n condition?: string,\n ): ParseResult => ({\n ok: true,\n operations: entityWrite(\n entityConfig,\n actions,\n entityType,\n second,\n data,\n undefined,\n condition,\n ),\n });\n if (verb === 'GET') {\n return one({\n kind: 'entity',\n action: 'get',\n entityType,\n entityId: second,\n });\n }\n if (verb === 'PUT') return write(['create', 'update']);\n if (verb === 'PATCH') {\n // As UpdateEntityController reads the body: these aren't data.\n if (payload === undefined) return write(['update']);\n const { $condition: condition, $where: _, ...data } = payload;\n return write(\n ['update'],\n data,\n typeof condition === 'string' ? condition : undefined,\n );\n }\n if (verb === 'DELETE') {\n return one({\n kind: 'entity',\n action: 'delete',\n entityType,\n entityId: second,\n });\n }\n }\n return unknown;\n }\n\n if (root === 'mutual') {\n const [byEntityType, byEntityId, entityType, entityId] = rest;\n if (rest.length === 3 && verb === 'GET') {\n // A chain query reads every relationship along the chain. Only the\n // first hop's byEntityId is known before Core runs the query.\n const chain = searchParams.get('chainEntityQuery');\n const types = [\n byEntityType,\n ...(chain ? chain.split(',') : []),\n entityType,\n ];\n return {\n ok: true,\n operations: types.slice(1).map(\n (to, hop): RelationshipOperation => ({\n kind: 'relationship',\n action: 'read',\n byEntityType: types[hop],\n ...(hop === 0 ? { byEntityId } : {}),\n entityType: to,\n }),\n ),\n };\n }\n if (rest.length === 4) {\n const action: RelationshipAction | undefined =\n verb === 'GET'\n ? 'read'\n : verb === 'POST'\n ? 'create'\n : verb === 'PATCH'\n ? 'update'\n : verb === 'DELETE'\n ? 'delete'\n : undefined;\n if (action) {\n const relationship: RelationshipOperation = {\n kind: 'relationship',\n action,\n byEntityType,\n byEntityId,\n entityType,\n entityId,\n ...(payload === undefined || action === 'read' || action === 'delete'\n ? {}\n : { payload }),\n };\n return {\n ok: true,\n operations:\n action === 'create'\n ? // CreateMutualController passes ?asEntity= to the service.\n relationshipCreate(\n entityConfig,\n relationship,\n searchParams.get('asEntity') ?? undefined,\n )\n : [relationship],\n };\n }\n }\n return unknown;\n }\n\n if (root === 'tag' && rest.length === 2 && verb === 'GET') {\n return one({\n kind: 'entity',\n action: 'list',\n entityType: rest[0],\n tag: rest[1],\n ...params('group', 'start', 'end'),\n });\n }\n\n if (root === 'transaction' && rest.length === 0 && verb === 'POST') {\n return transactionOperations(entityConfig, body);\n }\n\n if (root === 'app') {\n return one({\n kind: 'route',\n method: verb,\n path: `/${decoded.join('/')}`,\n ...(body === undefined ? {} : { body }),\n });\n }\n\n return unknown;\n};\n","import type { Entity } from '@monorise/base';\nimport type {\n EntityAction,\n EntityOperation,\n ProxyOperation,\n RelationshipAction,\n RelationshipOperation,\n RouteOperation,\n} from './operations';\n\n/** Calls Monorise Core with the request's key, for checks such as \"is this record in my organization?\". */\nexport type CoreClient = {\n /** A path under `/core`, e.g. `/mutual/hirer-organization/h1/project/p1`. */\n get(path: string): Promise<Response>;\n fetch(path: string, init?: RequestInit): Promise<Response>;\n};\n\nexport type RuleContext<Session = unknown> = {\n /** What `authenticate` returned; `undefined` for an anonymous visitor. */\n session: Session | undefined;\n request: Request;\n core: CoreClient;\n};\n\n/**\n * `true` forwards the operation; `false` refuses it with 403; a `Response`\n * is sent back as is. Only `true` forwards, so a rule that forgets to return\n * fails closed.\n */\nexport type RuleResult = boolean | Response;\n\n/**\n * Decides whether this user may perform one operation. Write shared rules\n * as `ProxyRule<Session>`; under an entity or action, the operation is\n * narrowed to that entity type and action.\n */\nexport type ProxyRule<Session = unknown, Operation = ProxyOperation> = (\n operation: Operation,\n context: RuleContext<Session>,\n) => RuleResult | Promise<RuleResult>;\n\n/** A rule for operations that need no ownership check: the key alone decides. */\nexport const allow = (): RuleResult => true;\n\n/** A rule that always refuses. */\nexport const deny = (): RuleResult => false;\n\n// biome-ignore lint/suspicious/noExplicitAny: a rule written for any operation or session\ntype AnyRule = ProxyRule<any, any>;\n\ntype HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n// The entity types rules can name: the generated `Entity`, or any string\n// until `monorise dev` generates it.\ntype EntityName = keyof typeof Entity extends never ? string : Entity;\n\n// `'*'` stands for every action.\ntype ActionOf<Key, All> = Key extends All ? Key : All;\n\n/** Rules for one direction of a relationship, e.g. learner→course. */\nexport type RelationshipRules<\n Session = unknown,\n By extends string = string,\n To extends string = string,\n> =\n | ProxyRule<Session, RelationshipOperation<By, To>>\n | {\n [A in RelationshipAction | '*']?: ProxyRule<\n Session,\n RelationshipOperation<By, To, ActionOf<A, RelationshipAction>>\n >;\n };\n\ntype MutualsRules<Session, By extends string> = {\n /** Every relationship from this entity that has no entry. */\n '*'?:\n | ProxyRule<Session, RelationshipOperation<By, EntityName>>\n | {\n [A in RelationshipAction]?: ProxyRule<\n Session,\n RelationshipOperation<By, EntityName, A>\n >;\n };\n} & { [To in EntityName]?: RelationshipRules<Session, By, To> };\n\n/**\n * Rules for one entity type. A single rule covers every action on the entity\n * and its relationships. An object names actions, with `'*'` for the rest of\n * the entity's actions, and `mutuals` for relationships from it.\n */\nexport type EntityRules<Session = unknown, T extends string = string> =\n | ProxyRule<\n Session,\n EntityOperation<T> | RelationshipOperation<T, EntityName>\n >\n | ({\n [A in EntityAction | '*']?: ProxyRule<\n Session,\n EntityOperation<T, ActionOf<A, EntityAction>>\n >;\n } & { mutuals?: MutualsRules<Session, T> });\n\ntype TableRules<Session> =\n | ProxyRule<Session>\n | {\n [A in EntityAction | RelationshipAction]?: ProxyRule<\n Session,\n | (A extends EntityAction ? EntityOperation<string, A> : never)\n | (A extends RelationshipAction\n ? RelationshipOperation<string, string, A>\n : never)\n >;\n };\n\n// Before `Entity` is generated, every entry takes rules on any operation.\ntype UntypedRules<Session> =\n | ProxyRule<Session>\n | ({\n [A in EntityAction | RelationshipAction | '*']?: ProxyRule<Session>;\n } & {\n mutuals?: Record<\n string,\n | ProxyRule<Session>\n | { [A in RelationshipAction | '*']?: ProxyRule<Session> }\n >;\n });\n\n/**\n * Rules keyed by entity type. `'*'` applies to anything the table doesn't\n * name: a single rule for every operation, or rules per action.\n */\nexport type ProxyRules<Session = unknown> = string extends EntityName\n ? Record<string, UntypedRules<Session>>\n : { '*'?: TableRules<Session> } & {\n [T in EntityName]?: EntityRules<Session, T>;\n };\n\n/**\n * Rules for custom routes, keyed by `'METHOD /app/path'`. A `:param` segment\n * matches any one segment and a trailing `*` matches the rest; `'*'` applies\n * to every route the table doesn't name.\n */\nexport type RouteRules<Session = unknown> = {\n [K in `${HttpMethod} /app/${string}` | '*']?: ProxyRule<\n Session,\n RouteOperation\n >;\n};\n\nconst hasOwn = (object: object, key: string) =>\n Object.prototype.hasOwnProperty.call(object, key);\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst own = (object: unknown, key: string): unknown =>\n isRecord(object) && hasOwn(object, key) ? object[key] : undefined;\n\nconst asRule = (value: unknown): AnyRule | undefined =>\n typeof value === 'function' ? (value as AnyRule) : undefined;\n\n// A single rule, or the rule an object of rules names for this action.\nconst ruleFor = (value: unknown, action: string) =>\n asRule(value) ?? asRule(own(value, action));\n\ntype RouteMatch = { rule: AnyRule; params: Record<string, string> };\n\n// The first position where two ranks differ decides; a tie keeps the earlier.\nconst outranks = (rank: number[], than: number[]) => {\n const index = rank.findIndex((value, at) => value !== than[at]);\n return index !== -1 && rank[index] > than[index];\n};\n\n/**\n * The most specific route rule wins, whatever order the table lists them in:\n * more literal segments first, then a pattern without a trailing `*`, then\n * fewer `:param`s. Declaration order only breaks ties.\n */\nconst matchRoute = (\n routes: object | undefined,\n operation: RouteOperation,\n): RouteMatch | undefined => {\n if (!routes) return undefined;\n\n const exact = asRule(own(routes, `${operation.method} ${operation.path}`));\n if (exact) return { rule: exact, params: {} };\n\n const segments = operation.path.split('/').filter(Boolean);\n let best: { match: RouteMatch; rank: number[] } | undefined;\n for (const [key, rule] of Object.entries(routes)) {\n const [method, pattern] = key.split(' ');\n if (method !== operation.method || !pattern || typeof rule !== 'function') {\n continue;\n }\n const parts = pattern.split('/').filter(Boolean);\n const params: Record<string, string> = {};\n const rest = parts.at(-1) === '*';\n const fixed = rest ? parts.slice(0, -1) : parts;\n if (\n rest ? segments.length < fixed.length : segments.length !== fixed.length\n ) {\n continue;\n }\n const matches = fixed.every((part, index) => {\n if (part.startsWith(':')) {\n params[part.slice(1)] = segments[index];\n return true;\n }\n return part === segments[index];\n });\n if (!matches) continue;\n\n const paramCount = fixed.filter((part) => part.startsWith(':')).length;\n // Compared in order; a higher number is more specific.\n const rank = [fixed.length - paramCount, rest ? 0 : 1, -paramCount];\n if (!best || outranks(rank, best.rank)) {\n best = { match: { rule, params }, rank };\n }\n }\n return best?.match;\n};\n\n/**\n * Finds the rule for an operation. The most specific match wins:\n *\n * | Entity operation | Relationship operation | Route |\n * | `rules[entity][action]` | `rules[by].mutuals[target][action]` | `routes['METHOD /app/…']` |\n * | `rules[entity]['*']`, or `rules[entity]` as a single rule | `rules[by].mutuals[target]['*']`, then `rules[by].mutuals['*']`, or `rules[by]` as a single rule | `routes['*']` |\n * | `rules['*'][action]`, or `rules['*']` as a single rule | the same | `rules['*']` as a single rule |\n *\n * `undefined` means no rule: the operation is refused.\n */\nexport const findRule = (\n rules: object | undefined,\n routes: object | undefined,\n operation: ProxyOperation,\n): { rule: AnyRule; operation: ProxyOperation } | undefined => {\n const tableFallback = own(rules, '*');\n const found = (rule: AnyRule | undefined, matched = operation) =>\n rule ? { rule, operation: matched } : undefined;\n\n if (operation.kind === 'entity') {\n const entity = own(rules, operation.entityType);\n return found(\n asRule(entity) ??\n asRule(own(entity, operation.action)) ??\n asRule(own(entity, '*')) ??\n ruleFor(tableFallback, operation.action),\n );\n }\n\n if (operation.kind === 'relationship') {\n const entity = own(rules, operation.byEntityType);\n const mutuals = own(entity, 'mutuals');\n return found(\n asRule(entity) ??\n ruleFor(own(mutuals, operation.entityType), operation.action) ??\n asRule(own(own(mutuals, operation.entityType), '*')) ??\n ruleFor(own(mutuals, '*'), operation.action) ??\n ruleFor(tableFallback, operation.action),\n );\n }\n\n const route = matchRoute(routes, operation);\n if (route) return found(route.rule, { ...operation, params: route.params });\n return found(asRule(own(routes, '*')) ?? asRule(tableFallback));\n};\n\n/** How a refusal names an operation, e.g. `delete on 'hirer-schedule'`. */\nexport const describeOperation = (operation: ProxyOperation) =>\n operation.kind === 'entity'\n ? `${operation.action} on '${operation.entityType}'`\n : operation.kind === 'relationship'\n ? `${operation.action} on ${operation.byEntityType}→${operation.entityType}`\n : `${operation.method} ${operation.path}`;\n\n// The rule to add, shaped for the operation, logged when one is missing.\nconst missingRuleHint = (operation: ProxyOperation) =>\n operation.kind === 'entity'\n ? `rules: { '${operation.entityType}': { ${operation.action}: (operation, { session }) => … } }`\n : operation.kind === 'relationship'\n ? `rules: { '${operation.byEntityType}': { mutuals: { '${operation.entityType}': { ${operation.action}: (operation, { session }) => … } } } }`\n : `routes: { '${operation.method} ${operation.path}': (operation, { session }) => … }`;\n\nconst forbidden = (message: string, operation: ProxyOperation) =>\n new Response(\n JSON.stringify({\n code: 'FORBIDDEN',\n message,\n ...('operationIndex' in operation &&\n operation.operationIndex !== undefined\n ? { operationIndex: operation.operationIndex }\n : {}),\n }),\n { status: 403, headers: { 'content-type': 'application/json' } },\n );\n\n/** A callback of the app's threw: refused, since nothing was checked. */\nexport const proxyError = (message: string, operation?: ProxyOperation) =>\n new Response(\n JSON.stringify({\n code: 'PROXY_ERROR',\n message,\n ...(operation &&\n 'operationIndex' in operation &&\n operation.operationIndex !== undefined\n ? { operationIndex: operation.operationIndex }\n : {}),\n }),\n { status: 500, headers: { 'content-type': 'application/json' } },\n );\n\n/**\n * Runs the rule for every operation, in order, and stops at the first\n * refusal. `undefined` means every operation may go ahead.\n */\nexport const checkOperations = async <Session>({\n operations,\n rules,\n routes,\n context,\n logMissingRules = false,\n}: {\n operations: ProxyOperation[];\n rules?: ProxyRules<Session>;\n routes?: RouteRules<Session>;\n context: RuleContext<Session>;\n logMissingRules?: boolean;\n}): Promise<Response | undefined> => {\n for (const operation of operations) {\n const found = findRule(rules, routes, operation);\n if (!found) {\n if (logMissingRules) {\n console.warn(\n `[monorise/proxy] No rule for ${describeOperation(operation)}. Add one: ${missingRuleHint(operation)}`,\n );\n }\n return forbidden(\n `No proxy rule for ${describeOperation(operation)}`,\n operation,\n );\n }\n\n let result: RuleResult;\n try {\n result = await found.rule(found.operation, context);\n } catch (error) {\n const what = `The rule for ${describeOperation(operation)}`;\n console.error(`[monorise/proxy] ${what} threw`, error);\n return proxyError(`${what} threw`, operation);\n }\n if (result instanceof Response) return result;\n if (result !== true) {\n return forbidden(\n `Proxy rule refused ${describeOperation(operation)}`,\n operation,\n );\n }\n }\n return undefined;\n};\n","import {\n type ProxyEntityConfig,\n type ProxyOperation,\n parseOperations,\n} from './operations';\nimport {\n type CoreClient,\n type ProxyRules,\n type RouteRules,\n type RuleContext,\n checkOperations,\n proxyError,\n} from './rules';\n\n/** One kind of caller: the key it calls Core with, and the rules for its users. */\nexport type ProxyCaller<Session = unknown> = {\n /** A key in `API_KEYS`, usually mapped to a policy for this kind of caller. */\n apiKey: string | undefined;\n rules?: ProxyRules<Session>;\n routes?: RouteRules<Session>;\n};\n\ntype AuthenticateResult<Session> = Session | null | undefined | Response;\n\ntype SharedOptions<Session> = {\n /** The generated config, which says which payload fields are relationships. */\n config: { EntityConfig: ProxyEntityConfig };\n /**\n * Reads the session. `undefined` or `null` is an anonymous visitor; a\n * `Response`, such as a 401 that clears an expired cookie, is sent back as is.\n */\n authenticate?: (\n request: Request,\n ) => AuthenticateResult<Session> | Promise<AuthenticateResult<Session>>;\n /** The prefix stripped before forwarding. Defaults to `/api/core`. */\n basePath?: string;\n /** Core's URL. Defaults to `process.env.API_BASE_URL`. */\n apiBaseUrl?: string;\n /** Logs the rule to add when none matches. Defaults to on outside production. */\n logMissingRules?: boolean;\n};\n\nexport type ProxyHandlerOptions<Session = unknown> = SharedOptions<Session> &\n (\n | {\n /** Names the kind of caller for this request; `undefined` answers 401. */\n caller: (args: {\n session: Session | undefined;\n request: Request;\n }) => string | undefined | Promise<string | undefined>;\n callers: Record<string, ProxyCaller<Session>>;\n apiKey?: never;\n rules?: never;\n routes?: never;\n }\n | ({ caller?: never; callers?: never } & ProxyCaller<Session>)\n );\n\nexport type CheckResult<Session = unknown> =\n | {\n allowed: true;\n /** The kind of caller, or `undefined` for an app with one kind. */\n caller: string | undefined;\n session: Session | undefined;\n operations: ProxyOperation[];\n }\n | { allowed: false; response: Response };\n\ntype RequestHandler = (request: Request) => Promise<Response>;\n\nexport type ProxyHandler<Session = unknown> = {\n /** Checks a request to Core and forwards it, or answers with the refusal. */\n handle: RequestHandler;\n /** Runs every step but forwarding, so rules can be unit-tested. */\n checkRequest: (request: Request) => Promise<CheckResult<Session>>;\n GET: RequestHandler;\n POST: RequestHandler;\n PUT: RequestHandler;\n PATCH: RequestHandler;\n DELETE: RequestHandler;\n};\n\nconst FORWARDED_HEADERS = [\n 'content-type',\n 'accept',\n 'accept-language',\n 'x-request-id',\n];\n\n// fetch has already decoded the body and framed it for this hop.\nconst DROPPED_RESPONSE_HEADERS = [\n 'content-encoding',\n 'content-length',\n 'transfer-encoding',\n 'connection',\n];\n\nconst hasOwn = (object: object, key: string) =>\n Object.prototype.hasOwnProperty.call(object, key);\n\nconst env = (name: string) =>\n typeof process === 'undefined' ? undefined : process.env?.[name];\n\nconst json = (status: number, body: Record<string, unknown>) =>\n new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json' },\n });\n\n// Responses depend on who is asking, so no shared cache, such as a CDN in\n// front of the app, may keep one for the next user of the same URL.\nconst NO_STORE = 'private, no-store';\n\nconst withNoStore = (response: Response) => {\n if (response.headers.has('cache-control')) return response;\n const headers = new Headers(response.headers);\n headers.set('cache-control', NO_STORE);\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n};\n\n// A callback of the app's threw before anything was checked or forwarded.\nconst callbackThrew = (what: string, error: unknown) => {\n console.error(`[monorise/proxy] ${what} threw`, error);\n return proxyError(`${what} threw`);\n};\n\nconst unauthorized = () =>\n json(401, { code: 'UNAUTHORIZED', message: 'Unauthorized' });\n\nconst misconfigured = (message: string) => {\n console.error(`[monorise/proxy] ${message}`);\n return json(500, { code: 'PROXY_MISCONFIGURED', message });\n};\n\ntype Prepared<Session> = {\n caller: string | undefined;\n session: Session | undefined;\n apiKey: string;\n apiBaseUrl: string;\n /** The path under `/core`, as the client encoded it, with its query. */\n target: string;\n body: ArrayBuffer | undefined;\n operations: ProxyOperation[];\n};\n\n/**\n * Puts Monorise Core behind your app's own route. Each request is checked\n * against the rules for its kind of caller, then forwarded with that\n * caller's key: the key decides what the caller can reach, and the rules\n * decide whose records.\n *\n * @example\n * ```ts\n * const proxy = createProxyHandler({\n * config,\n * authenticate: (request) => readSession(request),\n * caller: ({ session }) => session?.type ?? 'public',\n * callers: {\n * hirer: { apiKey: process.env.HIRER_API_KEY, rules: hirerRules },\n * public: { apiKey: process.env.PUBLIC_API_KEY, rules: publicRules },\n * },\n * });\n *\n * export const { GET, POST, PUT, PATCH, DELETE } = proxy;\n * ```\n */\nexport const createProxyHandler = <Session = unknown>(\n options: ProxyHandlerOptions<Session>,\n): ProxyHandler<Session> => {\n const multiple =\n options.callers !== undefined || options.caller !== undefined;\n if (\n multiple &&\n (typeof options.caller !== 'function' ||\n typeof options.callers !== 'object' ||\n options.apiKey !== undefined ||\n options.rules !== undefined ||\n options.routes !== undefined)\n ) {\n throw new Error(\n 'createProxyHandler takes either caller and callers, or apiKey and rules',\n );\n }\n\n const basePath = `/${(options.basePath ?? '/api/core').replace(/^\\/+|\\/+$/g, '')}`;\n const entityConfig = options.config?.EntityConfig;\n const logMissingRules =\n options.logMissingRules ?? env('NODE_ENV') !== 'production';\n\n const coreClient = (apiBaseUrl: string, apiKey: string): CoreClient => {\n const coreFetch = (path: string, init: RequestInit = {}) => {\n const headers = new Headers(init.headers);\n headers.set('x-api-key', apiKey);\n return fetch(`${apiBaseUrl}/core${path}`, {\n cache: 'no-store',\n ...init,\n headers,\n });\n };\n return { get: (path) => coreFetch(path), fetch: coreFetch };\n };\n\n const prepare = async (\n request: Request,\n ): Promise<Prepared<Session> | Response> => {\n // Read from a copy, so authenticate and rules can still read the request.\n const body =\n request.method === 'GET' || request.method === 'HEAD'\n ? undefined\n : await request.clone().arrayBuffer();\n\n // 1. Authenticate\n let authenticated: Session | null | undefined | Response;\n try {\n authenticated = options.authenticate\n ? await options.authenticate(request)\n : undefined;\n } catch (error) {\n return callbackThrew('authenticate', error);\n }\n if (authenticated instanceof Response) return authenticated;\n const session = authenticated ?? undefined;\n\n // 2. Choose the caller\n let caller: string | undefined;\n let entry: ProxyCaller<Session> | undefined;\n if (multiple) {\n try {\n caller = await options.caller?.({ session, request });\n } catch (error) {\n return callbackThrew('caller', error);\n }\n const callers = options.callers ?? {};\n entry =\n caller !== undefined && hasOwn(callers, caller)\n ? callers[caller]\n : undefined;\n } else if (!options.authenticate || session !== undefined) {\n entry = options;\n }\n if (!entry) return unauthorized();\n if (!entry.apiKey) {\n return misconfigured(\n caller === undefined\n ? 'No apiKey is set'\n : `No apiKey is set for caller '${caller}'`,\n );\n }\n const apiBaseUrl = (options.apiBaseUrl ?? env('API_BASE_URL'))?.replace(\n /\\/+$/,\n '',\n );\n if (!apiBaseUrl) {\n return misconfigured('No apiBaseUrl is set, and API_BASE_URL is empty');\n }\n\n // 3. Parse into operations\n const url = new URL(request.url);\n if (url.pathname !== basePath && !url.pathname.startsWith(`${basePath}/`)) {\n return json(404, {\n code: 'NOT_FOUND',\n message: `The proxy serves paths under ${basePath}`,\n });\n }\n const path = url.pathname.slice(basePath.length) || '/';\n const text = body ? new TextDecoder().decode(body) : '';\n let parsed: unknown;\n if (text.trim()) {\n try {\n parsed = JSON.parse(text);\n } catch {\n // Custom routes may take other bodies; their rules see none.\n if (!path.startsWith('/app/')) {\n return json(400, {\n code: 'BAD_REQUEST',\n message: 'Request body must be JSON',\n });\n }\n }\n }\n const result = parseOperations({\n method: request.method,\n path,\n searchParams: url.searchParams,\n body: parsed,\n entityConfig,\n });\n if (!result.ok) {\n return json(result.status, {\n code: result.status === 404 ? 'NOT_FOUND' : 'BAD_REQUEST',\n message: result.message,\n });\n }\n\n // 4. Check rules\n const context: RuleContext<Session> = {\n session,\n request,\n core: coreClient(apiBaseUrl, entry.apiKey),\n };\n const refusal = await checkOperations({\n operations: result.operations,\n rules: entry.rules,\n routes: entry.routes,\n context,\n logMissingRules,\n });\n if (refusal) return refusal;\n\n return {\n caller,\n session,\n apiKey: entry.apiKey,\n apiBaseUrl,\n target: `${path}${url.search}`,\n body: body && body.byteLength > 0 ? body : undefined,\n operations: result.operations,\n };\n };\n\n const checkRequest = async (\n request: Request,\n ): Promise<CheckResult<Session>> => {\n const prepared = await prepare(request);\n if (prepared instanceof Response) {\n return { allowed: false, response: withNoStore(prepared) };\n }\n const { caller, session, operations } = prepared;\n return { allowed: true, caller, session, operations };\n };\n\n const handle = async (request: Request): Promise<Response> =>\n withNoStore(await forward(request));\n\n const forward = async (request: Request): Promise<Response> => {\n const prepared = await prepare(request);\n if (prepared instanceof Response) return prepared;\n\n // 5. Forward, with only the headers Core needs and the caller's key\n const headers = new Headers();\n for (const name of FORWARDED_HEADERS) {\n const value = request.headers.get(name);\n if (value !== null) headers.set(name, value);\n }\n headers.set('x-api-key', prepared.apiKey);\n\n let response: Response;\n try {\n response = await fetch(`${prepared.apiBaseUrl}/core${prepared.target}`, {\n method: request.method,\n headers,\n body: prepared.body,\n cache: 'no-store',\n });\n } catch (error) {\n console.error('[monorise/proxy] Monorise Core is unreachable', error);\n return json(502, {\n code: 'BAD_GATEWAY',\n message: 'Monorise Core is unreachable',\n });\n }\n\n // 6. Respond with Core's status and body\n const responseHeaders = new Headers(response.headers);\n for (const name of DROPPED_RESPONSE_HEADERS) responseHeaders.delete(name);\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n });\n };\n\n const alias: RequestHandler = (request) => handle(request);\n return {\n handle,\n checkRequest,\n GET: alias,\n POST: alias,\n PUT: alias,\n PATCH: alias,\n DELETE: alias,\n };\n};\n","import type { Entity } from '@monorise/base';\n\ninterface GenerateTicketOptions {\n entityType: Entity;\n entityId: string;\n feedTypes?: Entity[];\n}\n\ninterface TicketResponse {\n ticket: string;\n wsUrl: string;\n expiresIn: number;\n}\n\nconst getApiBaseUrl = (): string => {\n const url = process.env.API_BASE_URL;\n if (!url) {\n throw new Error(\n 'API_BASE_URL environment variable is required for generateWebSocketTicket',\n );\n }\n return url;\n};\n\nconst getApiKey = (): string => {\n return process.env.MONORISE_API_KEY || process.env.API_KEY || '';\n};\n\n/**\n * Generate a WebSocket ticket for entity feed subscriptions.\n * Call this from your proxy route (e.g., Next.js API route) after validating auth.\n *\n * @example\n * ```ts\n * import { generateWebSocketTicket } from 'monorise/proxy';\n * import { Entity } from './monorise/entities';\n *\n * export async function POST(req) {\n * const session = await getSession(req);\n * const ticket = await generateWebSocketTicket({\n * entityType: Entity.USER,\n * entityId: session.userId,\n * feedTypes: [Entity.CHANNEL, Entity.MESSAGE],\n * });\n * return Response.json(ticket);\n * }\n * ```\n */\nexport const generateWebSocketTicket = async (\n options: GenerateTicketOptions,\n): Promise<TicketResponse> => {\n const apiBaseUrl = getApiBaseUrl();\n const apiKey = getApiKey();\n\n const { entityType, entityId, feedTypes } = options;\n\n const response = await fetch(\n // `/core` is monorise's own Hono basePath (packages/core/handles/app.ts),\n // not part of API_BASE_URL -- the React default endpoint spells the same\n // path as `/api/core/ws/ticket/...`.\n `${apiBaseUrl}/core/ws/ticket/${entityType}/${entityId}`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(apiKey && { 'x-api-key': apiKey }),\n },\n body: JSON.stringify({\n ...(feedTypes && { feedTypes }),\n }),\n },\n );\n\n if (!response.ok) {\n throw new Error(\n `Failed to generate WebSocket ticket: ${response.status} ${response.statusText}`,\n );\n }\n\n return response.json() as Promise<TicketResponse>;\n};\n\nexport {\n type CheckResult,\n type ProxyCaller,\n type ProxyHandler,\n type ProxyHandlerOptions,\n createProxyHandler,\n} from './proxy/handler';\nexport type {\n EntityAction,\n EntityOperation,\n ProxyEntityConfig,\n ProxyOperation,\n RelationshipAction,\n RelationshipOperation,\n RouteOperation,\n} from './proxy/operations';\nexport {\n type CoreClient,\n type EntityRules,\n type ProxyRule,\n type ProxyRules,\n type RelationshipRules,\n type RouteRules,\n type RuleContext,\n type RuleResult,\n allow,\n deny,\n} from './proxy/rules';\n"],"mappings":";AA+JA,IAAM,SAAS,CAAC,QAAgB,QAC9B,OAAO,UAAU,eAAe,KAAK,QAAQ,GAAG;AAElD,IAAM,WAAW,CAAC,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAErE,IAAM,WAAW,CAAC,aAAkC;AAAA,EAClD,IAAI;AAAA,EACJ,QAAQ;AA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