@nest-my-admin/core 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -2
- package/dist/api/action.service.js +24 -6
- package/dist/api/admin-api.service.js +38 -16
- package/dist/appearance/appearance.service.d.ts +28 -0
- package/dist/appearance/appearance.service.js +63 -0
- package/dist/audit/audit-reader.js +3 -2
- package/dist/auth/auth.service.js +9 -1
- package/dist/contract.d.ts +6 -1
- package/dist/crud/computed-columns.js +9 -0
- package/dist/dashboard/dashboard.service.js +2 -1
- package/dist/dashboard/widget-data.d.ts +8 -0
- package/dist/dashboard/widget-data.js +55 -0
- package/dist/decorators/admin-action.d.ts +29 -5
- package/dist/decorators/admin-action.js +50 -14
- package/dist/decorators/admin-print.d.ts +4 -1
- package/dist/decorators/admin-print.js +0 -6
- package/dist/decorators/admin-resource.d.ts +6 -2
- package/dist/decorators/admin-scope.d.ts +5 -2
- package/dist/decorators/admin-scope.js +0 -6
- package/dist/decorators/admin-settings-page.d.ts +2 -1
- package/dist/decorators/admin-widget.d.ts +2 -1
- package/dist/decorators/hooks.d.ts +11 -6
- package/dist/decorators/hooks.js +3 -3
- package/dist/decorators/typed.d.ts +20 -0
- package/dist/decorators/typed.js +2 -0
- package/dist/files/file-owner.js +2 -1
- package/dist/host-contract.d.ts +30 -0
- package/dist/host-contract.js +91 -0
- package/dist/http/admin-http.server.js +34 -5
- package/dist/http/error-response.js +4 -0
- package/dist/http/http-io.d.ts +2 -0
- package/dist/http/http-io.js +19 -1
- package/dist/http/ui-assets.d.ts +15 -2
- package/dist/http/ui-assets.js +29 -3
- package/dist/i18n/texts.js +9 -3
- package/dist/index.d.ts +2 -1
- package/dist/inlines/inline-reader.js +3 -2
- package/dist/inlines/inline-writer.js +3 -2
- package/dist/options.js +23 -1
- package/dist/pages/page-registry.js +3 -2
- package/dist/policy/admin-policy.service.js +30 -11
- package/dist/policy/explain.js +3 -2
- package/dist/rbac/rbac-routes.js +2 -1
- package/dist/registry/resource-registry.js +1 -1
- package/dist/resource/admin-resource-base.js +16 -5
- package/dist/resource/admin-source-base.d.ts +2 -0
- package/package.json +2 -2
|
@@ -2,8 +2,10 @@ import 'reflect-metadata';
|
|
|
2
2
|
import type { ActionSchema } from '../contract.js';
|
|
3
3
|
import { type LocalizedText } from '../i18n/localized-text.js';
|
|
4
4
|
import { type DtoForm } from '../schema/dto-form.js';
|
|
5
|
-
import type
|
|
5
|
+
import { type DtoClass } from '../schema/dto-fields.js';
|
|
6
6
|
import type { ScopedText } from '../i18n/texts.js';
|
|
7
|
+
import type { AdminContext } from '../resource/admin-context.js';
|
|
8
|
+
import type { Awaitable, RecordMethodDecorator, TypedMethodDecorator } from './typed.js';
|
|
7
9
|
export interface AdminActionOptions {
|
|
8
10
|
/**
|
|
9
11
|
* `'Mark shipped'` or `{ en: 'Mark shipped', fa: 'ارسال شد' }`. Defaults to the humanized method name. A label per
|
|
@@ -38,14 +40,18 @@ export interface AdminActionOptions {
|
|
|
38
40
|
/**
|
|
39
41
|
* A DTO for a form in the dialog. It is validated like a write (whitelist, class-validator) before the method
|
|
40
42
|
* runs; `@AdminField` on its properties sets labels, help and widgets. Files and rich text are not supported.
|
|
43
|
+
* Left out, the class of the method's input parameter is used (it needs `emitDecoratorMetadata`); `false` says
|
|
44
|
+
* the action takes no input, where the parameter types cannot be read.
|
|
41
45
|
*/
|
|
42
|
-
input?: DtoClass;
|
|
46
|
+
input?: DtoClass | false;
|
|
43
47
|
icon?: string;
|
|
44
48
|
}
|
|
45
49
|
/** What an action method may return: a message for the person who ran it. */
|
|
46
50
|
export interface ActionOutcome {
|
|
47
51
|
message?: LocalizedText;
|
|
48
52
|
}
|
|
53
|
+
/** What an action method returns: nothing, or an `ActionOutcome`. */
|
|
54
|
+
export type ActionReturn = ActionOutcome | void | null | undefined;
|
|
49
55
|
/** An `@AdminAction` as declared. `name` is the method name: the URL segment and the `{resource}.action.{name}` code. */
|
|
50
56
|
export interface ActionDefinition extends AdminActionOptions {
|
|
51
57
|
name: string;
|
|
@@ -74,13 +80,31 @@ export interface RegisteredAction {
|
|
|
74
80
|
* wrote is undone when it throws, and `atomic` actions are refused at boot. Throw an `HttpException` (or
|
|
75
81
|
* `AdminFieldError` for input fields) to refuse.
|
|
76
82
|
*/
|
|
77
|
-
export declare function AdminAction(options
|
|
83
|
+
export declare function AdminAction<I extends object>(options: AdminActionOptions & {
|
|
84
|
+
target: 'resource';
|
|
85
|
+
input: new (...args: any[]) => I;
|
|
86
|
+
}): TypedMethodDecorator<(input: I, ctx: AdminContext) => Awaitable<ActionReturn>>;
|
|
87
|
+
export declare function AdminAction(options: AdminActionOptions & {
|
|
88
|
+
target: 'resource';
|
|
89
|
+
}): TypedMethodDecorator<(input: any, ctx: AdminContext) => Awaitable<ActionReturn>>;
|
|
90
|
+
export declare function AdminAction<I extends object>(options: AdminActionOptions & {
|
|
91
|
+
target?: 'record';
|
|
92
|
+
input: new (...args: any[]) => I;
|
|
93
|
+
}): RecordMethodDecorator<[input: I, ctx: AdminContext], Awaitable<ActionReturn>>;
|
|
94
|
+
export declare function AdminAction(options?: AdminActionOptions & {
|
|
95
|
+
target?: 'record';
|
|
96
|
+
}): RecordMethodDecorator<[input: any, ctx: AdminContext], Awaitable<ActionReturn>>;
|
|
97
|
+
export declare function AdminAction(options?: AdminActionOptions): TypedMethodDecorator<(...args: any[]) => Awaitable<ActionReturn>>;
|
|
78
98
|
/** The actions declared on a resource class (inherited ones first), by name. */
|
|
79
99
|
export declare function getActions(resourceClass: Function): Map<string, ActionDefinition>;
|
|
80
100
|
/**
|
|
81
101
|
* Boot-time checks of a resource class's actions and of its `@AdminCan` names; returns the actions ready to run.
|
|
82
|
-
* `reserved` are the method names of `AdminResourceBase`, which an action must not take over
|
|
102
|
+
* `reserved` are the method names of `AdminResourceBase`, which an action must not take over; `row` is the class of
|
|
103
|
+
* the records (the entity, or a source's row), checked against a record action's first parameter.
|
|
104
|
+
*
|
|
105
|
+
* The method's parameter types (when the build emits them: tsc, SWC, Bun; not esbuild or Vite) are checked against the
|
|
106
|
+
* action: `input` must be the class of its input parameter, and an action without `input` takes it from that parameter.
|
|
83
107
|
*/
|
|
84
|
-
export declare function resolveActions(resourceClass: Function, reserved: readonly string[], fail: (message: string) => never): Map<string, RegisteredAction>;
|
|
108
|
+
export declare function resolveActions(resourceClass: Function, reserved: readonly string[], fail: (message: string) => never, row?: Function): Map<string, RegisteredAction>;
|
|
85
109
|
/** The action as one request gets it, texts through `text` (keys `actions.<name>.…` of the resource). */
|
|
86
110
|
export declare function toActionSchema(action: RegisteredAction, text: ScopedText): ActionSchema;
|
|
@@ -1,17 +1,11 @@
|
|
|
1
1
|
import 'reflect-metadata';
|
|
2
2
|
import { ADMIN_ACTIONS_METADATA } from '../constants.js';
|
|
3
3
|
import { buildDtoForm, localizeDtoForm } from '../schema/dto-form.js';
|
|
4
|
+
import { dtoPropertyNames } from '../schema/dto-fields.js';
|
|
5
|
+
import { describeValue, HostContractError, isLocalizedText } from '../host-contract.js';
|
|
4
6
|
import { humanize } from '../schema/humanize.js';
|
|
5
7
|
import { didYouMean } from '../schema/suggest.js';
|
|
6
8
|
import { getCanRuleNames } from './admin-scope.js';
|
|
7
|
-
/**
|
|
8
|
-
* A custom action of a resource (spec §5.2): a button on a record, on a list selection (`bulk`) or on the list
|
|
9
|
-
* (`target: 'resource'`). The method name is the action's name; running it needs `{resource}.action.{name}`, and for
|
|
10
|
-
* record actions `{resource}.update`, the user's row scopes and any `@AdminCan('<name>')` rule. It runs inside the
|
|
11
|
-
* admin's write transaction (`ctx.manager`), unless the admin runs with `transactions: false`: then nothing a method
|
|
12
|
-
* wrote is undone when it throws, and `atomic` actions are refused at boot. Throw an `HttpException` (or
|
|
13
|
-
* `AdminFieldError` for input fields) to refuse.
|
|
14
|
-
*/
|
|
15
9
|
export function AdminAction(options = {}) {
|
|
16
10
|
return (target, propertyKey) => {
|
|
17
11
|
if (typeof propertyKey !== 'string')
|
|
@@ -33,7 +27,19 @@ const UPLOAD_WIDGETS = ['file', 'image', 'richtext'];
|
|
|
33
27
|
* Boot-time checks of a resource class's actions and of its `@AdminCan` names; returns the actions ready to run.
|
|
34
28
|
* `reserved` are the method names of `AdminResourceBase`, which an action must not take over.
|
|
35
29
|
*/
|
|
36
|
-
|
|
30
|
+
/** A class the method's parameter was declared as (emitted with `emitDecoratorMetadata`); not `Object` (an interface, `any`) or a built-in. */
|
|
31
|
+
const BUILT_INS = [Object, String, Number, Boolean, Array, Promise, Function, Date, Map, Set];
|
|
32
|
+
const declaredClass = (type) => (typeof type === 'function' && !BUILT_INS.includes(type) ? type : undefined);
|
|
33
|
+
const related = (a, b) => a === b || a.prototype instanceof b || b.prototype instanceof a;
|
|
34
|
+
/**
|
|
35
|
+
* Boot-time checks of a resource class's actions and of its `@AdminCan` names; returns the actions ready to run.
|
|
36
|
+
* `reserved` are the method names of `AdminResourceBase`, which an action must not take over; `row` is the class of
|
|
37
|
+
* the records (the entity, or a source's row), checked against a record action's first parameter.
|
|
38
|
+
*
|
|
39
|
+
* The method's parameter types (when the build emits them: tsc, SWC, Bun; not esbuild or Vite) are checked against the
|
|
40
|
+
* action: `input` must be the class of its input parameter, and an action without `input` takes it from that parameter.
|
|
41
|
+
*/
|
|
42
|
+
export function resolveActions(resourceClass, reserved, fail, row) {
|
|
37
43
|
const actions = new Map();
|
|
38
44
|
for (const definition of getActions(resourceClass).values()) {
|
|
39
45
|
const { name } = definition;
|
|
@@ -56,7 +62,30 @@ export function resolveActions(resourceClass, reserved, fail) {
|
|
|
56
62
|
fail(`${where}: \`bulk\` and \`atomic\` are for record actions`);
|
|
57
63
|
if (atomic && !bulk)
|
|
58
64
|
fail(`${where}: \`atomic\` needs \`bulk: true\``);
|
|
59
|
-
const { confirm,
|
|
65
|
+
const { confirm, icon, label } = definition;
|
|
66
|
+
const noInput = definition.input === false;
|
|
67
|
+
let input = definition.input === false ? undefined : definition.input;
|
|
68
|
+
const params = Reflect.getMetadata('design:paramtypes', resourceClass.prototype, name);
|
|
69
|
+
const method = resourceClass.prototype[name];
|
|
70
|
+
const takesInput = typeof method === 'function' && method.length > (target === 'record' ? 1 : 0);
|
|
71
|
+
if (params === undefined && input === undefined && !noInput && takesInput) {
|
|
72
|
+
fail(`${where}: the method takes an input parameter, but its type cannot be read (emitDecoratorMetadata is off, or the build drops it: esbuild, Vite, tsx); set \`input\` to its DTO class, or \`input: false\` if it takes none`);
|
|
73
|
+
}
|
|
74
|
+
const recordParam = target === 'record' ? declaredClass(params?.[0]) : undefined;
|
|
75
|
+
if (recordParam && row && !related(recordParam, row))
|
|
76
|
+
fail(`${where}: the method's first parameter is ${recordParam.name}, but the action runs on ${row.name} records`);
|
|
77
|
+
const inputParam = declaredClass(params?.[target === 'record' ? 1 : 0]);
|
|
78
|
+
const inputLike = inputParam !== undefined && inputParam !== row && dtoPropertyNames(inputParam).length > 0;
|
|
79
|
+
if (input !== undefined && typeof input === 'function' && inputParam && inputParam !== input && !(input.prototype instanceof inputParam)) {
|
|
80
|
+
fail(`${where}: \`input\` is ${input.name} but the method's input parameter is ${inputParam.name}; use the same class (or leave \`input\` out to take the parameter's)`);
|
|
81
|
+
}
|
|
82
|
+
if (noInput && inputLike)
|
|
83
|
+
fail(`${where}: \`input: false\`, but the method's input parameter is ${inputParam.name}`);
|
|
84
|
+
if (input === undefined && !noInput && inputLike) {
|
|
85
|
+
if (definition.primary === true)
|
|
86
|
+
fail(`${where}: a primary action runs in one click and takes no input, but the method's input parameter is ${inputParam.name}`);
|
|
87
|
+
input = inputParam;
|
|
88
|
+
}
|
|
60
89
|
if (confirm !== undefined && typeof confirm !== 'boolean' && !isText(confirm))
|
|
61
90
|
fail(`${where}: confirm must be true, false or a text`);
|
|
62
91
|
const perRecord = typeof label === 'object' && label !== null && 'for' in label;
|
|
@@ -90,7 +119,7 @@ export function resolveActions(resourceClass, reserved, fail) {
|
|
|
90
119
|
actions.set(name, {
|
|
91
120
|
name,
|
|
92
121
|
label: perRecord ? label.static : (label ?? humanize(name)),
|
|
93
|
-
...(perRecord ? { labelFor: label.for } : {}),
|
|
122
|
+
...(perRecord ? { labelFor: checkedLabelFor(`${resourceClass.name} @AdminAction "${name}" label.for`, label.for) } : {}),
|
|
94
123
|
primary,
|
|
95
124
|
target,
|
|
96
125
|
bulk,
|
|
@@ -118,9 +147,7 @@ export function resolveActions(resourceClass, reserved, fail) {
|
|
|
118
147
|
return actions;
|
|
119
148
|
}
|
|
120
149
|
function isText(value) {
|
|
121
|
-
|
|
122
|
-
return true;
|
|
123
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value) && Object.values(value).every((text) => typeof text === 'string');
|
|
150
|
+
return isLocalizedText(value);
|
|
124
151
|
}
|
|
125
152
|
/** The action as one request gets it, texts through `text` (keys `actions.<name>.…` of the resource). */
|
|
126
153
|
export function toActionSchema(action, text) {
|
|
@@ -139,4 +166,13 @@ export function toActionSchema(action, text) {
|
|
|
139
166
|
...(action.form ? { input: localizeDtoForm(action.form, (value, path) => text(value, `${at}.fields.${path}`)) } : {}),
|
|
140
167
|
};
|
|
141
168
|
}
|
|
169
|
+
/** `label.for` as called: a text, or `null` (not on this record); anything else (a Promise of an `async` one) fails loudly. */
|
|
170
|
+
function checkedLabelFor(where, labelFor) {
|
|
171
|
+
return (record) => {
|
|
172
|
+
const value = labelFor(record);
|
|
173
|
+
if (value !== null && !isLocalizedText(value))
|
|
174
|
+
throw new HostContractError(`${where} returned ${describeValue(value)}; it answers at once with a text, or null where the action does not apply (it cannot be async)`);
|
|
175
|
+
return value;
|
|
176
|
+
};
|
|
177
|
+
}
|
|
142
178
|
//# sourceMappingURL=admin-action.js.map
|
|
@@ -2,6 +2,9 @@ import 'reflect-metadata';
|
|
|
2
2
|
import type { PrintSchema } from '../contract.js';
|
|
3
3
|
import { type LocalizedText } from '../i18n/localized-text.js';
|
|
4
4
|
import type { ScopedText } from '../i18n/texts.js';
|
|
5
|
+
import type { HtmlString } from '../print/html.js';
|
|
6
|
+
import type { AdminContext } from '../resource/admin-context.js';
|
|
7
|
+
import type { Awaitable, RowOf } from './typed.js';
|
|
5
8
|
/** Paper sizes by name; any other string is used as the CSS `@page { size }` value. */
|
|
6
9
|
export declare const PAPERS: Record<string, string>;
|
|
7
10
|
export interface AdminPrintOptions {
|
|
@@ -28,7 +31,7 @@ export interface RegisteredPrint {
|
|
|
28
31
|
* wraps it in a page sized for `paper` that prints itself. Printing needs `{resource}.view`, the user's row scopes and
|
|
29
32
|
* `{resource}.print.{name}`; each printed record is written to the audit log. Throw an `HttpException` to refuse.
|
|
30
33
|
*/
|
|
31
|
-
export declare function AdminPrint(options?: AdminPrintOptions):
|
|
34
|
+
export declare function AdminPrint(options?: AdminPrintOptions): <P extends object, T extends (records: Array<RowOf<P>>, ctx: AdminContext) => Awaitable<HtmlString>>(target: P, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => void;
|
|
32
35
|
/** Boot checks of a resource class's print templates; `taken` are names already in use (base methods, actions). */
|
|
33
36
|
export declare function resolvePrints(resourceClass: Function, taken: readonly string[], fail: (message: string) => never): Map<string, RegisteredPrint>;
|
|
34
37
|
/** The permission code of a print template. */
|
|
@@ -3,12 +3,6 @@ import { ADMIN_PRINTS_METADATA } from '../constants.js';
|
|
|
3
3
|
import { humanize } from '../schema/humanize.js';
|
|
4
4
|
/** Paper sizes by name; any other string is used as the CSS `@page { size }` value. */
|
|
5
5
|
export const PAPERS = { A4: 'A4', A5: 'A5', label: '100mm 150mm' };
|
|
6
|
-
/**
|
|
7
|
-
* A print template of a resource (an invoice, a shipping label): the method `(records, ctx)` returns the body HTML of
|
|
8
|
-
* the printed page, one or more records (`bulk`). Build it with the `html` tag, which escapes every value. The admin
|
|
9
|
-
* wraps it in a page sized for `paper` that prints itself. Printing needs `{resource}.view`, the user's row scopes and
|
|
10
|
-
* `{resource}.print.{name}`; each printed record is written to the audit log. Throw an `HttpException` to refuse.
|
|
11
|
-
*/
|
|
12
6
|
export function AdminPrint(options = {}) {
|
|
13
7
|
return (target, propertyKey) => {
|
|
14
8
|
if (typeof propertyKey !== 'string')
|
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import 'reflect-metadata';
|
|
2
|
+
import type { ObjectLiteral } from 'typeorm';
|
|
3
|
+
import type { AdminResourceBase } from '../resource/admin-resource-base.js';
|
|
4
|
+
import type { AdminSourceBase } from '../resource/admin-source-base.js';
|
|
5
|
+
import type { TypedClassDecorator } from './typed.js';
|
|
2
6
|
import type { LocalizedText } from '../i18n/localized-text.js';
|
|
3
7
|
import type { TitleDefinition } from '../schema/titles.js';
|
|
4
8
|
export interface AdminResourceOptions {
|
|
@@ -55,7 +59,7 @@ export interface AdminSourceOptions extends Omit<AdminResourceOptions, 'dataSour
|
|
|
55
59
|
* extends AdminSourceBase and answers `findMany`/`findOne` (and `create`/`update`/`delete` when it allows them).
|
|
56
60
|
* `row` is a class whose class-validator decorators describe a row's fields, like an action's input DTO.
|
|
57
61
|
*/
|
|
58
|
-
export declare function AdminSource(row:
|
|
62
|
+
export declare function AdminSource<R extends ObjectLiteral>(row: abstract new (...args: any[]) => R, options?: AdminSourceOptions): TypedClassDecorator<AdminSourceBase<R, any>>;
|
|
59
63
|
/** Marks a provider as an admin resource for `entity`. The class must extend AdminResourceBase. */
|
|
60
|
-
export declare function AdminResource(entity:
|
|
64
|
+
export declare function AdminResource<E extends ObjectLiteral>(entity: abstract new (...args: any[]) => E, options?: AdminResourceOptions): TypedClassDecorator<AdminResourceBase<E, any>>;
|
|
61
65
|
export declare function getAdminResourceDefinition(target: Function): AdminResourceDefinition | undefined;
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import 'reflect-metadata';
|
|
2
2
|
import type { WhereExpressionBuilder } from 'typeorm';
|
|
3
|
+
import type { AdminContext } from '../resource/admin-context.js';
|
|
4
|
+
import type { RecordMethodDecorator, TypedMethodDecorator } from './typed.js';
|
|
3
5
|
/**
|
|
4
6
|
* What a scope returns: a column map (`{ ownerId: ctx.user.id }`; an array means IN, null means IS NULL), or a
|
|
5
7
|
* callback that adds conditions for anything else (`(where, alias) => where.where(`${alias}.total > 0`)`).
|
|
@@ -9,7 +11,7 @@ export type ScopeCondition = Record<string, unknown> | ((where: WhereExpressionB
|
|
|
9
11
|
* A named row scope (spec §6.4): `@AdminScope('own') own(ctx) { return { ownerId: ctx.user.id }; }`. Roles assign
|
|
10
12
|
* scopes per resource and operation; the method runs per request and must not throw for a normal user.
|
|
11
13
|
*/
|
|
12
|
-
export declare function AdminScope(name: string):
|
|
14
|
+
export declare function AdminScope(name: string): TypedMethodDecorator<(ctx: AdminContext) => ScopeCondition>;
|
|
13
15
|
export declare function getScopes(target: Function): Record<string, string | symbol>;
|
|
14
16
|
export type RecordOperation = 'update' | 'delete';
|
|
15
17
|
/**
|
|
@@ -18,7 +20,8 @@ export type RecordOperation = 'update' | 'delete';
|
|
|
18
20
|
* (`@AdminCan('ship')`) rules that action the same way: `_perm.actions` lists it only where the rule agrees, and
|
|
19
21
|
* running it elsewhere is a 403. Any other name fails at boot.
|
|
20
22
|
*/
|
|
21
|
-
export declare function AdminCan(operation:
|
|
23
|
+
export declare function AdminCan(operation: 'create'): TypedMethodDecorator<(parent: any, ctx: AdminContext) => boolean>;
|
|
24
|
+
export declare function AdminCan(operation: RecordOperation | (string & {})): RecordMethodDecorator<[ctx: AdminContext], boolean>;
|
|
22
25
|
/** The rule methods for an operation (`update`, `delete`) or a record action's name. */
|
|
23
26
|
export declare function getCanRules(target: Function, operation: string): Array<string | symbol>;
|
|
24
27
|
/** Every name the class has `@AdminCan` rules for. */
|
|
@@ -14,12 +14,6 @@ export function AdminScope(name) {
|
|
|
14
14
|
export function getScopes(target) {
|
|
15
15
|
return Reflect.getMetadata(ADMIN_SCOPES_METADATA, target) ?? {};
|
|
16
16
|
}
|
|
17
|
-
/**
|
|
18
|
-
* A per-record rule (spec §6.3): `@AdminCan('update') canEdit(record, ctx) { return record.status === 'draft'; }`.
|
|
19
|
-
* Records carry the answer in `_perm`; PATCH and DELETE re-check it (403). The name of a record `@AdminAction`
|
|
20
|
-
* (`@AdminCan('ship')`) rules that action the same way: `_perm.actions` lists it only where the rule agrees, and
|
|
21
|
-
* running it elsewhere is a 403. Any other name fails at boot.
|
|
22
|
-
*/
|
|
23
17
|
export function AdminCan(operation) {
|
|
24
18
|
return (target, propertyKey) => {
|
|
25
19
|
const owner = target.constructor;
|
|
@@ -3,6 +3,7 @@ import type { LocalizedText } from '../i18n/localized-text.js';
|
|
|
3
3
|
import type { AdminContext } from '../resource/admin-context.js';
|
|
4
4
|
import type { LayoutConfig } from '../schema/field-config.js';
|
|
5
5
|
import type { AdminFieldOptions } from './admin-field.js';
|
|
6
|
+
import type { TypedClassDecorator } from './typed.js';
|
|
6
7
|
export interface AdminSettingsPageOptions<T extends object = any> {
|
|
7
8
|
/** `'Payments'` or `{ en: 'Payments', fa: 'پرداخت' }`. Defaults to the humanized page name. */
|
|
8
9
|
label?: LocalizedText;
|
|
@@ -63,5 +64,5 @@ export interface AdminSettingsPageDefinition extends AdminSettingsPageOptions {
|
|
|
63
64
|
* `save` (`AdminSettingsSource`). Viewing it needs `page.<name>`, saving `page.<name>.update`. The name is letters,
|
|
64
65
|
* digits, `-` and `_`, and not the name of a resource.
|
|
65
66
|
*/
|
|
66
|
-
export declare function AdminSettingsPage<T extends object>(name: string, options: AdminSettingsPageOptions<T>):
|
|
67
|
+
export declare function AdminSettingsPage<T extends object>(name: string, options: AdminSettingsPageOptions<T>): TypedClassDecorator<AdminSettingsSource<T>>;
|
|
67
68
|
export declare function getAdminSettingsPageDefinition(target: Function): AdminSettingsPageDefinition | undefined;
|
|
@@ -2,6 +2,7 @@ import 'reflect-metadata';
|
|
|
2
2
|
import type { WidgetData, WidgetParams, WidgetType } from '../contract.js';
|
|
3
3
|
import type { LocalizedText } from '../i18n/localized-text.js';
|
|
4
4
|
import type { AdminContext } from '../resource/admin-context.js';
|
|
5
|
+
import type { TypedClassDecorator } from './typed.js';
|
|
5
6
|
export interface AdminWidgetOptions {
|
|
6
7
|
type: WidgetType;
|
|
7
8
|
title: LocalizedText;
|
|
@@ -23,5 +24,5 @@ export interface AdminWidgetDefinition extends AdminWidgetOptions {
|
|
|
23
24
|
name: string;
|
|
24
25
|
}
|
|
25
26
|
/** A dashboard widget: a provider whose `load` answers its data. The dashboard replaces the home page once one exists. */
|
|
26
|
-
export declare function AdminWidget(name: string, options: AdminWidgetOptions):
|
|
27
|
+
export declare function AdminWidget(name: string, options: AdminWidgetOptions): TypedClassDecorator<AdminWidgetSource>;
|
|
27
28
|
export declare function getAdminWidgetDefinition(target: Function): AdminWidgetDefinition | undefined;
|
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
import 'reflect-metadata';
|
|
2
|
+
import type { AdminContext } from '../resource/admin-context.js';
|
|
3
|
+
import type { ReturnsNothing, RowOf } from './typed.js';
|
|
2
4
|
export type HookKind = 'beforeSave' | 'afterSave' | 'beforeDelete';
|
|
3
5
|
export type SaveMode = 'create' | 'update';
|
|
4
6
|
/** `soft`: moved to the trash (@DeleteDateColumn); `hard`: the row is removed (no trash, or a purge). */
|
|
5
7
|
export type DeleteMode = 'soft' | 'hard';
|
|
6
|
-
/** `(
|
|
7
|
-
|
|
8
|
-
/** `(
|
|
9
|
-
export declare const
|
|
10
|
-
/** `(entity, ctx, mode
|
|
11
|
-
export declare const
|
|
8
|
+
/** A hook decorator: the method takes `(first, ctx, mode)` and returns nothing (sync or async). */
|
|
9
|
+
type HookDecorator<First, Mode> = <P extends object, T extends (first: First extends 'row' ? RowOf<P> : any, ctx: AdminContext, mode: Mode) => unknown>(target: P, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T> & ReturnsNothing<T>) => void;
|
|
10
|
+
/** `(dto, ctx, mode)` — runs before the default create/update saves; may mutate `dto`. Returns nothing. */
|
|
11
|
+
export declare const BeforeSave: () => HookDecorator<'dto', SaveMode>;
|
|
12
|
+
/** `(entity, ctx, mode)` — runs after the default create/update saved. Returns nothing. */
|
|
13
|
+
export declare const AfterSave: () => HookDecorator<'row', SaveMode>;
|
|
14
|
+
/** `(entity, ctx, mode: DeleteMode)` — runs before the default delete and purge; throw to refuse. Returns nothing. */
|
|
15
|
+
export declare const BeforeDelete: () => HookDecorator<'row', DeleteMode>;
|
|
12
16
|
export declare function getHooks(target: Function, kind: HookKind): Array<string | symbol>;
|
|
17
|
+
export {};
|
package/dist/decorators/hooks.js
CHANGED
|
@@ -15,11 +15,11 @@ function hook(kind) {
|
|
|
15
15
|
Reflect.defineMetadata(ADMIN_HOOKS_METADATA, table, owner);
|
|
16
16
|
};
|
|
17
17
|
}
|
|
18
|
-
/** `(dto, ctx, mode)` — runs before the default create/update saves; may mutate `dto`. */
|
|
18
|
+
/** `(dto, ctx, mode)` — runs before the default create/update saves; may mutate `dto`. Returns nothing. */
|
|
19
19
|
export const BeforeSave = () => hook('beforeSave');
|
|
20
|
-
/** `(entity, ctx, mode)` — runs after the default create/update saved. */
|
|
20
|
+
/** `(entity, ctx, mode)` — runs after the default create/update saved. Returns nothing. */
|
|
21
21
|
export const AfterSave = () => hook('afterSave');
|
|
22
|
-
/** `(entity, ctx, mode: DeleteMode)` — runs before the default delete and purge; throw to refuse. */
|
|
22
|
+
/** `(entity, ctx, mode: DeleteMode)` — runs before the default delete and purge; throw to refuse. Returns nothing. */
|
|
23
23
|
export const BeforeDelete = () => hook('beforeDelete');
|
|
24
24
|
export function getHooks(target, kind) {
|
|
25
25
|
return Reflect.getMetadata(ADMIN_HOOKS_METADATA, target)?.[kind] ?? [];
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { AdminContext } from '../resource/admin-context.js';
|
|
2
|
+
import type { AdminResourceBase } from '../resource/admin-resource-base.js';
|
|
3
|
+
/** A value or a Promise of it. */
|
|
4
|
+
export type Awaitable<T> = T | Promise<T>;
|
|
5
|
+
/**
|
|
6
|
+
* A method decorator that only accepts methods of the signature `M`: decorating a method that takes or returns
|
|
7
|
+
* something else is a compile error, at the decorator.
|
|
8
|
+
*/
|
|
9
|
+
export type TypedMethodDecorator<M> = <T extends M>(target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => void;
|
|
10
|
+
/** A class decorator that only accepts classes whose instances are `I`. */
|
|
11
|
+
export type TypedClassDecorator<I> = <C extends abstract new (...args: any[]) => I>(target: C) => void;
|
|
12
|
+
/** The row type of a resource class (`AdminResourceBase<Order>` → `Order`); `any` outside one. */
|
|
13
|
+
export type RowOf<P> = P extends AdminResourceBase<infer T, any> ? T : any;
|
|
14
|
+
/** Refuses (at compile time) a method that returns a value where nothing is read. */
|
|
15
|
+
export type ReturnsNothing<M> = M extends (...args: any[]) => infer R ? [Awaited<R>] extends [void | undefined] ? unknown : {
|
|
16
|
+
'nest-my-admin: this method must return nothing (its value would be ignored)': never;
|
|
17
|
+
} : unknown;
|
|
18
|
+
/** A method of a resource whose first parameter is one of its rows. */
|
|
19
|
+
export type RecordMethodDecorator<Rest extends unknown[], R> = <P extends object, T extends (record: RowOf<P>, ...rest: Rest) => R>(target: P, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => void;
|
|
20
|
+
export type { AdminContext };
|
package/dist/files/file-owner.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { parseRecordId, recordIdOf } from '../crud/record-id.js';
|
|
2
2
|
import { AdminBadRequestError, AdminForbiddenError, AdminNotFoundError, AdminValidationError } from '../errors.js';
|
|
3
|
+
import { checkFoundRecord } from '../host-contract.js';
|
|
3
4
|
/** A resource as the owner of its records' files: permissions, field levels and row scopes decide. */
|
|
4
5
|
export function resourceFileOwner(entry, policy) {
|
|
5
6
|
const { name } = entry.schema;
|
|
@@ -30,7 +31,7 @@ export function resourceFileOwner(entry, policy) {
|
|
|
30
31
|
return undefined;
|
|
31
32
|
try {
|
|
32
33
|
const id = parseRecordId(recordId, entry.schema);
|
|
33
|
-
const entity = await entry.resource.findOne(id, ctx);
|
|
34
|
+
const entity = checkFoundRecord(await entry.resource.findOne(id, ctx), `${entry.resource.constructor.name}.findOne()`);
|
|
34
35
|
if (!entity)
|
|
35
36
|
return undefined;
|
|
36
37
|
await policy.requireInScope(entry, id, recordId, 'view', ctx); // a findOne override may ignore scopes
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime checks of what host code returns where the admin needs a particular shape (spec: «fail loudly»): a wrong
|
|
3
|
+
* value is a programming error, so it fails the request with a sentence naming the method and what it returned,
|
|
4
|
+
* instead of being misread (an `async` scope read as «no restriction»).
|
|
5
|
+
*/
|
|
6
|
+
/** A Promise or any other thenable. */
|
|
7
|
+
export declare const isThenable: (value: unknown) => value is PromiseLike<unknown>;
|
|
8
|
+
/** A short description of a value for an error message: `a Promise`, `an array`, `the string "x"`, `undefined`. */
|
|
9
|
+
export declare function describeValue(value: unknown): string;
|
|
10
|
+
/** Host code broke its contract: a 500 whose message (logged with the correlation id) says what to fix. */
|
|
11
|
+
export declare class HostContractError extends Error {
|
|
12
|
+
constructor(message: string);
|
|
13
|
+
}
|
|
14
|
+
export declare const isPlainObject: (value: unknown) => value is Record<string, unknown>;
|
|
15
|
+
/** What `findMany` must answer: `{ items: [...], total: number | null }` (and the optional paging fields). */
|
|
16
|
+
export declare function checkFindMany<T>(found: T, where: string): T;
|
|
17
|
+
/** A text: a string, or a plain object of strings by locale (`{ en, fa }`), never a Promise or a class instance. */
|
|
18
|
+
export declare const isLocalizedText: (value: unknown) => boolean;
|
|
19
|
+
/** What `query()` and `relationOptions()` hand back: the query builder, never a Promise of it or nothing. */
|
|
20
|
+
export declare function checkQueryBuilder<Q>(value: Q, where: string): Q;
|
|
21
|
+
/** A list of strings (`resolveRoles`), or nothing. */
|
|
22
|
+
export declare function checkStringList(value: unknown, where: string): string[];
|
|
23
|
+
/** A record a write method answered: an object, or nothing (the admin then reloads it). */
|
|
24
|
+
export declare function checkWriteResult(value: unknown, where: string): unknown;
|
|
25
|
+
/** A record `findOne`/`getUser` answered: an object, or null. */
|
|
26
|
+
export declare function checkFoundRecord<T>(value: T, where: string): T;
|
|
27
|
+
/** A yes/no answer given at once. */
|
|
28
|
+
export declare function checkBoolean(value: unknown, where: string): boolean;
|
|
29
|
+
/** An object of values: a plain object or a class instance, never an array or a Promise. */
|
|
30
|
+
export declare const isRecordObject: (value: unknown) => value is Record<string, unknown>;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime checks of what host code returns where the admin needs a particular shape (spec: «fail loudly»): a wrong
|
|
3
|
+
* value is a programming error, so it fails the request with a sentence naming the method and what it returned,
|
|
4
|
+
* instead of being misread (an `async` scope read as «no restriction»).
|
|
5
|
+
*/
|
|
6
|
+
/** A Promise or any other thenable. */
|
|
7
|
+
export const isThenable = (value) => (typeof value === 'object' || typeof value === 'function') && value !== null && typeof value.then === 'function';
|
|
8
|
+
/** A short description of a value for an error message: `a Promise`, `an array`, `the string "x"`, `undefined`. */
|
|
9
|
+
export function describeValue(value) {
|
|
10
|
+
if (value === undefined)
|
|
11
|
+
return 'undefined';
|
|
12
|
+
if (value === null)
|
|
13
|
+
return 'null';
|
|
14
|
+
if (isThenable(value))
|
|
15
|
+
return 'a Promise (is the method async?)';
|
|
16
|
+
if (Array.isArray(value))
|
|
17
|
+
return 'an array';
|
|
18
|
+
if (typeof value === 'string')
|
|
19
|
+
return `the string ${JSON.stringify(value.length > 40 ? `${value.slice(0, 40)}…` : value)}`;
|
|
20
|
+
if (typeof value === 'function')
|
|
21
|
+
return 'a function';
|
|
22
|
+
if (typeof value === 'object') {
|
|
23
|
+
const name = value.constructor?.name;
|
|
24
|
+
return name && name !== 'Object' ? `a ${name}` : 'an object';
|
|
25
|
+
}
|
|
26
|
+
return `the ${typeof value} ${String(value)}`;
|
|
27
|
+
}
|
|
28
|
+
/** Host code broke its contract: a 500 whose message (logged with the correlation id) says what to fix. */
|
|
29
|
+
export class HostContractError extends Error {
|
|
30
|
+
constructor(message) {
|
|
31
|
+
super(`nest-my-admin: ${message}`);
|
|
32
|
+
this.name = 'HostContractError';
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export const isPlainObject = (value) => typeof value === 'object' && value !== null && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
|
|
36
|
+
/** What `findMany` must answer: `{ items: [...], total: number | null }` (and the optional paging fields). */
|
|
37
|
+
export function checkFindMany(found, where) {
|
|
38
|
+
const value = found;
|
|
39
|
+
const fail = (what) => {
|
|
40
|
+
throw new HostContractError(`${where}.findMany() returned ${what}; it answers { items: [...], total: number | null } (inMemoryList(rows, params) builds that from an array)`);
|
|
41
|
+
};
|
|
42
|
+
if (!isPlainObject(value))
|
|
43
|
+
fail(describeValue(found));
|
|
44
|
+
if (!Array.isArray(value.items))
|
|
45
|
+
fail(`items that are ${describeValue(value.items)}`);
|
|
46
|
+
const total = value.total;
|
|
47
|
+
if (total !== null && total !== undefined && (typeof total !== 'number' || !Number.isFinite(total) || total < 0))
|
|
48
|
+
fail(`a total of ${describeValue(total)}`);
|
|
49
|
+
if (value.items.some((item) => typeof item !== "object" || item === null))
|
|
50
|
+
fail('items that are not all records (objects)');
|
|
51
|
+
return found;
|
|
52
|
+
}
|
|
53
|
+
/** A text: a string, or a plain object of strings by locale (`{ en, fa }`), never a Promise or a class instance. */
|
|
54
|
+
export const isLocalizedText = (value) => typeof value === 'string' || (isPlainObject(value) && Object.values(value).every((text) => typeof text === 'string'));
|
|
55
|
+
/** What `query()` and `relationOptions()` hand back: the query builder, never a Promise of it or nothing. */
|
|
56
|
+
export function checkQueryBuilder(value, where) {
|
|
57
|
+
// By shape, not instanceof: a host may resolve its own copy of typeorm.
|
|
58
|
+
const qb = value;
|
|
59
|
+
if (typeof qb === 'object' && qb !== null && typeof qb.andWhere === 'function' && typeof qb.getQuery === 'function')
|
|
60
|
+
return value;
|
|
61
|
+
throw new HostContractError(`${where} must return the query builder (add to the one it was given and return it), but it returned ${describeValue(value)}`);
|
|
62
|
+
}
|
|
63
|
+
/** A list of strings (`resolveRoles`), or nothing. */
|
|
64
|
+
export function checkStringList(value, where) {
|
|
65
|
+
if (value === undefined || value === null)
|
|
66
|
+
return [];
|
|
67
|
+
if (Array.isArray(value) && value.every((item) => typeof item === 'string'))
|
|
68
|
+
return value;
|
|
69
|
+
throw new HostContractError(`${where} must return an array of role names, but it returned ${describeValue(value)}`);
|
|
70
|
+
}
|
|
71
|
+
/** A record a write method answered: an object, or nothing (the admin then reloads it). */
|
|
72
|
+
export function checkWriteResult(value, where) {
|
|
73
|
+
if (value === undefined || value === null || (typeof value === 'object' && !Array.isArray(value) && !isThenable(value)))
|
|
74
|
+
return value;
|
|
75
|
+
throw new HostContractError(`${where} must return the saved record (or nothing, to have it reloaded), but it returned ${describeValue(value)}`);
|
|
76
|
+
}
|
|
77
|
+
/** A record `findOne`/`getUser` answered: an object, or null. */
|
|
78
|
+
export function checkFoundRecord(value, where) {
|
|
79
|
+
if (value === undefined || value === null || (typeof value === 'object' && !Array.isArray(value)))
|
|
80
|
+
return value;
|
|
81
|
+
throw new HostContractError(`${where} must return the record or null, but it returned ${describeValue(value)}`);
|
|
82
|
+
}
|
|
83
|
+
/** A yes/no answer given at once. */
|
|
84
|
+
export function checkBoolean(value, where) {
|
|
85
|
+
if (typeof value === 'boolean')
|
|
86
|
+
return value;
|
|
87
|
+
throw new HostContractError(`${where} must return true or false, but it returned ${describeValue(value)}`);
|
|
88
|
+
}
|
|
89
|
+
/** An object of values: a plain object or a class instance, never an array or a Promise. */
|
|
90
|
+
export const isRecordObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value) && !isThenable(value);
|
|
91
|
+
//# sourceMappingURL=host-contract.js.map
|
|
@@ -20,7 +20,7 @@ import { AuditReader } from '../audit/audit-reader.js';
|
|
|
20
20
|
import { addAuditRoutes } from '../audit/audit-routes.js';
|
|
21
21
|
import { addMenuRoutes } from '../api/menu-routes.js';
|
|
22
22
|
import { addDashboardRoutes } from '../dashboard/dashboard-routes.js';
|
|
23
|
-
import { AdminAppearance } from '../appearance/appearance.service.js';
|
|
23
|
+
import { AdminAppearance, appearanceImageType, MAX_APPEARANCE_IMAGE_BYTES } from '../appearance/appearance.service.js';
|
|
24
24
|
import { DashboardService } from '../dashboard/dashboard.service.js';
|
|
25
25
|
import { AdminAudit, clientOf } from '../audit/audit.service.js';
|
|
26
26
|
import { AdminAuthService } from '../auth/auth.service.js';
|
|
@@ -33,7 +33,7 @@ import { AdminRbac } from '../rbac/rbac.service.js';
|
|
|
33
33
|
import { ResourceRegistry } from '../registry/resource-registry.js';
|
|
34
34
|
import { createAdminContext, runInAdminContext } from '../resource/admin-context.js';
|
|
35
35
|
import { codeForStatus, toErrorResponse } from './error-response.js';
|
|
36
|
-
import { readJsonBody, sendJson } from './http-io.js';
|
|
36
|
+
import { readJsonBody, readRawBody, sendJson } from './http-io.js';
|
|
37
37
|
import { Router } from './router.js';
|
|
38
38
|
import { UiAssets, resolveUiDist } from './ui-assets.js';
|
|
39
39
|
import { AdminApiService } from '../api/admin-api.service.js';
|
|
@@ -41,6 +41,10 @@ import { ADMIN_OPTIONS } from '../constants.js';
|
|
|
41
41
|
import { readUiMessages, uiOverrides } from './ui-messages.js';
|
|
42
42
|
/** The only API routes that answer without a session: reading it (to learn you are signed out) and logging in. */
|
|
43
43
|
const PUBLIC_ROUTES = new Set(['GET /api/session', 'POST /api/session']);
|
|
44
|
+
/** The logo/favicon uploads: their body is the picture, and the route checks it is an image type. */
|
|
45
|
+
const IMAGE_ROUTE = /^PUT \/api\/appearance\/[^/]+$/;
|
|
46
|
+
/** An uploaded logo or favicon, served to anyone (the sign-in page and the browser tab need it). */
|
|
47
|
+
const IMAGE_PATH = /^\/appearance\/([^/]+)$/;
|
|
44
48
|
// Methods that carry a JSON body. DELETE is never a CORS "simple" request, so a foreign page cannot send one without a preflight.
|
|
45
49
|
const BODY_METHODS = new Set(['POST', 'PATCH', 'PUT']);
|
|
46
50
|
function isJsonContentType(header) {
|
|
@@ -276,6 +280,15 @@ let AdminHttpServer = class AdminHttpServer {
|
|
|
276
280
|
addAuditRoutes(this.router, { reader: auditReader });
|
|
277
281
|
addMenuRoutes(this.router, { api: this.api });
|
|
278
282
|
addDashboardRoutes(this.router, { dashboard: this.dashboard });
|
|
283
|
+
// The logo and favicon: the picture itself is the body (an image type: never a CORS "simple" request).
|
|
284
|
+
this.router.add('PUT', '/api/appearance/:kind', async ({ req, res, ctx }, p) => {
|
|
285
|
+
const type = appearanceImageType(req.headers['content-type']);
|
|
286
|
+
if (!type)
|
|
287
|
+
throw new AdminUnsupportedMediaTypeError('Upload a PNG, JPEG, GIF, WebP, ICO or SVG picture');
|
|
288
|
+
const data = await readRawBody(req, MAX_APPEARANCE_IMAGE_BYTES);
|
|
289
|
+
sendJson(res, 200, await this.appearance.setImage(p.kind, type, data, ctx));
|
|
290
|
+
});
|
|
291
|
+
this.router.add('DELETE', '/api/appearance/:kind', async ({ res, ctx }, p) => sendJson(res, 200, await this.appearance.setImage(p.kind, undefined, null, ctx)));
|
|
279
292
|
this.router.add('PUT', '/api/appearance', async ({ req, res, ctx }) => sendJson(res, 200, await this.appearance.setAccent(((await readJsonBody(req)) ?? {}).accent ?? null, ctx)));
|
|
280
293
|
addRbacRoutes(this.router, { rbac: this.rbac, auth: this.auth, api: this.api, policy: this.policy, registry: this.registry, audit: this.audit });
|
|
281
294
|
}
|
|
@@ -339,7 +352,7 @@ let AdminHttpServer = class AdminHttpServer {
|
|
|
339
352
|
auth: this.auth.capabilities,
|
|
340
353
|
rbac: { enabled, view: enabled && (permissions.can('rbac.view') || permissions.can('rbac.manage')), manage: enabled && permissions.can('rbac.manage') },
|
|
341
354
|
audit: { enabled: this.audit.enabled, view: this.audit.enabled && permissions.can('audit.view') },
|
|
342
|
-
...(this.appearance.enabled ? { appearance: { accent: this.appearance.current(), manage: !viewAs && permissions.can('appearance.manage') } } : {}),
|
|
355
|
+
...(this.appearance.enabled ? { appearance: { accent: this.appearance.current(), manage: !viewAs && permissions.can('appearance.manage'), ...this.appearance.imageUrls() } } : {}),
|
|
343
356
|
permissionsVersion: this.rbac.permissionsVersion,
|
|
344
357
|
...(viewAs ? { viewAs: { by: toSessionUser(viewAs.by) } } : {}),
|
|
345
358
|
};
|
|
@@ -366,7 +379,7 @@ let AdminHttpServer = class AdminHttpServer {
|
|
|
366
379
|
branding: this.options.branding,
|
|
367
380
|
...(this.options.currency ? { currency: this.options.currency } : {}),
|
|
368
381
|
...(Object.keys(messages).length > 0 ? { messages } : {}),
|
|
369
|
-
}, { title: this.options.title });
|
|
382
|
+
}, { title: this.options.title }, this.appearance.enabled ? () => this.appearance.imageUrls() : undefined);
|
|
370
383
|
adapter.use(this.options.path, (req, res, next) => {
|
|
371
384
|
this.handle(req, res, next).catch((error) => {
|
|
372
385
|
const correlationId = randomUUID();
|
|
@@ -414,7 +427,7 @@ let AdminHttpServer = class AdminHttpServer {
|
|
|
414
427
|
// Only JSON can be sent by a script; forms and text/plain are CORS "simple" requests a foreign page could forge.
|
|
415
428
|
// Uploads carry the raw file instead; FilesService.upload refuses the simple types itself.
|
|
416
429
|
const route = `${req.method} ${pathname.replace(/\/+$/, '')}`;
|
|
417
|
-
if (BODY_METHODS.has(req.method ?? '') && route !== UPLOAD_ROUTE && !isJsonContentType(req.headers['content-type'])) {
|
|
430
|
+
if (BODY_METHODS.has(req.method ?? '') && route !== UPLOAD_ROUTE && !IMAGE_ROUTE.test(route) && !isJsonContentType(req.headers['content-type'])) {
|
|
418
431
|
throw new AdminUnsupportedMediaTypeError('Content-Type must be application/json');
|
|
419
432
|
}
|
|
420
433
|
resourceName = match.params.resource;
|
|
@@ -441,6 +454,22 @@ let AdminHttpServer = class AdminHttpServer {
|
|
|
441
454
|
next();
|
|
442
455
|
return;
|
|
443
456
|
}
|
|
457
|
+
const picture = IMAGE_PATH.exec(pathname);
|
|
458
|
+
if (picture && this.appearance.enabled) {
|
|
459
|
+
const image = this.appearance.image(picture[1]);
|
|
460
|
+
if (!image)
|
|
461
|
+
throw new AdminNotFoundError('No such picture');
|
|
462
|
+
res.statusCode = 200;
|
|
463
|
+
res.setHeader('Content-Type', image.type);
|
|
464
|
+
res.setHeader('Content-Length', image.data.length);
|
|
465
|
+
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
466
|
+
// Opened on its own (an SVG is a document), nothing in it may run or load.
|
|
467
|
+
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox");
|
|
468
|
+
// The URL carries ?v=<hash>: a new picture has a new URL, so this one may be cached for good.
|
|
469
|
+
res.setHeader('Cache-Control', url.searchParams.has('v') ? 'public, max-age=31536000, immutable' : 'no-cache');
|
|
470
|
+
res.end(req.method === 'HEAD' ? undefined : image.data);
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
444
473
|
this.ui.serve(pathname, req, res);
|
|
445
474
|
}
|
|
446
475
|
catch (error) {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { BadRequestException, HttpException } from '@nestjs/common';
|
|
2
2
|
import { QueryFailedError } from 'typeorm';
|
|
3
3
|
import { AdminConflictError, AdminError } from '../errors.js';
|
|
4
|
+
import { describeValue } from '../host-contract.js';
|
|
4
5
|
/** Maps any thrown value to the admin error contract. Never leaks messages of 5xx/unknown errors. */
|
|
5
6
|
export function toErrorResponse(error, correlationId, logger, context = {}) {
|
|
6
7
|
const { errorMapper } = context;
|
|
@@ -13,6 +14,9 @@ export function toErrorResponse(error, correlationId, logger, context = {}) {
|
|
|
13
14
|
}
|
|
14
15
|
error = mapped;
|
|
15
16
|
}
|
|
17
|
+
else if (mapped !== undefined) {
|
|
18
|
+
logger.error(`[${correlationId}] nest-my-admin: errorMapper must return an AdminError (AdminFieldError, AdminConflictError…) or undefined, but it returned ${describeValue(mapped)}; the error is answered as unmapped`);
|
|
19
|
+
}
|
|
16
20
|
}
|
|
17
21
|
catch (mapperError) {
|
|
18
22
|
logger.error(`[${correlationId}] errorMapper threw: ${mapperError instanceof Error ? (mapperError.stack ?? mapperError.message) : String(mapperError)}`);
|