@contember/engine-panel 2.2.0-alpha.4
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/CLAUDE.md +29 -0
- package/dist/development/index.cjs +21 -0
- package/dist/development/index.cjs.map +1 -0
- package/dist/development/index.js +21 -0
- package/dist/development/index.js.map +1 -0
- package/dist/development/src/PanelAccessCheck.cjs +21 -0
- package/dist/development/src/PanelAccessCheck.cjs.map +1 -0
- package/dist/development/src/PanelAccessCheck.js +21 -0
- package/dist/development/src/PanelAccessCheck.js.map +1 -0
- package/dist/development/src/PanelApiController.cjs +60 -0
- package/dist/development/src/PanelApiController.cjs.map +1 -0
- package/dist/development/src/PanelApiController.js +60 -0
- package/dist/development/src/PanelApiController.js.map +1 -0
- package/dist/development/src/PanelAssets.cjs +57 -0
- package/dist/development/src/PanelAssets.cjs.map +1 -0
- package/dist/development/src/PanelAssets.js +57 -0
- package/dist/development/src/PanelAssets.js.map +1 -0
- package/dist/development/src/PanelController.cjs +108 -0
- package/dist/development/src/PanelController.cjs.map +1 -0
- package/dist/development/src/PanelController.js +108 -0
- package/dist/development/src/PanelController.js.map +1 -0
- package/dist/development/src/PanelMount.cjs +27 -0
- package/dist/development/src/PanelMount.cjs.map +1 -0
- package/dist/development/src/PanelMount.js +27 -0
- package/dist/development/src/PanelMount.js.map +1 -0
- package/dist/development/src/PanelPlugin.cjs +66 -0
- package/dist/development/src/PanelPlugin.cjs.map +1 -0
- package/dist/development/src/PanelPlugin.js +66 -0
- package/dist/development/src/PanelPlugin.js.map +1 -0
- package/dist/development/src/TtlCache.cjs +47 -0
- package/dist/development/src/TtlCache.cjs.map +1 -0
- package/dist/development/src/TtlCache.js +47 -0
- package/dist/development/src/TtlCache.js.map +1 -0
- package/dist/development/src/generated/assets.cjs +46 -0
- package/dist/development/src/generated/assets.cjs.map +1 -0
- package/dist/development/src/generated/assets.js +46 -0
- package/dist/development/src/generated/assets.js.map +1 -0
- package/dist/production/index.cjs +21 -0
- package/dist/production/index.cjs.map +1 -0
- package/dist/production/index.js +21 -0
- package/dist/production/index.js.map +1 -0
- package/dist/production/src/PanelAccessCheck.cjs +21 -0
- package/dist/production/src/PanelAccessCheck.cjs.map +1 -0
- package/dist/production/src/PanelAccessCheck.js +21 -0
- package/dist/production/src/PanelAccessCheck.js.map +1 -0
- package/dist/production/src/PanelApiController.cjs +60 -0
- package/dist/production/src/PanelApiController.cjs.map +1 -0
- package/dist/production/src/PanelApiController.js +60 -0
- package/dist/production/src/PanelApiController.js.map +1 -0
- package/dist/production/src/PanelAssets.cjs +57 -0
- package/dist/production/src/PanelAssets.cjs.map +1 -0
- package/dist/production/src/PanelAssets.js +57 -0
- package/dist/production/src/PanelAssets.js.map +1 -0
- package/dist/production/src/PanelController.cjs +108 -0
- package/dist/production/src/PanelController.cjs.map +1 -0
- package/dist/production/src/PanelController.js +108 -0
- package/dist/production/src/PanelController.js.map +1 -0
- package/dist/production/src/PanelMount.cjs +27 -0
- package/dist/production/src/PanelMount.cjs.map +1 -0
- package/dist/production/src/PanelMount.js +27 -0
- package/dist/production/src/PanelMount.js.map +1 -0
- package/dist/production/src/PanelPlugin.cjs +66 -0
- package/dist/production/src/PanelPlugin.cjs.map +1 -0
- package/dist/production/src/PanelPlugin.js +66 -0
- package/dist/production/src/PanelPlugin.js.map +1 -0
- package/dist/production/src/TtlCache.cjs +47 -0
- package/dist/production/src/TtlCache.cjs.map +1 -0
- package/dist/production/src/TtlCache.js +47 -0
- package/dist/production/src/TtlCache.js.map +1 -0
- package/dist/production/src/generated/assets.cjs +46 -0
- package/dist/production/src/generated/assets.cjs.map +1 -0
- package/dist/production/src/generated/assets.js +46 -0
- package/dist/production/src/generated/assets.js.map +1 -0
- package/dist/tests/cases/unit/panelController.test.d.ts +2 -0
- package/dist/tests/cases/unit/panelController.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/panelMount.test.d.ts +2 -0
- package/dist/tests/cases/unit/panelMount.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/ttlCache.test.d.ts +2 -0
- package/dist/tests/cases/unit/ttlCache.test.d.ts.map +1 -0
- package/dist/tests/tsconfig.tsbuildinfo +1 -0
- package/dist/types/PanelAccessCheck.d.ts +16 -0
- package/dist/types/PanelAccessCheck.d.ts.map +1 -0
- package/dist/types/PanelApiController.d.ts +58 -0
- package/dist/types/PanelApiController.d.ts.map +1 -0
- package/dist/types/PanelAssets.d.ts +32 -0
- package/dist/types/PanelAssets.d.ts.map +1 -0
- package/dist/types/PanelController.d.ts +46 -0
- package/dist/types/PanelController.d.ts.map +1 -0
- package/dist/types/PanelMount.d.ts +26 -0
- package/dist/types/PanelMount.d.ts.map +1 -0
- package/dist/types/PanelPlugin.d.ts +6 -0
- package/dist/types/PanelPlugin.d.ts.map +1 -0
- package/dist/types/TtlCache.d.ts +16 -0
- package/dist/types/TtlCache.d.ts.map +1 -0
- package/dist/types/generated/assets.d.ts +3 -0
- package/dist/types/generated/assets.d.ts.map +1 -0
- package/dist/types/index.d.ts +10 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/tsconfig.tsbuildinfo +1 -0
- package/package.json +40 -0
- package/scripts/buildAssets.ts +79 -0
- package/src/PanelAccessCheck.ts +24 -0
- package/src/PanelApiController.ts +126 -0
- package/src/PanelAssets.ts +69 -0
- package/src/PanelController.ts +166 -0
- package/src/PanelMount.ts +34 -0
- package/src/PanelPlugin.ts +77 -0
- package/src/TtlCache.ts +53 -0
- package/src/index.ts +11 -0
- package/src/tsconfig.json +9 -0
- package/tests/cases/unit/panelController.test.ts +159 -0
- package/tests/cases/unit/panelMount.test.ts +55 -0
- package/tests/cases/unit/ttlCache.test.ts +55 -0
- package/tests/tsconfig.json +9 -0
- package/tsconfig.json +8 -0
- package/tsconfig.settings.json +6 -0
package/package.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@contember/engine-panel",
|
|
3
|
+
"license": "Apache-2.0",
|
|
4
|
+
"version": "2.2.0-alpha.4",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/production/index.js",
|
|
7
|
+
"typings": "./dist/types/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": {
|
|
11
|
+
"types": "./dist/types/index.d.ts",
|
|
12
|
+
"development": "./dist/development/index.js",
|
|
13
|
+
"production": "./dist/production/index.js",
|
|
14
|
+
"typescript": "./src/index.ts",
|
|
15
|
+
"default": "./dist/production/index.js"
|
|
16
|
+
},
|
|
17
|
+
"require": {
|
|
18
|
+
"types": "./dist/types/index.d.ts",
|
|
19
|
+
"development": "./dist/development/index.cjs",
|
|
20
|
+
"production": "./dist/production/index.cjs",
|
|
21
|
+
"typescript": "./src/index.ts",
|
|
22
|
+
"default": "./dist/production/index.cjs"
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
"scripts": {
|
|
27
|
+
"build:assets": "bun ./scripts/buildAssets.ts"
|
|
28
|
+
},
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "git+https://github.com/contember/contember.git",
|
|
32
|
+
"directory": "packages/engine-panel"
|
|
33
|
+
},
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"@contember/engine-http": "2.2.0-alpha.4"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"@types/node": "^24.12.0"
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds the panel UI and embeds it into `src/generated/assets.ts`.
|
|
3
|
+
*
|
|
4
|
+
* The engine docker image contains a single bundled `dist/start.js` and nothing else, so there is no
|
|
5
|
+
* directory to serve static files from — the assets travel inside the bundle. Everything is stored
|
|
6
|
+
* gzipped so the payload stays close to what a browser would download anyway, and so the controller
|
|
7
|
+
* can hand the bytes over without compressing per request.
|
|
8
|
+
*/
|
|
9
|
+
import { spawnSync } from 'node:child_process'
|
|
10
|
+
import { constants as zlibConstants, gzipSync } from 'node:zlib'
|
|
11
|
+
import { mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
12
|
+
import { dirname, join, relative, resolve, sep } from 'node:path'
|
|
13
|
+
|
|
14
|
+
const packageDir = resolve(import.meta.dir, '..')
|
|
15
|
+
const uiDir = resolve(packageDir, '../panel-ui')
|
|
16
|
+
const distDir = join(uiDir, 'dist')
|
|
17
|
+
const outputFile = join(packageDir, 'src/generated/assets.ts')
|
|
18
|
+
|
|
19
|
+
const contentTypes: Record<string, string> = {
|
|
20
|
+
'.css': 'text/css; charset=utf-8',
|
|
21
|
+
'.html': 'text/html; charset=utf-8',
|
|
22
|
+
'.ico': 'image/x-icon',
|
|
23
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
24
|
+
'.json': 'application/json; charset=utf-8',
|
|
25
|
+
'.png': 'image/png',
|
|
26
|
+
'.svg': 'image/svg+xml',
|
|
27
|
+
'.webp': 'image/webp',
|
|
28
|
+
'.woff2': 'font/woff2',
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const contentTypeOf = (path: string): string => {
|
|
32
|
+
const ext = path.slice(path.lastIndexOf('.'))
|
|
33
|
+
return contentTypes[ext] ?? 'application/octet-stream'
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const listFiles = (dir: string): string[] =>
|
|
37
|
+
readdirSync(dir, { withFileTypes: true }).flatMap(entry => {
|
|
38
|
+
const path = join(dir, entry.name)
|
|
39
|
+
return entry.isDirectory() ? listFiles(path) : [path]
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
const build = spawnSync('bun', ['run', 'build'], { cwd: uiDir, stdio: 'inherit' })
|
|
43
|
+
if (build.status !== 0) {
|
|
44
|
+
throw new Error('Failed to build @contember/panel-ui.')
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Source maps would roughly double the embedded payload and hand out the console's sources; the
|
|
48
|
+
// panel is debugged from a dev build.
|
|
49
|
+
const files = listFiles(distDir).filter(it => !it.endsWith('.map'))
|
|
50
|
+
if (!files.some(it => relative(distDir, it) === 'index.html')) {
|
|
51
|
+
throw new Error(`No index.html in ${distDir} — the panel build produced nothing usable.`)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
let totalRaw = 0
|
|
55
|
+
let totalGzip = 0
|
|
56
|
+
const entries = files
|
|
57
|
+
.map(file => {
|
|
58
|
+
const path = relative(distDir, file).split(sep).join('/')
|
|
59
|
+
const raw = readFileSync(file)
|
|
60
|
+
const gzip = gzipSync(raw, { level: zlibConstants.Z_BEST_COMPRESSION })
|
|
61
|
+
totalRaw += raw.byteLength
|
|
62
|
+
totalGzip += gzip.byteLength
|
|
63
|
+
return `\t${JSON.stringify(path)}: { contentType: ${JSON.stringify(contentTypeOf(path))}, gzip: ${JSON.stringify(gzip.toString('base64'))} },`
|
|
64
|
+
})
|
|
65
|
+
.sort()
|
|
66
|
+
|
|
67
|
+
const output = `import type { PanelAssetMap } from '../PanelAssets.js'
|
|
68
|
+
|
|
69
|
+
// Generated by scripts/buildAssets.ts — do not edit.
|
|
70
|
+
export const panelAssets: PanelAssetMap = {
|
|
71
|
+
${entries.join('\n')}
|
|
72
|
+
}
|
|
73
|
+
`
|
|
74
|
+
|
|
75
|
+
mkdirSync(dirname(outputFile), { recursive: true })
|
|
76
|
+
writeFileSync(outputFile, output)
|
|
77
|
+
|
|
78
|
+
const kb = (bytes: number) => `${(bytes / 1024).toFixed(1)} kB`
|
|
79
|
+
console.log(`engine-panel: embedded ${files.length} files, ${kb(totalRaw)} raw / ${kb(totalGzip)} gzipped (${kb(output.length)} of source).`)
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { AuthResult, ProjectGroupContainer } from '@contember/engine-http'
|
|
2
|
+
import type { PanelAccessCheck } from './PanelApiController.js'
|
|
3
|
+
import { TtlCache } from './TtlCache.js'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Evaluates the tenant-configured panel policy, memoized per api key so a page of parallel requests
|
|
7
|
+
* costs one lookup rather than one per request. The TTL is deliberately short: revoking someone's
|
|
8
|
+
* access should take effect in seconds, not on their next sign-in.
|
|
9
|
+
*/
|
|
10
|
+
export class ConfiguredPanelAccessCheck implements PanelAccessCheck {
|
|
11
|
+
private readonly cache: TtlCache<boolean>
|
|
12
|
+
|
|
13
|
+
constructor(ttlMs: number = 10_000) {
|
|
14
|
+
this.cache = new TtlCache(ttlMs)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
public async isAllowed({ projectGroup, authResult }: { projectGroup: ProjectGroupContainer; authResult: AuthResult }): Promise<boolean> {
|
|
18
|
+
const { panelAccessResolver, databaseContext } = projectGroup.tenantContainer
|
|
19
|
+
return await this.cache.resolve(
|
|
20
|
+
`${projectGroup.slug ?? ''}:${authResult.apiKeyId}`,
|
|
21
|
+
() => panelAccessResolver.isAllowed(databaseContext, authResult.identityId, authResult.roles),
|
|
22
|
+
)
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import type { IncomingHttpHeaders } from 'node:http'
|
|
2
|
+
import type { AuthResult, HttpController, ProjectGroupContainer } from '@contember/engine-http'
|
|
3
|
+
import { createUnpersistedLoginVerifyResult, HttpErrorResponse } from '@contember/engine-http'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Decides whether a signed-in identity may use the management panel. This is an entry gate for the
|
|
7
|
+
* console, not an authorization system — every API the panel calls still enforces the tenant ACL.
|
|
8
|
+
*/
|
|
9
|
+
export interface PanelAccessCheck {
|
|
10
|
+
isAllowed(args: { projectGroup: ProjectGroupContainer; authResult: AuthResult }): Promise<boolean>
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface PanelApiControllerOptions {
|
|
14
|
+
/**
|
|
15
|
+
* Whether a request carrying no credentials may act as the virtual `login` identity. Only the
|
|
16
|
+
* tenant mount has a pre-sign-in caller (the login screen); content and system do not, so they
|
|
17
|
+
* answer 401 rather than widening the anonymous surface for nobody.
|
|
18
|
+
*/
|
|
19
|
+
allowAnonymous: boolean
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Wraps an API controller (tenant / content / system) for the panel's own `/panel/api/*` mount.
|
|
24
|
+
*
|
|
25
|
+
* Two things happen here that do not happen on the public routes:
|
|
26
|
+
*
|
|
27
|
+
* 1. **Anonymous calls act as a virtual `login` identity.** The panel's sign-in screen has no
|
|
28
|
+
* credentials of its own, and shipping a login token to the browser — which is what every
|
|
29
|
+
* Contember admin app does today — would publish it. Instead the caller is given
|
|
30
|
+
* `createUnpersistedLoginVerifyResult()`: no token exists anywhere, no `api_key` row is read or
|
|
31
|
+
* written, and the roles are pinned in code, so a misconfigured `CONTEMBER_LOGIN_TOKEN` cannot
|
|
32
|
+
* turn this into anything but `login`. Browser requests must be same-origin; direct clients can
|
|
33
|
+
* reproduce the required headers. See {@link isSameOriginBrowser}.
|
|
34
|
+
* 2. **The access gate runs.** Anything the caller authenticated itself is checked against the
|
|
35
|
+
* configured panel policy before it reaches the API.
|
|
36
|
+
*/
|
|
37
|
+
export class PanelApiControllerFactory {
|
|
38
|
+
constructor(private readonly access: PanelAccessCheck) {}
|
|
39
|
+
|
|
40
|
+
public create(inner: HttpController, { allowAnonymous }: PanelApiControllerOptions): HttpController {
|
|
41
|
+
return async ctx => {
|
|
42
|
+
if (ctx.authResult) {
|
|
43
|
+
// The caller presented its own credentials, so the panel gate applies.
|
|
44
|
+
if (!await this.access.isAllowed({ projectGroup: ctx.projectGroup, authResult: ctx.authResult })) {
|
|
45
|
+
return accessDeniedResponse()
|
|
46
|
+
}
|
|
47
|
+
return await inner(ctx)
|
|
48
|
+
}
|
|
49
|
+
if (!allowAnonymous) {
|
|
50
|
+
return new HttpErrorResponse(401, 'Authentication required')
|
|
51
|
+
}
|
|
52
|
+
if (!isSameOriginBrowser(ctx.request.headers)) {
|
|
53
|
+
return crossOriginDeniedResponse()
|
|
54
|
+
}
|
|
55
|
+
const authResult = await ctx.projectGroup.authenticator.authenticate({
|
|
56
|
+
request: ctx.request,
|
|
57
|
+
timer: ctx.timer,
|
|
58
|
+
clientIp: ctx.clientIp,
|
|
59
|
+
fallbackIdentity: createUnpersistedLoginVerifyResult(),
|
|
60
|
+
})
|
|
61
|
+
if (!authResult) {
|
|
62
|
+
return new HttpErrorResponse(401, 'Authentication required')
|
|
63
|
+
}
|
|
64
|
+
// Nothing to gate yet: this is the pre-sign-in panel, not an identity.
|
|
65
|
+
return await inner({ ...ctx, authResult })
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Whether the request carries same-origin browser signals. This is a CSRF check, not client
|
|
72
|
+
* authentication: a direct client can reproduce these headers.
|
|
73
|
+
*
|
|
74
|
+
* A cross-origin page is kept out: the app-wide CORS headers would otherwise let any site drive
|
|
75
|
+
* sign-in, password reset and magic links from a visitor's browser, spreading the per-IP rate limits
|
|
76
|
+
* across those visitors' addresses. Rate limits remain the protection against direct abuse.
|
|
77
|
+
*
|
|
78
|
+
* A browser signal is required. Current browsers send `Sec-Fetch-Site`; older browsers send `Origin`
|
|
79
|
+
* on a POST, including a same-origin one.
|
|
80
|
+
*/
|
|
81
|
+
const isSameOriginBrowser = (headers: IncomingHttpHeaders): boolean => {
|
|
82
|
+
const secFetchSite = headerValue(headers['sec-fetch-site'])
|
|
83
|
+
if (secFetchSite !== undefined) {
|
|
84
|
+
// `none` is a user-initiated navigation (typed URL, bookmark); `fetch` never produces it.
|
|
85
|
+
return secFetchSite === 'same-origin' || secFetchSite === 'none'
|
|
86
|
+
}
|
|
87
|
+
const origin = headerValue(headers['origin'])
|
|
88
|
+
if (origin === undefined) {
|
|
89
|
+
return false
|
|
90
|
+
}
|
|
91
|
+
const host = headerValue(headers['host'])
|
|
92
|
+
try {
|
|
93
|
+
// Hostname, not host: a TLS-terminating proxy commonly rewrites the port into `Host`, and the
|
|
94
|
+
// port is not what this check is defending.
|
|
95
|
+
return host !== undefined && new URL(origin).hostname === new URL(`http://${host}`).hostname
|
|
96
|
+
} catch {
|
|
97
|
+
return false
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const headerValue = (header: string | string[] | undefined): string | undefined => Array.isArray(header) ? header[0] : header
|
|
102
|
+
|
|
103
|
+
const crossOriginDeniedResponse = (): HttpErrorResponse =>
|
|
104
|
+
new HttpErrorResponse(403, 'PANEL_CROSS_ORIGIN_DENIED: the panel API accepts anonymous calls from its own origin only.')
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Names the gate as the source of a 403, because the status alone does not: the system API answers
|
|
108
|
+
* 403 for a project the caller is not a member of when the server runs in debug mode, and the content
|
|
109
|
+
* API does the same for a rejected `assumeMembership`. Without this header the panel would read either
|
|
110
|
+
* of those as "you may not be here" and throw the whole session away.
|
|
111
|
+
*
|
|
112
|
+
* `GraphQlClient` drops the body of a 403 but keeps the `Response`, so a header is what reaches the
|
|
113
|
+
* client. The panel is served from this origin, so it is readable without `Access-Control-Expose-Headers`.
|
|
114
|
+
* The client half is `isPanelAccessDenied` in `panel-ui/src/shell/accessDenied.ts`.
|
|
115
|
+
*/
|
|
116
|
+
export const panelErrorHeader = 'X-Contember-Panel-Error'
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* 403 rather than a GraphQL error, so the panel can tell "you may not be here" apart from "you may
|
|
120
|
+
* not see this particular thing" (which the APIs report as a 200 with a `ForbiddenError` extension).
|
|
121
|
+
* The message is for operators reading logs; the browser acts on {@link panelErrorHeader}.
|
|
122
|
+
*/
|
|
123
|
+
export const accessDeniedResponse = (): HttpErrorResponse =>
|
|
124
|
+
new HttpErrorResponse(403, 'PANEL_ACCESS_DENIED: this identity is not allowed to use the management panel.', {
|
|
125
|
+
[panelErrorHeader]: 'PANEL_ACCESS_DENIED',
|
|
126
|
+
})
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { gunzipSync } from 'node:zlib'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A single file of the built panel UI. Every entry is stored gzip-compressed and base64-encoded so
|
|
5
|
+
* the whole panel can be bundled into `dist/start.js` — the engine docker image contains nothing but
|
|
6
|
+
* that one file, so there is no directory to serve from.
|
|
7
|
+
*/
|
|
8
|
+
export interface PanelAsset {
|
|
9
|
+
readonly contentType: string
|
|
10
|
+
/** gzip-compressed content, base64-encoded. */
|
|
11
|
+
readonly gzip: string
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Keys are paths relative to the panel root, without a leading slash (`assets/index-a1b2.js`). */
|
|
15
|
+
export type PanelAssetMap = Readonly<Record<string, PanelAsset>>
|
|
16
|
+
|
|
17
|
+
export const indexAssetPath = 'index.html'
|
|
18
|
+
|
|
19
|
+
export class PanelAssetStore {
|
|
20
|
+
private readonly gzip = new Map<string, Buffer>()
|
|
21
|
+
private readonly identity = new Map<string, Buffer>()
|
|
22
|
+
|
|
23
|
+
constructor(private readonly assets: PanelAssetMap) {}
|
|
24
|
+
|
|
25
|
+
/** True when the panel was not built into this binary — see `scripts/buildAssets.ts`. */
|
|
26
|
+
public isEmpty(): boolean {
|
|
27
|
+
return this.get(indexAssetPath) === undefined
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
public getContentType(path: string): string | undefined {
|
|
31
|
+
return this.get(path)?.contentType
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Gzipped bytes, decoded from base64 on first use and kept for the process lifetime. */
|
|
35
|
+
public getGzip(path: string): Buffer | undefined {
|
|
36
|
+
const asset = this.get(path)
|
|
37
|
+
if (!asset) {
|
|
38
|
+
return undefined
|
|
39
|
+
}
|
|
40
|
+
let decoded = this.gzip.get(path)
|
|
41
|
+
if (!decoded) {
|
|
42
|
+
decoded = Buffer.from(asset.gzip, 'base64')
|
|
43
|
+
this.gzip.set(path, decoded)
|
|
44
|
+
}
|
|
45
|
+
return decoded
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Uncompressed bytes, decoded once for clients that do not accept gzip. */
|
|
49
|
+
public getIdentity(path: string): Buffer | undefined {
|
|
50
|
+
const gzip = this.getGzip(path)
|
|
51
|
+
if (gzip === undefined) {
|
|
52
|
+
return undefined
|
|
53
|
+
}
|
|
54
|
+
let identity = this.identity.get(path)
|
|
55
|
+
if (!identity) {
|
|
56
|
+
identity = gunzipSync(gzip)
|
|
57
|
+
this.identity.set(path, identity)
|
|
58
|
+
}
|
|
59
|
+
return identity
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The map is a plain object literal, so a request for `constructor` or `toString` would otherwise
|
|
64
|
+
* resolve an inherited member and blow up further down. The route is unauthenticated.
|
|
65
|
+
*/
|
|
66
|
+
private get(path: string): PanelAsset | undefined {
|
|
67
|
+
return Object.hasOwn(this.assets, path) ? this.assets[path] : undefined
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { gunzipSync, gzipSync } from 'node:zlib'
|
|
2
|
+
import type { InternalHttpContext, InternalHttpController } from '@contember/engine-http'
|
|
3
|
+
import { indexAssetPath, PanelAssetStore } from './PanelAssets.js'
|
|
4
|
+
|
|
5
|
+
export interface PanelControllerArgs {
|
|
6
|
+
/** Mount path without a trailing slash, e.g. `/panel`. */
|
|
7
|
+
basePath: string
|
|
8
|
+
/** Prefix the panel prepends to every API path, e.g. `/panel/api`. */
|
|
9
|
+
apiBaseUrl: string
|
|
10
|
+
assets: PanelAssetStore
|
|
11
|
+
/** Plugin APIs mounted under {@link apiBaseUrl}; read on the first request, see {@link PanelController.indexHtml}. */
|
|
12
|
+
pluginApis: () => readonly string[]
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Everything the controller reads from a request — see {@link PanelController.handle}. */
|
|
16
|
+
export interface PanelRequest {
|
|
17
|
+
method: string
|
|
18
|
+
/** Path relative to the panel root, i.e. the route's wildcard parameter. */
|
|
19
|
+
path: string | undefined
|
|
20
|
+
acceptEncoding: string | undefined
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface PanelResponse {
|
|
24
|
+
status: number
|
|
25
|
+
headers: Readonly<Record<string, string>>
|
|
26
|
+
body: Buffer
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const basePlaceholder = '__CONTEMBER_PANEL_BASE__'
|
|
30
|
+
const configPlaceholder = '__CONTEMBER_PANEL_CONFIG__'
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* `style-src` allows inline styles because the component libraries set `style` attributes; nothing
|
|
34
|
+
* else is relaxed, and no external origin is reachable at all.
|
|
35
|
+
*/
|
|
36
|
+
const contentSecurityPolicy = [
|
|
37
|
+
`default-src 'self'`,
|
|
38
|
+
`script-src 'self'`,
|
|
39
|
+
`style-src 'self' 'unsafe-inline'`,
|
|
40
|
+
`img-src 'self' data:`,
|
|
41
|
+
`font-src 'self' data:`,
|
|
42
|
+
`connect-src 'self'`,
|
|
43
|
+
`base-uri 'self'`,
|
|
44
|
+
`form-action 'self'`,
|
|
45
|
+
`frame-ancestors 'none'`,
|
|
46
|
+
].join('; ')
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Serves the built panel UI out of the bundled asset map.
|
|
50
|
+
*
|
|
51
|
+
* Registered as an *internal* route: static assets must not authenticate, and going through the
|
|
52
|
+
* regular pipeline would resolve a project group and verify an API key against the database on every
|
|
53
|
+
* file request. The panel's API traffic is a separate, regular route.
|
|
54
|
+
*/
|
|
55
|
+
export class PanelController {
|
|
56
|
+
/**
|
|
57
|
+
* Rendered on the first request rather than here: the plugins that mount their API into the panel
|
|
58
|
+
* are not all registered yet while the container is still being built, and the shell carries the
|
|
59
|
+
* list. Built once and kept, since nothing in it can change afterwards.
|
|
60
|
+
*/
|
|
61
|
+
private indexHtml: { gzip: Buffer; identity: Buffer } | undefined
|
|
62
|
+
private readonly indexSource: Buffer
|
|
63
|
+
|
|
64
|
+
constructor(private readonly args: PanelControllerArgs) {
|
|
65
|
+
const source = args.assets.getGzip(indexAssetPath)
|
|
66
|
+
if (source === undefined) {
|
|
67
|
+
throw new Error('The panel UI was not built into this binary. Run `bun run pre-build` before building the server.')
|
|
68
|
+
}
|
|
69
|
+
this.indexSource = source
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
public create(): InternalHttpController {
|
|
73
|
+
return (ctx: InternalHttpContext) => {
|
|
74
|
+
const response = this.handle({
|
|
75
|
+
method: ctx.koa.method,
|
|
76
|
+
path: typeof ctx.params.path === 'string' ? ctx.params.path : undefined,
|
|
77
|
+
acceptEncoding: headerValue(ctx.request.headers['accept-encoding']),
|
|
78
|
+
})
|
|
79
|
+
ctx.koa.status = response.status
|
|
80
|
+
for (const [name, value] of Object.entries(response.headers)) {
|
|
81
|
+
ctx.koa.set(name, value)
|
|
82
|
+
}
|
|
83
|
+
ctx.koa.body = response.body
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
public handle(request: PanelRequest): PanelResponse {
|
|
88
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
|
89
|
+
return { status: 405, headers: { 'Allow': 'GET, HEAD' }, body: Buffer.alloc(0) }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const path = normalizePath(request.path)
|
|
93
|
+
const gzip = path === undefined || path === indexAssetPath ? undefined : this.args.assets.getGzip(path)
|
|
94
|
+
|
|
95
|
+
if (path === undefined || gzip === undefined) {
|
|
96
|
+
// Anything that is not a built file is a client-side route — serve the app shell.
|
|
97
|
+
this.indexHtml ??= this.renderIndex()
|
|
98
|
+
return this.respond(request, this.indexHtml.gzip, () => this.indexHtml?.identity, {
|
|
99
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
100
|
+
'Cache-Control': 'no-store',
|
|
101
|
+
'Content-Security-Policy': contentSecurityPolicy,
|
|
102
|
+
'X-Robots-Tag': 'noindex, nofollow',
|
|
103
|
+
'Referrer-Policy': 'no-referrer',
|
|
104
|
+
})
|
|
105
|
+
}
|
|
106
|
+
// Every built file name carries a content hash, so it can never change under the same URL.
|
|
107
|
+
return this.respond(request, gzip, () => this.args.assets.getIdentity(path), {
|
|
108
|
+
'Content-Type': this.args.assets.getContentType(path) ?? 'application/octet-stream',
|
|
109
|
+
'Cache-Control': 'public, max-age=31536000, immutable',
|
|
110
|
+
})
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
private respond(request: PanelRequest, gzipped: Buffer, identity: () => Buffer | undefined, headers: Record<string, string>): PanelResponse {
|
|
114
|
+
const common = {
|
|
115
|
+
...headers,
|
|
116
|
+
'Vary': 'Accept-Encoding',
|
|
117
|
+
'X-Content-Type-Options': 'nosniff',
|
|
118
|
+
}
|
|
119
|
+
if (acceptsGzip(request.acceptEncoding)) {
|
|
120
|
+
return { status: 200, headers: { ...common, 'Content-Encoding': 'gzip' }, body: request.method === 'HEAD' ? Buffer.alloc(0) : gzipped }
|
|
121
|
+
}
|
|
122
|
+
return { status: 200, headers: common, body: request.method === 'HEAD' ? Buffer.alloc(0) : identity() ?? Buffer.alloc(0) }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
private renderIndex(): { gzip: Buffer; identity: Buffer } {
|
|
126
|
+
const config = JSON.stringify({
|
|
127
|
+
basePath: `${this.args.basePath}/`,
|
|
128
|
+
apiBaseUrl: this.args.apiBaseUrl,
|
|
129
|
+
pluginApis: this.args.pluginApis(),
|
|
130
|
+
})
|
|
131
|
+
const identity = Buffer.from(
|
|
132
|
+
gunzipSync(this.indexSource)
|
|
133
|
+
.toString('utf8')
|
|
134
|
+
// An absolute base href keeps the relative asset URLs resolving from the panel root at any
|
|
135
|
+
// route depth, which is what lets the mount path stay configurable.
|
|
136
|
+
.replaceAll(basePlaceholder, () => `${this.args.basePath}/`)
|
|
137
|
+
.replaceAll(configPlaceholder, () => config),
|
|
138
|
+
)
|
|
139
|
+
return { gzip: gzipSync(identity), identity }
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const headerValue = (header: string | string[] | undefined): string | undefined => Array.isArray(header) ? header.join(',') : header
|
|
144
|
+
|
|
145
|
+
const acceptsGzip = (acceptEncoding: string | undefined): boolean =>
|
|
146
|
+
acceptEncoding !== undefined && /(^|,)\s*(gzip|\*)\s*(;|,|$)/.test(acceptEncoding)
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* `undefined` for the panel root, `undefined` for anything that tries to escape the asset map;
|
|
150
|
+
* both fall through to the app shell.
|
|
151
|
+
*/
|
|
152
|
+
const normalizePath = (raw: string | undefined): string | undefined => {
|
|
153
|
+
if (raw === undefined || raw === '') {
|
|
154
|
+
return undefined
|
|
155
|
+
}
|
|
156
|
+
let decoded: string
|
|
157
|
+
try {
|
|
158
|
+
decoded = decodeURIComponent(raw)
|
|
159
|
+
} catch {
|
|
160
|
+
return undefined
|
|
161
|
+
}
|
|
162
|
+
if (decoded.includes('\0') || decoded.split('/').includes('..')) {
|
|
163
|
+
return undefined
|
|
164
|
+
}
|
|
165
|
+
return decoded
|
|
166
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { PanelApiMount, PanelApiMountArgs, PanelApiMountTarget } from '@contember/engine-http'
|
|
2
|
+
import type { PanelApiControllerFactory } from './PanelApiController.js'
|
|
3
|
+
import type { PanelAssetStore } from './PanelAssets.js'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Everything needed to serve the panel, resolved once. It exists only when the panel really is
|
|
7
|
+
* served — enabled *and* built into this binary — so a plugin can read "this resolved" as "there is
|
|
8
|
+
* a panel to mount into" and skip its panel route otherwise.
|
|
9
|
+
*/
|
|
10
|
+
export class PanelMount implements PanelApiMount {
|
|
11
|
+
private readonly pluginApiNames = new Set<string>()
|
|
12
|
+
|
|
13
|
+
constructor(
|
|
14
|
+
public readonly basePath: string,
|
|
15
|
+
public readonly assets: PanelAssetStore,
|
|
16
|
+
/** Shared with the panel's own routes: one factory means one access-check cache for all of them. */
|
|
17
|
+
public readonly api: PanelApiControllerFactory,
|
|
18
|
+
) {
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
public mount(application: PanelApiMountTarget, { name, path, controller }: PanelApiMountArgs): void {
|
|
22
|
+
application.addRoute('panel-api', `${this.basePath}/api/${path}`, this.api.create(controller, { allowAnonymous: false }))
|
|
23
|
+
this.pluginApiNames.add(name)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* APIs plugins have mounted, reported to the UI so a module can hide itself when the plugin that
|
|
28
|
+
* backs it is not installed. Read when the shell is rendered, not when it is constructed, so a
|
|
29
|
+
* plugin registering after the panel is still counted.
|
|
30
|
+
*/
|
|
31
|
+
public get pluginApis(): readonly string[] {
|
|
32
|
+
return [...this.pluginApiNames].sort()
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { MasterContainerBuilder, MasterContainerHook, Plugin } from '@contember/engine-http'
|
|
2
|
+
import { panelAssets } from './generated/assets.js'
|
|
3
|
+
import { ConfiguredPanelAccessCheck } from './PanelAccessCheck.js'
|
|
4
|
+
import { PanelApiControllerFactory } from './PanelApiController.js'
|
|
5
|
+
import { PanelAssetStore } from './PanelAssets.js'
|
|
6
|
+
import { PanelController } from './PanelController.js'
|
|
7
|
+
import { PanelMount } from './PanelMount.js'
|
|
8
|
+
|
|
9
|
+
const defaultBasePath = '/panel'
|
|
10
|
+
|
|
11
|
+
export class PanelPlugin implements Plugin {
|
|
12
|
+
name = 'contember/panel'
|
|
13
|
+
|
|
14
|
+
getMasterContainerHook(): MasterContainerHook {
|
|
15
|
+
return (builder: MasterContainerBuilder) =>
|
|
16
|
+
builder
|
|
17
|
+
.replaceService('panelApiMount', ({ serverConfig, logger, inner }) => {
|
|
18
|
+
if (serverConfig.panel?.enabled !== true) {
|
|
19
|
+
return inner
|
|
20
|
+
}
|
|
21
|
+
const assets = new PanelAssetStore(panelAssets)
|
|
22
|
+
if (assets.isEmpty()) {
|
|
23
|
+
// Running from source without the build step. A released build cannot get here —
|
|
24
|
+
// `scripts/buildAssets.ts` fails when the panel produced nothing — so this is a
|
|
25
|
+
// developer's checkout, and refusing to start would be a poor trade.
|
|
26
|
+
logger.error(
|
|
27
|
+
new Error(
|
|
28
|
+
'The panel is enabled but this build contains no panel assets — run `bun run --filter=@contember/engine-panel build:assets`. Not serving the panel.',
|
|
29
|
+
),
|
|
30
|
+
)
|
|
31
|
+
return inner
|
|
32
|
+
}
|
|
33
|
+
const basePath = normalizeBasePath(serverConfig.panel.path ?? defaultBasePath)
|
|
34
|
+
return new PanelMount(basePath, assets, new PanelApiControllerFactory(new ConfiguredPanelAccessCheck()))
|
|
35
|
+
})
|
|
36
|
+
.setupService(
|
|
37
|
+
'application',
|
|
38
|
+
(it, { panelApiMount, tenantApiMiddlewareFactory, contentApiMiddlewareFactory, systemApiMiddlewareFactory }) => {
|
|
39
|
+
if (!(panelApiMount instanceof PanelMount)) {
|
|
40
|
+
return
|
|
41
|
+
}
|
|
42
|
+
const { basePath, api } = panelApiMount
|
|
43
|
+
|
|
44
|
+
// The panel's own API mount, mirroring the public paths so the client's existing URL
|
|
45
|
+
// building (`${apiBaseUrl}${path}`) needs no special cases. Only tenant takes anonymous
|
|
46
|
+
// callers — it is the one the sign-in screen talks to before there is a session.
|
|
47
|
+
// Content and system have no pre-sign-in consumer.
|
|
48
|
+
it.addRoute('panel-api', `${basePath}/api/tenant`, api.create(tenantApiMiddlewareFactory.create(), { allowAnonymous: true }))
|
|
49
|
+
it.addRoute(
|
|
50
|
+
'panel-api',
|
|
51
|
+
`${basePath}/api/content/:projectSlug/:stageSlug`,
|
|
52
|
+
api.create(contentApiMiddlewareFactory.create(), { allowAnonymous: false }),
|
|
53
|
+
)
|
|
54
|
+
it.addRoute('panel-api', `${basePath}/api/system/:projectSlug`, api.create(systemApiMiddlewareFactory.create(), { allowAnonymous: false }))
|
|
55
|
+
|
|
56
|
+
const controller = new PanelController({
|
|
57
|
+
basePath,
|
|
58
|
+
apiBaseUrl: `${basePath}/api`,
|
|
59
|
+
assets: panelApiMount.assets,
|
|
60
|
+
pluginApis: () => panelApiMount.pluginApis,
|
|
61
|
+
})
|
|
62
|
+
// Optional trailing group so both `/panel` and `/panel/anything` are served. An API route
|
|
63
|
+
// is a regular route and the shell an internal one, so `/panel/api/...` is matched first
|
|
64
|
+
// however late a plugin registers it.
|
|
65
|
+
it.addInternalRoute('panel', `${basePath}{/*path}`, controller.create())
|
|
66
|
+
},
|
|
67
|
+
)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const normalizeBasePath = (path: string): string => {
|
|
72
|
+
const trimmed = path.trim().replace(/\/+$/, '')
|
|
73
|
+
if (!trimmed.startsWith('/') || trimmed.length < 2) {
|
|
74
|
+
throw new Error(`Invalid CONTEMBER_PANEL_PATH ${JSON.stringify(path)}: expecting an absolute path like "/panel".`)
|
|
75
|
+
}
|
|
76
|
+
return trimmed
|
|
77
|
+
}
|
package/src/TtlCache.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A minimal time-boxed memo. Entries are keyed by api key, so the map would otherwise grow with
|
|
3
|
+
* every session the process ever sees — expired entries are swept once the map gets large rather
|
|
4
|
+
* than on a timer.
|
|
5
|
+
*/
|
|
6
|
+
export class TtlCache<T> {
|
|
7
|
+
private readonly entries = new Map<string, { value: Promise<T>; expiresAt: number }>()
|
|
8
|
+
|
|
9
|
+
constructor(
|
|
10
|
+
private readonly ttlMs: number,
|
|
11
|
+
private readonly sweepThreshold: number = 1000,
|
|
12
|
+
private readonly now: () => number = () => Date.now(),
|
|
13
|
+
) {}
|
|
14
|
+
|
|
15
|
+
public async resolve(key: string, compute: () => Promise<T>): Promise<T> {
|
|
16
|
+
const cached = this.entries.get(key)
|
|
17
|
+
if (cached && cached.expiresAt > this.now()) {
|
|
18
|
+
return await cached.value
|
|
19
|
+
}
|
|
20
|
+
// The promise is stored before it settles, so a page's worth of parallel requests shares one
|
|
21
|
+
// lookup — caching the resolved value instead would let every one of them miss and recompute.
|
|
22
|
+
const pending = compute()
|
|
23
|
+
this.entries.set(key, { value: pending, expiresAt: this.now() + this.ttlMs })
|
|
24
|
+
try {
|
|
25
|
+
const value = await pending
|
|
26
|
+
// Charge the TTL from when the answer is actually known, not from before the lookup.
|
|
27
|
+
this.entries.set(key, { value: pending, expiresAt: this.now() + this.ttlMs })
|
|
28
|
+
this.sweep(this.now())
|
|
29
|
+
return value
|
|
30
|
+
} catch (error) {
|
|
31
|
+
// Never memoise a failure — the next caller should try again.
|
|
32
|
+
if (this.entries.get(key)?.value === pending) {
|
|
33
|
+
this.entries.delete(key)
|
|
34
|
+
}
|
|
35
|
+
throw error
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
public get size(): number {
|
|
40
|
+
return this.entries.size
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
private sweep(now: number): void {
|
|
44
|
+
if (this.entries.size < this.sweepThreshold) {
|
|
45
|
+
return
|
|
46
|
+
}
|
|
47
|
+
for (const [key, entry] of this.entries) {
|
|
48
|
+
if (entry.expiresAt <= now) {
|
|
49
|
+
this.entries.delete(key)
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|