@nest-my-admin/core 0.8.0 → 0.8.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/README.md +4 -0
- package/dist/appearance/appearance.service.d.ts +28 -0
- package/dist/appearance/appearance.service.js +63 -0
- package/dist/contract.d.ts +6 -1
- package/dist/http/admin-http.server.js +34 -5
- 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/package.json +2 -2
package/README.md
CHANGED
|
@@ -969,6 +969,10 @@ Things hosts tend to write by hand that the admin already does:
|
|
|
969
969
|
- **Inline children stay out of the sidebar** by default (`nav: false` unless they set `nav`): no extra group to hide them in.
|
|
970
970
|
- **Labels in one language** are plain strings; other languages can come from `translate` (see Languages, theme and branding).
|
|
971
971
|
|
|
972
|
+
## Upgrading to 0.8.1
|
|
973
|
+
|
|
974
|
+
Nothing to change. New: with `appearance` on, whoever holds `appearance.manage` uploads the **logo** (sidebar and sign-in page) and the **tab icon** (favicon) from the account menu, for everyone (PNG, JPEG, GIF, WebP, ICO or SVG, up to 512 KB; stored in `nma_setting`, served at `<path>/appearance/logo` and `/appearance/favicon`). An uploaded logo wins over `branding.logo`. Without a logo the sidebar shows the admin's own mark instead of the first letter of the title, and it is the default tab icon.
|
|
975
|
+
|
|
972
976
|
## Upgrading to 0.8.0
|
|
973
977
|
|
|
974
978
|
Nothing to change. New: [source resources](#source-resources): `@AdminSource(RowClass, …)` and `AdminSourceBase` give rows that are not database rows (an HTTP API, files, live state) the list, record page, forms and actions of a table; `inMemoryList` searches, filters, sorts and pages rows fetched whole.
|
|
@@ -5,6 +5,19 @@ import { AdminPolicy } from '../policy/admin-policy.service.js';
|
|
|
5
5
|
import type { AdminContext } from '../resource/admin-context.js';
|
|
6
6
|
/** Changing the admin-wide look. A code only while `appearance` is on. */
|
|
7
7
|
export declare const APPEARANCE_CODES: string[];
|
|
8
|
+
/** The pictures the admin's look has: the logo (sidebar and sign-in page) and the browser tab's icon. */
|
|
9
|
+
export declare const APPEARANCE_IMAGES: readonly ['logo', 'favicon'];
|
|
10
|
+
export type AppearanceImageKind = (typeof APPEARANCE_IMAGES)[number];
|
|
11
|
+
/** The most an uploaded logo or favicon may weigh. */
|
|
12
|
+
export declare const MAX_APPEARANCE_IMAGE_BYTES: number;
|
|
13
|
+
/** The media type of an upload (`image/png; charset=…` → `image/png`), or undefined when it is not an accepted image. */
|
|
14
|
+
export declare function appearanceImageType(contentType: string | undefined): string | undefined;
|
|
15
|
+
interface StoredImage {
|
|
16
|
+
type: string;
|
|
17
|
+
data: Buffer;
|
|
18
|
+
/** The first 12 hex digits of its SHA-256: the `?v=` of its URL, so a new picture is never served from a cache. */
|
|
19
|
+
version: string;
|
|
20
|
+
}
|
|
8
21
|
/**
|
|
9
22
|
* The admin-wide accent colour (`forRoot({ appearance })`): set in the admin by whoever holds `appearance.manage`, seen
|
|
10
23
|
* by everyone (it wins over `branding.primaryColor`; each person may still pick their own in their browser).
|
|
@@ -16,9 +29,23 @@ export declare class AdminAppearance implements OnApplicationBootstrap {
|
|
|
16
29
|
private dataSource?;
|
|
17
30
|
/** The stored accent, read once at boot and kept current by `setAccent`. */
|
|
18
31
|
private accent;
|
|
32
|
+
/** The uploaded pictures, read once at boot and kept current by `setImage`. */
|
|
33
|
+
private readonly images;
|
|
19
34
|
constructor(options: ResolvedAdminOptions, moduleRef: ModuleRef, policy: AdminPolicy);
|
|
20
35
|
get enabled(): boolean;
|
|
21
36
|
onApplicationBootstrap(): Promise<void>;
|
|
37
|
+
/** An uploaded picture (served at `<path>/appearance/<kind>`), or undefined. */
|
|
38
|
+
image(kind: string): StoredImage | undefined;
|
|
39
|
+
/** Where the page finds each uploaded picture, relative to the admin's `<base href>`; null when there is none. */
|
|
40
|
+
imageUrls(): {
|
|
41
|
+
logo: string | null;
|
|
42
|
+
favicon: string | null;
|
|
43
|
+
};
|
|
44
|
+
/** `PUT /api/appearance/:kind` (a picture) and `DELETE` (`null`: none again, so `branding.logo` is back). */
|
|
45
|
+
setImage(kind: string, type: string | undefined, data: Buffer | null, ctx: AdminContext): Promise<{
|
|
46
|
+
logo: string | null;
|
|
47
|
+
favicon: string | null;
|
|
48
|
+
}>;
|
|
22
49
|
/** The admin-wide accent (`SessionResponse.appearance.accent`). */
|
|
23
50
|
current(): string | null;
|
|
24
51
|
/** `PUT /api/appearance`: a CSS colour, or `null` for the host's branding again. */
|
|
@@ -26,3 +53,4 @@ export declare class AdminAppearance implements OnApplicationBootstrap {
|
|
|
26
53
|
accent: string | null;
|
|
27
54
|
}>;
|
|
28
55
|
}
|
|
56
|
+
export {};
|
|
@@ -10,6 +10,7 @@ var __metadata = (this && this.__metadata) || function (k, v) {
|
|
|
10
10
|
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
11
11
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
12
|
};
|
|
13
|
+
import { createHash } from 'node:crypto';
|
|
13
14
|
import { Inject, Injectable } from '@nestjs/common';
|
|
14
15
|
import { ModuleRef } from '@nestjs/core';
|
|
15
16
|
import { getDataSourceToken } from '@nestjs/typeorm';
|
|
@@ -21,6 +22,25 @@ import { ADMIN_SETTING_ENTITIES, NmaSetting } from './entities.js';
|
|
|
21
22
|
/** Changing the admin-wide look. A code only while `appearance` is on. */
|
|
22
23
|
export const APPEARANCE_CODES = ['appearance.manage'];
|
|
23
24
|
const ACCENT = 'appearance.accent';
|
|
25
|
+
/** The pictures the admin's look has: the logo (sidebar and sign-in page) and the browser tab's icon. */
|
|
26
|
+
export const APPEARANCE_IMAGES = ['logo', 'favicon'];
|
|
27
|
+
/** The most an uploaded logo or favicon may weigh. */
|
|
28
|
+
export const MAX_APPEARANCE_IMAGE_BYTES = 512 * 1024;
|
|
29
|
+
/** The image types accepted, each with a check of the bytes (so a file is what its type says). */
|
|
30
|
+
const IMAGE_TYPES = {
|
|
31
|
+
'image/png': (d) => d.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])),
|
|
32
|
+
'image/jpeg': (d) => d[0] === 0xff && d[1] === 0xd8 && d[2] === 0xff,
|
|
33
|
+
'image/gif': (d) => d.subarray(0, 4).toString('latin1') === 'GIF8',
|
|
34
|
+
'image/webp': (d) => d.subarray(0, 4).toString('latin1') === 'RIFF' && d.subarray(8, 12).toString('latin1') === 'WEBP',
|
|
35
|
+
'image/x-icon': (d) => d.readUInt32BE(0) === 0x00000100,
|
|
36
|
+
'image/vnd.microsoft.icon': (d) => d.readUInt32BE(0) === 0x00000100,
|
|
37
|
+
'image/svg+xml': (d) => /<svg[\s>]/i.test(d.subarray(0, 4096).toString('utf8')),
|
|
38
|
+
};
|
|
39
|
+
/** The media type of an upload (`image/png; charset=…` → `image/png`), or undefined when it is not an accepted image. */
|
|
40
|
+
export function appearanceImageType(contentType) {
|
|
41
|
+
const type = (contentType ?? '').split(';')[0].trim().toLowerCase();
|
|
42
|
+
return type in IMAGE_TYPES ? type : undefined;
|
|
43
|
+
}
|
|
24
44
|
/**
|
|
25
45
|
* The admin-wide accent colour (`forRoot({ appearance })`): set in the admin by whoever holds `appearance.manage`, seen
|
|
26
46
|
* by everyone (it wins over `branding.primaryColor`; each person may still pick their own in their browser).
|
|
@@ -32,6 +52,8 @@ let AdminAppearance = class AdminAppearance {
|
|
|
32
52
|
dataSource;
|
|
33
53
|
/** The stored accent, read once at boot and kept current by `setAccent`. */
|
|
34
54
|
accent = null;
|
|
55
|
+
/** The uploaded pictures, read once at boot and kept current by `setImage`. */
|
|
56
|
+
images = new Map();
|
|
35
57
|
constructor(options, moduleRef, policy) {
|
|
36
58
|
this.options = options;
|
|
37
59
|
this.moduleRef = moduleRef;
|
|
@@ -56,6 +78,46 @@ let AdminAppearance = class AdminAppearance {
|
|
|
56
78
|
}
|
|
57
79
|
const stored = await this.dataSource.getRepository(NmaSetting).findOneBy({ key: ACCENT });
|
|
58
80
|
this.accent = typeof stored?.value === 'string' && isCssColor(stored.value) ? stored.value : null;
|
|
81
|
+
for (const kind of APPEARANCE_IMAGES) {
|
|
82
|
+
const row = await this.dataSource.getRepository(NmaSetting).findOneBy({ key: `appearance.${kind}` });
|
|
83
|
+
const value = row?.value;
|
|
84
|
+
if (typeof value?.type !== 'string' || typeof value.data !== 'string' || !(value.type in IMAGE_TYPES))
|
|
85
|
+
continue;
|
|
86
|
+
const data = Buffer.from(value.data, 'base64');
|
|
87
|
+
this.images.set(kind, { type: value.type, data, version: versionOf(data) });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** An uploaded picture (served at `<path>/appearance/<kind>`), or undefined. */
|
|
91
|
+
image(kind) {
|
|
92
|
+
return APPEARANCE_IMAGES.includes(kind) ? this.images.get(kind) : undefined;
|
|
93
|
+
}
|
|
94
|
+
/** Where the page finds each uploaded picture, relative to the admin's `<base href>`; null when there is none. */
|
|
95
|
+
imageUrls() {
|
|
96
|
+
const url = (kind) => {
|
|
97
|
+
const image = this.images.get(kind);
|
|
98
|
+
return image ? `appearance/${kind}?v=${image.version}` : null;
|
|
99
|
+
};
|
|
100
|
+
return { logo: url('logo'), favicon: url('favicon') };
|
|
101
|
+
}
|
|
102
|
+
/** `PUT /api/appearance/:kind` (a picture) and `DELETE` (`null`: none again, so `branding.logo` is back). */
|
|
103
|
+
async setImage(kind, type, data, ctx) {
|
|
104
|
+
if (!this.dataSource)
|
|
105
|
+
throw new AdminNotFoundError('The look is not set in this admin (no `appearance` option)');
|
|
106
|
+
if (!APPEARANCE_IMAGES.includes(kind))
|
|
107
|
+
throw new AdminNotFoundError(`No admin picture "${kind}" (logo or favicon)`);
|
|
108
|
+
if (ctx.viewAs || !this.policy.permissionsOf(ctx).can('appearance.manage'))
|
|
109
|
+
throw new AdminForbiddenError('You may not change the admin’s look');
|
|
110
|
+
const repo = this.dataSource.getRepository(NmaSetting);
|
|
111
|
+
if (data === null) {
|
|
112
|
+
await repo.delete({ key: `appearance.${kind}` });
|
|
113
|
+
this.images.delete(kind);
|
|
114
|
+
return this.imageUrls();
|
|
115
|
+
}
|
|
116
|
+
if (!type || !IMAGE_TYPES[type](data))
|
|
117
|
+
throw new AdminValidationError({ [kind]: [`the file is not a ${type ?? 'picture'}`] });
|
|
118
|
+
await repo.save({ key: `appearance.${kind}`, value: { type, data: data.toString('base64') } });
|
|
119
|
+
this.images.set(kind, { type, data, version: versionOf(data) });
|
|
120
|
+
return this.imageUrls();
|
|
59
121
|
}
|
|
60
122
|
/** The admin-wide accent (`SessionResponse.appearance.accent`). */
|
|
61
123
|
current() {
|
|
@@ -85,4 +147,5 @@ AdminAppearance = __decorate([
|
|
|
85
147
|
AdminPolicy])
|
|
86
148
|
], AdminAppearance);
|
|
87
149
|
export { AdminAppearance };
|
|
150
|
+
const versionOf = (data) => createHash('sha256').update(data).digest('hex').slice(0, 12);
|
|
88
151
|
//# sourceMappingURL=appearance.service.js.map
|
package/dist/contract.d.ts
CHANGED
|
@@ -654,10 +654,15 @@ export interface SessionResponse {
|
|
|
654
654
|
enabled: boolean;
|
|
655
655
|
view: boolean;
|
|
656
656
|
};
|
|
657
|
-
/**
|
|
657
|
+
/**
|
|
658
|
+
* With `appearance`: the admin-wide accent colour (null: the host's branding), whether this user may change it, and
|
|
659
|
+
* the uploaded logo and favicon (URLs relative to the admin; null: none, so `branding.logo` and the build's icon).
|
|
660
|
+
*/
|
|
658
661
|
appearance?: {
|
|
659
662
|
accent: string | null;
|
|
660
663
|
manage: boolean;
|
|
664
|
+
logo: string | null;
|
|
665
|
+
favicon: string | null;
|
|
661
666
|
};
|
|
662
667
|
/** Changes when roles or memberships change: refetch meta and schemas. */
|
|
663
668
|
permissionsVersion: number;
|
|
@@ -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) {
|
package/dist/http/http-io.d.ts
CHANGED
|
@@ -6,3 +6,5 @@ export type AdminRequest = IncomingMessage & {
|
|
|
6
6
|
export declare function sendJson(res: ServerResponse, status: number, body: unknown): void;
|
|
7
7
|
/** Uses the host-parsed body when present (Nest registers express.json()); otherwise reads the stream. */
|
|
8
8
|
export declare function readJsonBody(req: AdminRequest): Promise<unknown>;
|
|
9
|
+
/** The raw body of an upload, refused (413) past `limit` bytes. A body the host already read as a Buffer is used as is. */
|
|
10
|
+
export declare function readRawBody(req: AdminRequest, limit: number): Promise<Buffer>;
|
package/dist/http/http-io.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AdminBadRequestError } from '../errors.js';
|
|
1
|
+
import { AdminBadRequestError, AdminPayloadTooLargeError } from '../errors.js';
|
|
2
2
|
const MAX_BODY_BYTES = 1_048_576;
|
|
3
3
|
export function sendJson(res, status, body) {
|
|
4
4
|
const payload = JSON.stringify(body);
|
|
@@ -37,4 +37,22 @@ function parseJson(text) {
|
|
|
37
37
|
throw new AdminBadRequestError('Request body is not valid JSON');
|
|
38
38
|
}
|
|
39
39
|
}
|
|
40
|
+
/** The raw body of an upload, refused (413) past `limit` bytes. A body the host already read as a Buffer is used as is. */
|
|
41
|
+
export async function readRawBody(req, limit) {
|
|
42
|
+
if (Buffer.isBuffer(req.body)) {
|
|
43
|
+
if (req.body.length > limit)
|
|
44
|
+
throw new AdminPayloadTooLargeError(`The file is larger than ${limit} bytes`);
|
|
45
|
+
return req.body;
|
|
46
|
+
}
|
|
47
|
+
const chunks = [];
|
|
48
|
+
let size = 0;
|
|
49
|
+
for await (const chunk of req) {
|
|
50
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
51
|
+
size += buffer.length;
|
|
52
|
+
if (size > limit)
|
|
53
|
+
throw new AdminPayloadTooLargeError(`The file is larger than ${limit} bytes`);
|
|
54
|
+
chunks.push(buffer);
|
|
55
|
+
}
|
|
56
|
+
return Buffer.concat(chunks);
|
|
57
|
+
}
|
|
40
58
|
//# sourceMappingURL=http-io.js.map
|
package/dist/http/ui-assets.d.ts
CHANGED
|
@@ -22,12 +22,25 @@ export interface UiPageOptions {
|
|
|
22
22
|
/** The admin's `title`, in every language given. Defaults to the runtime config's title. */
|
|
23
23
|
title?: LocalizedText;
|
|
24
24
|
}
|
|
25
|
+
/** Pictures uploaded in the admin (`appearance`), read on every page load: they win over `branding.logo`. */
|
|
26
|
+
export type UiPictures = () => {
|
|
27
|
+
logo: string | null;
|
|
28
|
+
favicon: string | null;
|
|
29
|
+
};
|
|
30
|
+
/** A `<link rel="icon">` in `<head>` (replacing the build's own, if any). */
|
|
31
|
+
export declare function withFavicon(html: string, href: string): string;
|
|
25
32
|
export declare class UiAssets {
|
|
26
33
|
private readonly runtime;
|
|
34
|
+
private readonly pictures?;
|
|
27
35
|
private readonly root;
|
|
28
36
|
/** index.html as served: in the admin's default locale, with `<base href>` and the runtime config. */
|
|
29
|
-
private
|
|
30
|
-
|
|
37
|
+
private indexHtml;
|
|
38
|
+
/** The page before the runtime config, and the pictures the cached `indexHtml` was made with. */
|
|
39
|
+
private readonly localized;
|
|
40
|
+
private madeFor;
|
|
41
|
+
constructor(distDir: string, runtime: AdminRuntimeConfig, page?: UiPageOptions, pictures?: UiPictures | undefined);
|
|
42
|
+
/** The page with the pictures uploaded now (made again only when they change). */
|
|
43
|
+
private page;
|
|
31
44
|
/** Serves a file, 404s a missing /assets/* file, and falls back to index.html for client-side routes. */
|
|
32
45
|
serve(pathname: string, req: AdminRequest, res: ServerResponse): void;
|
|
33
46
|
private sendFile;
|
package/dist/http/ui-assets.js
CHANGED
|
@@ -92,13 +92,24 @@ export function resolveStaticFile(root, pathname) {
|
|
|
92
92
|
return undefined;
|
|
93
93
|
}
|
|
94
94
|
}
|
|
95
|
+
/** A `<link rel="icon">` in `<head>` (replacing the build's own, if any). */
|
|
96
|
+
export function withFavicon(html, href) {
|
|
97
|
+
const link = `<link rel="icon" href="${escapeAttribute(href)}">`;
|
|
98
|
+
const withoutOwn = html.replace(/<link\b[^>]*\brel\s*=\s*["']?(?:shortcut )?icon["']?[^>]*>/gi, '');
|
|
99
|
+
return withoutOwn.replace(/<\/head\s*>/i, (close) => link + close);
|
|
100
|
+
}
|
|
95
101
|
export class UiAssets {
|
|
96
102
|
runtime;
|
|
103
|
+
pictures;
|
|
97
104
|
root;
|
|
98
105
|
/** index.html as served: in the admin's default locale, with `<base href>` and the runtime config. */
|
|
99
106
|
indexHtml;
|
|
100
|
-
|
|
107
|
+
/** The page before the runtime config, and the pictures the cached `indexHtml` was made with. */
|
|
108
|
+
localized;
|
|
109
|
+
madeFor = '';
|
|
110
|
+
constructor(distDir, runtime, page = {}, pictures) {
|
|
101
111
|
this.runtime = runtime;
|
|
112
|
+
this.pictures = pictures;
|
|
102
113
|
this.root = resolve(distDir);
|
|
103
114
|
const indexPath = join(this.root, 'index.html');
|
|
104
115
|
// index.html as built, or the "missing build" page.
|
|
@@ -107,7 +118,22 @@ export class UiAssets {
|
|
|
107
118
|
// saved another choice, which lives in their browser where the server cannot see it), so `lang`, `dir` and the
|
|
108
119
|
// title are right from the first byte for everyone who has not switched. `Accept-Language` is not consulted.
|
|
109
120
|
const title = resolveText(page.title ?? runtime.title, runtime.locale, runtime.locale);
|
|
110
|
-
this.
|
|
121
|
+
this.localized = localizeDocument(template, { locale: runtime.locale, title });
|
|
122
|
+
this.indexHtml = injectRuntime(this.localized, runtime);
|
|
123
|
+
}
|
|
124
|
+
/** The page with the pictures uploaded now (made again only when they change). */
|
|
125
|
+
page() {
|
|
126
|
+
if (!this.pictures)
|
|
127
|
+
return this.indexHtml;
|
|
128
|
+
const now = this.pictures();
|
|
129
|
+
const key = `${now.logo ?? ''}|${now.favicon ?? ''}`;
|
|
130
|
+
if (key !== this.madeFor) {
|
|
131
|
+
const runtime = now.logo ? { ...this.runtime, branding: { ...this.runtime.branding, logo: now.logo } } : this.runtime;
|
|
132
|
+
const html = injectRuntime(this.localized, runtime);
|
|
133
|
+
this.indexHtml = now.favicon ? withFavicon(html, now.favicon) : html;
|
|
134
|
+
this.madeFor = key;
|
|
135
|
+
}
|
|
136
|
+
return this.indexHtml;
|
|
111
137
|
}
|
|
112
138
|
/** Serves a file, 404s a missing /assets/* file, and falls back to index.html for client-side routes. */
|
|
113
139
|
serve(pathname, req, res) {
|
|
@@ -122,7 +148,7 @@ export class UiAssets {
|
|
|
122
148
|
}
|
|
123
149
|
// One page for every request: no `Vary` (a host's own `Vary` header is left as it is).
|
|
124
150
|
res.setHeader('Content-Language', this.runtime.locale);
|
|
125
|
-
this.send(req, res, 200, 'text/html; charset=utf-8', this.
|
|
151
|
+
this.send(req, res, 200, 'text/html; charset=utf-8', this.page(), 'no-cache');
|
|
126
152
|
}
|
|
127
153
|
sendFile(file, pathname, req, res) {
|
|
128
154
|
let size;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nest-my-admin/core",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.1",
|
|
4
4
|
"description": "Django-admin-class admin panel for NestJS + TypeORM",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
36
36
|
},
|
|
37
37
|
"dependencies": {
|
|
38
|
-
"@nest-my-admin/ui": "0.8.
|
|
38
|
+
"@nest-my-admin/ui": "0.8.1"
|
|
39
39
|
},
|
|
40
40
|
"peerDependencies": {
|
|
41
41
|
"@nestjs/common": "^11.0.0 || ^12.0.0",
|