@taicode/common-server 4.0.0-beta.2 → 4.0.0-beta.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/output/app/index.d.ts +13 -15
- package/output/app/index.d.ts.map +1 -1
- package/output/app/index.js +256 -18
- package/output/auth/index.d.ts +72 -0
- package/output/auth/index.d.ts.map +1 -0
- package/output/auth/index.js +176 -0
- package/output/core/assemble.d.ts +64 -0
- package/output/core/assemble.d.ts.map +1 -0
- package/output/core/assemble.js +88 -0
- package/output/core/boot/context.d.ts +89 -0
- package/output/core/boot/context.d.ts.map +1 -0
- package/output/core/boot/context.js +106 -0
- package/output/core/boot/lifecycle.d.ts +94 -0
- package/output/core/boot/lifecycle.d.ts.map +1 -0
- package/output/{app → core/boot}/lifecycle.js +45 -14
- package/output/core/boot/shutdown.d.ts +30 -0
- package/output/core/boot/shutdown.d.ts.map +1 -0
- package/output/core/boot/shutdown.js +45 -0
- package/output/core/boot/signal.d.ts +13 -0
- package/output/core/boot/signal.d.ts.map +1 -0
- package/output/{app → core/boot}/signal.js +3 -2
- package/output/core/boot/steps.d.ts +107 -0
- package/output/core/boot/steps.d.ts.map +1 -0
- package/output/core/boot/steps.js +200 -0
- package/output/core/entries.d.ts +123 -0
- package/output/core/entries.d.ts.map +1 -0
- package/output/core/entries.js +193 -0
- package/output/core/entries.test.d.ts +2 -0
- package/output/core/entries.test.d.ts.map +1 -0
- package/output/core/entries.test.js +217 -0
- package/output/core/env.d.ts +62 -0
- package/output/core/env.d.ts.map +1 -0
- package/output/core/env.js +96 -0
- package/output/{app → core}/env.test.d.ts.map +1 -1
- package/output/core/env.test.js +105 -0
- package/output/core/modules/auth-provider/index.d.ts +10 -0
- package/output/core/modules/auth-provider/index.d.ts.map +1 -0
- package/output/core/modules/auth-provider/index.js +9 -0
- package/output/core/modules/auth-provider/types.d.ts +71 -0
- package/output/core/modules/auth-provider/types.d.ts.map +1 -0
- package/output/core/modules/context/index.d.ts +18 -0
- package/output/core/modules/context/index.d.ts.map +1 -0
- package/output/core/modules/context/index.js +23 -0
- package/output/core/modules/context/index.test.d.ts.map +1 -0
- package/output/core/modules/cookie/index.d.ts +21 -0
- package/output/core/modules/cookie/index.d.ts.map +1 -0
- package/output/{app/core/cookie.js → core/modules/cookie/index.js} +1 -6
- package/output/core/modules/identity/index.d.ts +4 -0
- package/output/core/modules/identity/index.d.ts.map +1 -0
- package/output/{app/core/identity.js → core/modules/identity/index.js} +1 -1
- package/output/core/modules/logging/index.d.ts +5 -0
- package/output/core/modules/logging/index.d.ts.map +1 -0
- package/output/{app/core/logging.js → core/modules/logging/index.js} +2 -2
- package/output/core/modules/openapi/index.d.ts +7 -0
- package/output/core/modules/openapi/index.d.ts.map +1 -0
- package/output/{app/core/openapi.js → core/modules/openapi/index.js} +11 -12
- package/output/core/modules/permission-operations/index.d.ts +26 -0
- package/output/core/modules/permission-operations/index.d.ts.map +1 -0
- package/output/core/modules/permission-operations/index.js +36 -0
- package/output/core/modules/permission-operations/index.test.d.ts +2 -0
- package/output/core/modules/permission-operations/index.test.d.ts.map +1 -0
- package/output/core/modules/permission-operations/index.test.js +45 -0
- package/output/{app/core/request-id.d.ts → core/modules/request-id/index.d.ts} +1 -4
- package/output/core/modules/request-id/index.d.ts.map +1 -0
- package/output/{app/core/request-id.js → core/modules/request-id/index.js} +2 -2
- package/output/core/modules/response/index.d.ts +22 -0
- package/output/core/modules/response/index.d.ts.map +1 -0
- package/output/{app/core/response.js → core/modules/response/index.js} +22 -11
- package/output/{schema/index.d.ts → core/modules/schema/builders.d.ts} +8 -1
- package/output/core/modules/schema/builders.d.ts.map +1 -0
- package/output/{schema/index.js → core/modules/schema/builders.js} +7 -4
- package/output/core/modules/schema/index.d.ts +34 -0
- package/output/core/modules/schema/index.d.ts.map +1 -0
- package/output/core/modules/schema/index.js +62 -0
- package/output/core/modules/schema/index.test.d.ts +2 -0
- package/output/core/modules/schema/index.test.d.ts.map +1 -0
- package/output/core/modules/schema/index.test.js +55 -0
- package/output/core/modules/system-routes/index.d.ts +15 -0
- package/output/core/modules/system-routes/index.d.ts.map +1 -0
- package/output/core/modules/system-routes/index.js +171 -0
- package/output/core/test-support/database.d.ts +96 -0
- package/output/core/test-support/database.d.ts.map +1 -0
- package/output/core/test-support/database.js +144 -0
- package/output/core/test-support/database.test.d.ts +2 -0
- package/output/core/test-support/database.test.d.ts.map +1 -0
- package/output/core/test-support/database.test.js +110 -0
- package/output/core/test-support/environment.d.ts +33 -0
- package/output/core/test-support/environment.d.ts.map +1 -0
- package/output/core/test-support/environment.js +42 -0
- package/output/core/test-support/test-server.d.ts +94 -0
- package/output/core/test-support/test-server.d.ts.map +1 -0
- package/output/core/test-support/test-server.js +60 -0
- package/output/core/test-support/test-server.test.d.ts +2 -0
- package/output/core/test-support/test-server.test.d.ts.map +1 -0
- package/output/core/test-support/test-server.test.js +162 -0
- package/output/{app → core}/type-augment.d.ts +2 -2
- package/output/core/type-augment.d.ts.map +1 -0
- package/output/core/types.d.ts +338 -0
- package/output/core/types.d.ts.map +1 -0
- package/output/cors/index.d.ts +3 -0
- package/output/cors/index.d.ts.map +1 -0
- package/output/cors/index.js +27 -0
- package/output/index.d.ts +8 -4
- package/output/index.d.ts.map +1 -1
- package/output/index.js +24 -5
- package/output/rate-limit/index.d.ts +23 -0
- package/output/rate-limit/index.d.ts.map +1 -0
- package/output/rate-limit/index.js +42 -0
- package/output/{rate-limiter/rate-limiter.d.ts → rate-limit/limiter.d.ts} +1 -1
- package/output/rate-limit/limiter.d.ts.map +1 -0
- package/output/rate-limit/memory-store.d.ts.map +1 -0
- package/output/rate-limit/redis-store.d.ts.map +1 -0
- package/output/rate-limit/redis-store.test.d.ts.map +1 -0
- package/output/{rate-limiter → rate-limit}/redis-store.test.js +2 -2
- package/output/{rate-limiter → rate-limit}/types.d.ts +0 -1
- package/output/rate-limit/types.d.ts.map +1 -0
- package/output/rate-limit/types.js +1 -0
- package/output/{redis-cache/redis-cache.d.ts → redis/cache.d.ts} +1 -1
- package/output/redis/cache.d.ts.map +1 -0
- package/output/redis/cache.test.d.ts +2 -0
- package/output/redis/cache.test.d.ts.map +1 -0
- package/output/{redis-cache/redis-cache.test.js → redis/cache.test.js} +1 -1
- package/output/{app/redis.d.ts → redis/index.d.ts} +12 -7
- package/output/redis/index.d.ts.map +1 -0
- package/output/{app/redis.js → redis/index.js} +15 -5
- package/output/redis/index.test.d.ts +2 -0
- package/output/{context → redis}/index.test.d.ts.map +1 -1
- package/output/redis/index.test.js +55 -0
- package/output/redis-queue/index.js +1 -1
- package/output/redis-queue/test-helpers.d.ts +1 -1
- package/output/redis-queue/test-helpers.js +1 -1
- package/output/redis-queue/types.d.ts +3 -12
- package/output/redis-queue/types.d.ts.map +1 -1
- package/package.json +16 -15
- package/LICENSE +0 -21
- package/output/app/auth.test.d.ts +0 -2
- package/output/app/auth.test.d.ts.map +0 -1
- package/output/app/auth.test.js +0 -148
- package/output/app/boot.d.ts +0 -39
- package/output/app/boot.d.ts.map +0 -1
- package/output/app/boot.js +0 -140
- package/output/app/config.test.d.ts +0 -2
- package/output/app/config.test.d.ts.map +0 -1
- package/output/app/config.test.js +0 -132
- package/output/app/context.d.ts +0 -70
- package/output/app/context.d.ts.map +0 -1
- package/output/app/context.js +0 -73
- package/output/app/core/cookie.d.ts +0 -25
- package/output/app/core/cookie.d.ts.map +0 -1
- package/output/app/core/identity.d.ts +0 -12
- package/output/app/core/identity.d.ts.map +0 -1
- package/output/app/core/index.d.ts +0 -44
- package/output/app/core/index.d.ts.map +0 -1
- package/output/app/core/index.js +0 -57
- package/output/app/core/logging.d.ts +0 -13
- package/output/app/core/logging.d.ts.map +0 -1
- package/output/app/core/openapi.d.ts +0 -17
- package/output/app/core/openapi.d.ts.map +0 -1
- package/output/app/core/request-id.d.ts.map +0 -1
- package/output/app/core/response.d.ts +0 -41
- package/output/app/core/response.d.ts.map +0 -1
- package/output/app/define-server.negative-cases.d.ts +0 -40
- package/output/app/define-server.negative-cases.d.ts.map +0 -1
- package/output/app/define-server.negative-cases.js +0 -268
- package/output/app/define-server.test.d.ts +0 -2
- package/output/app/define-server.test.d.ts.map +0 -1
- package/output/app/define-server.test.js +0 -97
- package/output/app/entries.d.ts +0 -29
- package/output/app/entries.d.ts.map +0 -1
- package/output/app/entries.js +0 -64
- package/output/app/env.d.ts +0 -59
- package/output/app/env.d.ts.map +0 -1
- package/output/app/env.js +0 -66
- package/output/app/env.test.js +0 -124
- package/output/app/error-contract.test.d.ts +0 -2
- package/output/app/error-contract.test.d.ts.map +0 -1
- package/output/app/error-contract.test.js +0 -227
- package/output/app/errors.d.ts +0 -20
- package/output/app/errors.d.ts.map +0 -1
- package/output/app/errors.js +0 -51
- package/output/app/generate-openapi.test.d.ts +0 -2
- package/output/app/generate-openapi.test.d.ts.map +0 -1
- package/output/app/generate-openapi.test.js +0 -123
- package/output/app/lifecycle-logging.test.d.ts +0 -2
- package/output/app/lifecycle-logging.test.d.ts.map +0 -1
- package/output/app/lifecycle-logging.test.js +0 -155
- package/output/app/lifecycle.d.ts +0 -70
- package/output/app/lifecycle.d.ts.map +0 -1
- package/output/app/lifecycle.test.d.ts +0 -2
- package/output/app/lifecycle.test.d.ts.map +0 -1
- package/output/app/lifecycle.test.js +0 -152
- package/output/app/middleware/auth.d.ts +0 -71
- package/output/app/middleware/auth.d.ts.map +0 -1
- package/output/app/middleware/auth.js +0 -190
- package/output/app/middleware/context.d.ts +0 -13
- package/output/app/middleware/context.d.ts.map +0 -1
- package/output/app/middleware/context.js +0 -15
- package/output/app/middleware/cors.d.ts +0 -14
- package/output/app/middleware/cors.d.ts.map +0 -1
- package/output/app/middleware/cors.js +0 -30
- package/output/app/middleware/index.d.ts +0 -17
- package/output/app/middleware/index.d.ts.map +0 -1
- package/output/app/middleware/index.js +0 -16
- package/output/app/middleware/rate-limit.d.ts +0 -24
- package/output/app/middleware/rate-limit.d.ts.map +0 -1
- package/output/app/middleware/rate-limit.js +0 -46
- package/output/app/middleware-order.test.d.ts +0 -2
- package/output/app/middleware-order.test.d.ts.map +0 -1
- package/output/app/middleware-order.test.js +0 -148
- package/output/app/permission-operations.d.ts +0 -48
- package/output/app/permission-operations.d.ts.map +0 -1
- package/output/app/permission-operations.js +0 -77
- package/output/app/permission-operations.test.d.ts +0 -2
- package/output/app/permission-operations.test.d.ts.map +0 -1
- package/output/app/permission-operations.test.js +0 -72
- package/output/app/permission-registration.test.d.ts +0 -2
- package/output/app/permission-registration.test.d.ts.map +0 -1
- package/output/app/permission-registration.test.js +0 -138
- package/output/app/redis.d.ts.map +0 -1
- package/output/app/registered-operations.test.d.ts +0 -2
- package/output/app/registered-operations.test.d.ts.map +0 -1
- package/output/app/registered-operations.test.js +0 -57
- package/output/app/request-id.test.d.ts +0 -2
- package/output/app/request-id.test.d.ts.map +0 -1
- package/output/app/request-id.test.js +0 -130
- package/output/app/resources.test.d.ts +0 -2
- package/output/app/resources.test.d.ts.map +0 -1
- package/output/app/resources.test.js +0 -199
- package/output/app/shutdown.d.ts +0 -22
- package/output/app/shutdown.d.ts.map +0 -1
- package/output/app/shutdown.js +0 -30
- package/output/app/shutdown.test.d.ts +0 -2
- package/output/app/shutdown.test.d.ts.map +0 -1
- package/output/app/shutdown.test.js +0 -103
- package/output/app/signal.d.ts +0 -12
- package/output/app/signal.d.ts.map +0 -1
- package/output/app/smoke.test.d.ts +0 -2
- package/output/app/smoke.test.d.ts.map +0 -1
- package/output/app/smoke.test.js +0 -210
- package/output/app/test-support.d.ts +0 -21
- package/output/app/test-support.d.ts.map +0 -1
- package/output/app/test-support.js +0 -24
- package/output/app/type-augment.d.ts.map +0 -1
- package/output/app/types.d.ts +0 -228
- package/output/app/types.d.ts.map +0 -1
- package/output/context/index.d.ts +0 -6
- package/output/context/index.d.ts.map +0 -1
- package/output/context/index.js +0 -14
- package/output/rate-limiter/index.d.ts +0 -5
- package/output/rate-limiter/index.d.ts.map +0 -1
- package/output/rate-limiter/index.js +0 -4
- package/output/rate-limiter/memory-store.d.ts.map +0 -1
- package/output/rate-limiter/rate-limiter.d.ts.map +0 -1
- package/output/rate-limiter/redis-store.d.ts.map +0 -1
- package/output/rate-limiter/redis-store.test.d.ts.map +0 -1
- package/output/rate-limiter/types.d.ts.map +0 -1
- package/output/redis-cache/index.d.ts +0 -4
- package/output/redis-cache/index.d.ts.map +0 -1
- package/output/redis-cache/index.js +0 -1
- package/output/redis-cache/redis-cache.d.ts.map +0 -1
- package/output/redis-cache/redis-cache.test.d.ts +0 -2
- package/output/redis-cache/redis-cache.test.d.ts.map +0 -1
- package/output/schema/index.d.ts.map +0 -1
- /package/output/{app → core}/env.test.d.ts +0 -0
- /package/output/{rate-limiter → core/modules/auth-provider}/types.js +0 -0
- /package/output/{context → core/modules/context}/index.test.d.ts +0 -0
- /package/output/{context → core/modules/context}/index.test.js +0 -0
- /package/output/{app → core}/type-augment.js +0 -0
- /package/output/{app → core}/types.js +0 -0
- /package/output/{rate-limiter/rate-limiter.js → rate-limit/limiter.js} +0 -0
- /package/output/{rate-limiter → rate-limit}/memory-store.d.ts +0 -0
- /package/output/{rate-limiter → rate-limit}/memory-store.js +0 -0
- /package/output/{rate-limiter → rate-limit}/redis-store.d.ts +0 -0
- /package/output/{rate-limiter → rate-limit}/redis-store.js +0 -0
- /package/output/{rate-limiter → rate-limit}/redis-store.test.d.ts +0 -0
- /package/output/{redis-cache/redis-cache.js → redis/cache.js} +0 -0
|
@@ -1,155 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
-
import { defineServer, startServer } from './entries.js';
|
|
3
|
-
import { buildDisposeOrder, initServiceUnits, LIFECYCLE_PHASE_DISPOSE, LIFECYCLE_PHASE_INIT, MIDDLEWARES_LOG_STAGE, middlewareUnitName, SERVICES_STAGE, serviceUnitName, } from './lifecycle.js';
|
|
4
|
-
import { createRecordingLogger } from './test-support.js';
|
|
5
|
-
/**
|
|
6
|
-
* 逐单元日志。
|
|
7
|
-
*
|
|
8
|
-
* - **注册期**:每个中间件注册后打一条 `debug`,带 `{ service, unit, stage: 'middlewares' }`;
|
|
9
|
-
* - **init / dispose**:逐单元 `debug`(开始 / 完成),失败 `error`;带 `{ service, unit, stage, phase }`;
|
|
10
|
-
* - 中间件名字:`unit.name ?? '<service>:middleware[<index>]'`;services 用对象键。
|
|
11
|
-
*
|
|
12
|
-
* 分两层验证:
|
|
13
|
-
* 1. **单元层**:直接调 `initServiceUnits` / `buildDisposeOrder`,注入记录型 logger;
|
|
14
|
-
* 2. **真路径**:`startServer(server, { listen: false })` 走完整装配;把框架 logger 的写入流接到
|
|
15
|
-
* 捕获数组(mock `./core/logging.js` 的 `createLoggerOptions`),再按字段断言。
|
|
16
|
-
*/
|
|
17
|
-
// ── 单元层:记录型 logger ────────────────────────────────────────
|
|
18
|
-
/** 按相位 / 阶段 / 消息片段挑出 `unit` 列表(保序) */
|
|
19
|
-
function unitsOf(log, phase, stage, messagePart) {
|
|
20
|
-
return log.entries
|
|
21
|
-
.filter((entry) => entry.level === 'debug' && entry.msg?.includes(messagePart) === true)
|
|
22
|
-
.map((entry) => entry.obj)
|
|
23
|
-
.filter((fields) => fields.phase === phase && fields.stage === stage)
|
|
24
|
-
.map((fields) => fields.unit);
|
|
25
|
-
}
|
|
26
|
-
function expectServiceField(log, service) {
|
|
27
|
-
const fields = log.entries
|
|
28
|
-
.filter((entry) => entry.level === 'debug')
|
|
29
|
-
.map((entry) => entry.obj);
|
|
30
|
-
expect(fields.length).toBeGreaterThan(0);
|
|
31
|
-
for (const field of fields) {
|
|
32
|
-
expect(field.service).toBe(service);
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
describe('逐单元日志:init / dispose', () => {
|
|
36
|
-
it('init 逐单元 debug:单元名 = 对象键', async () => {
|
|
37
|
-
const log = createRecordingLogger();
|
|
38
|
-
const services = {
|
|
39
|
-
alpha: { init: () => undefined },
|
|
40
|
-
beta: { init: () => undefined },
|
|
41
|
-
};
|
|
42
|
-
await initServiceUnits({ service: 'svc', log, services });
|
|
43
|
-
expect(unitsOf(log, LIFECYCLE_PHASE_INIT, SERVICES_STAGE, 'start')).toEqual(['alpha', 'beta']);
|
|
44
|
-
expect(unitsOf(log, LIFECYCLE_PHASE_INIT, SERVICES_STAGE, 'done')).toEqual(['alpha', 'beta']);
|
|
45
|
-
expectServiceField(log, 'svc');
|
|
46
|
-
expect(serviceUnitName('alpha')).toBe('alpha');
|
|
47
|
-
});
|
|
48
|
-
it('dispose 逐单元 debug:声明序逆序', async () => {
|
|
49
|
-
const log = createRecordingLogger();
|
|
50
|
-
const services = {
|
|
51
|
-
alpha: { dispose: () => undefined },
|
|
52
|
-
beta: { dispose: () => undefined },
|
|
53
|
-
};
|
|
54
|
-
for (const step of buildDisposeOrder({ service: 'svc', log, services })) {
|
|
55
|
-
await step();
|
|
56
|
-
}
|
|
57
|
-
expect(unitsOf(log, LIFECYCLE_PHASE_DISPOSE, SERVICES_STAGE, 'start')).toEqual(['beta', 'alpha']);
|
|
58
|
-
expectServiceField(log, 'svc');
|
|
59
|
-
});
|
|
60
|
-
it('单元 init 抛错 → 逐单元 error(带 unit / stage / phase)后重新抛出', async () => {
|
|
61
|
-
const log = createRecordingLogger();
|
|
62
|
-
const services = {
|
|
63
|
-
boom: {
|
|
64
|
-
init: () => {
|
|
65
|
-
throw new Error('init boom');
|
|
66
|
-
},
|
|
67
|
-
},
|
|
68
|
-
};
|
|
69
|
-
await expect(initServiceUnits({ service: 'svc', log, services })).rejects.toThrow('init boom');
|
|
70
|
-
const failure = log.entries.find((entry) => entry.level === 'error');
|
|
71
|
-
expect(failure).toBeDefined();
|
|
72
|
-
const fields = failure?.obj;
|
|
73
|
-
expect(fields.unit).toBe('boom');
|
|
74
|
-
expect(fields.stage).toBe(SERVICES_STAGE);
|
|
75
|
-
expect(fields.phase).toBe(LIFECYCLE_PHASE_INIT);
|
|
76
|
-
expect(fields.error.message).toBe('init boom');
|
|
77
|
-
});
|
|
78
|
-
it('不传 logger → 生命周期函数照常工作(纯函数式调用不发日志)', async () => {
|
|
79
|
-
const calls = [];
|
|
80
|
-
const services = {
|
|
81
|
-
alpha: {
|
|
82
|
-
init: () => {
|
|
83
|
-
calls.push('init');
|
|
84
|
-
},
|
|
85
|
-
},
|
|
86
|
-
};
|
|
87
|
-
await initServiceUnits({ services });
|
|
88
|
-
expect(calls).toEqual(['init']);
|
|
89
|
-
});
|
|
90
|
-
it('中间件日志名字退路:`<service>:middleware[index]`', () => {
|
|
91
|
-
expect(middlewareUnitName('svc', {}, 3)).toBe('svc:middleware[3]');
|
|
92
|
-
expect(middlewareUnitName('svc', { name: 'named' }, 1)).toBe('named');
|
|
93
|
-
});
|
|
94
|
-
});
|
|
95
|
-
// ── 真路径:`startServer` 走完整装配,捕获框架 logger 写入 ────────
|
|
96
|
-
const captured = vi.hoisted(() => ({ lines: [] }));
|
|
97
|
-
vi.mock('./core/logging.js', () => ({
|
|
98
|
-
LOG_REDACT_PATHS: [],
|
|
99
|
-
// 把 pino 的目标流换成捕获数组(level=debug,否则逐单元 debug 不会落盘)
|
|
100
|
-
createLoggerOptions: () => ({
|
|
101
|
-
level: 'debug',
|
|
102
|
-
stream: {
|
|
103
|
-
write: (chunk) => {
|
|
104
|
-
captured.lines.push(chunk);
|
|
105
|
-
},
|
|
106
|
-
},
|
|
107
|
-
}),
|
|
108
|
-
}));
|
|
109
|
-
function capturedRecords() {
|
|
110
|
-
return captured.lines
|
|
111
|
-
.join('')
|
|
112
|
-
.split('\n')
|
|
113
|
-
.filter((line) => line.trim().length > 0)
|
|
114
|
-
.map((line) => JSON.parse(line));
|
|
115
|
-
}
|
|
116
|
-
/** 按字段匹配捕获到的记录(pino 还会加 `time` / `pid` 等,故只比关键字段) */
|
|
117
|
-
function matchRecords(records, match) {
|
|
118
|
-
return records.filter((record) => Object.entries(match).every(([key, value]) => record[key] === value));
|
|
119
|
-
}
|
|
120
|
-
describe('startServer 真路径:注册 / init / dispose 逐单元日志', () => {
|
|
121
|
-
it('中间件注册、services 的 init / dispose 日志都能拿到名字;未命名用退路', async () => {
|
|
122
|
-
captured.lines.length = 0;
|
|
123
|
-
const server = defineServer({
|
|
124
|
-
app: { service: 'logging-svc', title: 'Logging Service', version: '1.0.0' },
|
|
125
|
-
resources: () => ({}),
|
|
126
|
-
config: () => ({}),
|
|
127
|
-
services: () => ({
|
|
128
|
-
alpha: {
|
|
129
|
-
init: () => undefined,
|
|
130
|
-
dispose: () => undefined,
|
|
131
|
-
},
|
|
132
|
-
}),
|
|
133
|
-
middlewares: () => [
|
|
134
|
-
{ name: 'named', register: () => undefined },
|
|
135
|
-
// 未命名 → 退路 `logging-svc:middleware[1]`
|
|
136
|
-
{ register: () => undefined },
|
|
137
|
-
],
|
|
138
|
-
routers: () => undefined,
|
|
139
|
-
});
|
|
140
|
-
const app = await startServer(server, { listen: false });
|
|
141
|
-
await app.close();
|
|
142
|
-
const records = capturedRecords();
|
|
143
|
-
// 注册期:字段 `{ service, unit, stage }`,未命名走退路
|
|
144
|
-
const registered = matchRecords(records, { msg: '[middleware] registered' });
|
|
145
|
-
expect(matchRecords(registered, { unit: 'named', stage: MIDDLEWARES_LOG_STAGE }).length).toBe(1);
|
|
146
|
-
expect(matchRecords(registered, { unit: 'logging-svc:middleware[1]', stage: MIDDLEWARES_LOG_STAGE }).length).toBe(1);
|
|
147
|
-
expect(matchRecords(registered, { service: 'logging-svc' }).length).toBe(2);
|
|
148
|
-
// init / dispose:services 逐单元 debug(带 `phase`)
|
|
149
|
-
expect(matchRecords(records, { unit: 'alpha', stage: SERVICES_STAGE, phase: LIFECYCLE_PHASE_INIT }).length).toBeGreaterThan(0);
|
|
150
|
-
expect(matchRecords(records, { unit: 'alpha', stage: SERVICES_STAGE, phase: LIFECYCLE_PHASE_DISPOSE }).length).toBeGreaterThan(0);
|
|
151
|
-
// 中间件**不参与生命周期**:没有 middlewares 阶段的 init / dispose 日志
|
|
152
|
-
expect(matchRecords(records, { stage: MIDDLEWARES_LOG_STAGE, phase: LIFECYCLE_PHASE_INIT })).toHaveLength(0);
|
|
153
|
-
expect(matchRecords(records, { stage: MIDDLEWARES_LOG_STAGE, phase: LIFECYCLE_PHASE_DISPOSE })).toHaveLength(0);
|
|
154
|
-
});
|
|
155
|
-
});
|
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
import type { LoggerLike } from './types.js';
|
|
2
|
-
/**
|
|
3
|
-
* 生命周期序(N1 §4 / N2 §2.5)。
|
|
4
|
-
*
|
|
5
|
-
* **只有 `services` 参与生命周期**:
|
|
6
|
-
* - 单元之间**不得相互依赖**(`services` 的 ctx 没有 `services` 字段,编译期禁止);
|
|
7
|
-
* - 顺序语义只有一条:按**对象声明序** `init`、**逆序** `dispose`;
|
|
8
|
-
* - `middlewares` 按数组序注册,**不参与生命周期**(要常驻资源就放 `services`);
|
|
9
|
-
* - `resources` 只是惰性包装(构造不建连),框架不替它们做生命周期。
|
|
10
|
-
*/
|
|
11
|
-
export declare const SERVICES_STAGE = "services";
|
|
12
|
-
/** `middlewares` 的**注册期日志**阶段标签(中间件不参与生命周期,只用于注册日志) */
|
|
13
|
-
export declare const MIDDLEWARES_LOG_STAGE = "middlewares";
|
|
14
|
-
/** 生命周期相位(逐单元日志字段 `phase`) */
|
|
15
|
-
export declare const LIFECYCLE_PHASE_INIT = "init";
|
|
16
|
-
export declare const LIFECYCLE_PHASE_DISPOSE = "dispose";
|
|
17
|
-
export type LifecyclePhase = typeof LIFECYCLE_PHASE_INIT | typeof LIFECYCLE_PHASE_DISPOSE;
|
|
18
|
-
/**
|
|
19
|
-
* 逐单元生命周期日志上下文。
|
|
20
|
-
*
|
|
21
|
-
* `log` / `service` 缺省时**不打日志**(纯单测可直接调用生命周期函数,不注入假 logger)。
|
|
22
|
-
* 字段名固定为全拼:`service` + `unit` + `stage` + `phase`。
|
|
23
|
-
*/
|
|
24
|
-
export interface LifecycleLogContext {
|
|
25
|
-
/** 日志标签(`defineServer({ app: { service } })`);缺省时退路名字失去前缀 */
|
|
26
|
-
service?: string;
|
|
27
|
-
/** 记录型 logger(`ctx.log`);缺省 = 不打日志 */
|
|
28
|
-
log?: LoggerLike;
|
|
29
|
-
}
|
|
30
|
-
/** 逐单元日志字段(全拼):`unit` = 有效名字,`stage` = `services` */
|
|
31
|
-
export interface LifecycleUnitLogFields {
|
|
32
|
-
service: string;
|
|
33
|
-
unit: string;
|
|
34
|
-
stage: string;
|
|
35
|
-
phase: LifecyclePhase;
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* `services` 有效名字:**对象键即单元名**(N1 §4:没有 `name` 字段)。
|
|
39
|
-
*/
|
|
40
|
-
export declare function serviceUnitName(key: string): string;
|
|
41
|
-
/**
|
|
42
|
-
* `middlewares` 日志名字:`unit.name ?? '<service>:middleware[<index>]'`(仅用于注册期日志)。
|
|
43
|
-
*/
|
|
44
|
-
export declare function middlewareUnitName(service: string, unit: unknown, index: number): string;
|
|
45
|
-
/** `initServiceUnits` 入参(参数签名内联对象类型已按 lint 规则外提) */
|
|
46
|
-
export interface InitServiceUnitsParams extends LifecycleLogContext {
|
|
47
|
-
/** `services(ctx)` 返回的对象(**对象键即单元名**) */
|
|
48
|
-
services?: Record<string, unknown>;
|
|
49
|
-
}
|
|
50
|
-
/**
|
|
51
|
-
* 启动序:`services` 按**对象声明序**逐项 `await init?.()`;逐项打日志。
|
|
52
|
-
*/
|
|
53
|
-
export declare function initServiceUnits(params: InitServiceUnitsParams): Promise<void>;
|
|
54
|
-
/** `buildDisposeOrder` / `disposeServiceUnits` 入参(参数签名内联对象类型已按 lint 规则外提) */
|
|
55
|
-
export interface DisposeServiceUnitsParams extends LifecycleLogContext {
|
|
56
|
-
/** `services(ctx)` 返回的对象(**对象键即单元名**) */
|
|
57
|
-
services?: Record<string, unknown>;
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* 关闭序:`services` 按声明序**逆序**逐项 `dispose?.()`。
|
|
61
|
-
*/
|
|
62
|
-
export declare function buildDisposeOrder(params: DisposeServiceUnitsParams): Array<() => void | Promise<void>>;
|
|
63
|
-
/**
|
|
64
|
-
* 关闭步 `disposeServices`:`services` 声明序逆序释放。
|
|
65
|
-
*
|
|
66
|
-
* 单元级失败已在 `runLifecycleUnit` 内 `log.error`(带 service / unit / stage / phase);
|
|
67
|
-
* 此处仅保证单步不阻断后续。
|
|
68
|
-
*/
|
|
69
|
-
export declare function disposeServices(params: DisposeServiceUnitsParams): Promise<void>;
|
|
70
|
-
//# sourceMappingURL=lifecycle.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"lifecycle.d.ts","sourceRoot":"","sources":["../../source/app/lifecycle.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AAE5C;;;;;;;;GAQG;AAEH,eAAO,MAAM,cAAc,aAAa,CAAA;AACxC,uDAAuD;AACvD,eAAO,MAAM,qBAAqB,gBAAgB,CAAA;AAElD,8BAA8B;AAC9B,eAAO,MAAM,oBAAoB,SAAS,CAAA;AAC1C,eAAO,MAAM,uBAAuB,YAAY,CAAA;AAChD,MAAM,MAAM,cAAc,GAAG,OAAO,oBAAoB,GAAG,OAAO,uBAAuB,CAAA;AAEzF;;;;;GAKG;AACH,MAAM,WAAW,mBAAmB;IAClC,6DAA6D;IAC7D,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,sCAAsC;IACtC,GAAG,CAAC,EAAE,UAAU,CAAA;CACjB;AAED,qDAAqD;AACrD,MAAM,WAAW,sBAAsB;IACrC,OAAO,EAAE,MAAM,CAAA;IACf,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,EAAE,cAAc,CAAA;CACtB;AAMD;;GAEG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEnD;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAKxF;AAED,oDAAoD;AACpD,MAAM,WAAW,sBAAuB,SAAQ,mBAAmB;IACjE,yCAAyC;IACzC,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CACnC;AAmCD;;GAEG;AACH,wBAAsB,gBAAgB,CAAC,MAAM,EAAE,sBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC,CAIpF;AAED,6EAA6E;AAC7E,MAAM,WAAW,yBAA0B,SAAQ,mBAAmB;IACpE,yCAAyC;IACzC,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CACnC;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,yBAAyB,GAAG,KAAK,CAAC,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAMtG;AAED;;;;;GAKG;AACH,wBAAsB,eAAe,CAAC,MAAM,EAAE,yBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC,CAQtF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"lifecycle.test.d.ts","sourceRoot":"","sources":["../../source/app/lifecycle.test.ts"],"names":[],"mappings":""}
|
|
@@ -1,152 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'vitest';
|
|
2
|
-
import { defineServer, startServer } from './entries.js';
|
|
3
|
-
import { buildDisposeOrder, initServiceUnits, serviceUnitName } from './lifecycle.js';
|
|
4
|
-
/**
|
|
5
|
-
* 生命周期(N1 §4)。
|
|
6
|
-
*
|
|
7
|
-
* - **只有 `services` 参与**:按**对象声明序** `init` / **逆序** `dispose`;
|
|
8
|
-
* - **没有 `dependsOn`**(`services` 的 ctx 没有 `services` 字段,编译期禁止互依);
|
|
9
|
-
* - 单元名 = **对象键**;
|
|
10
|
-
* - `middlewares` 按数组序注册,**不参与生命周期**。
|
|
11
|
-
*/
|
|
12
|
-
describe('init / dispose 顺序:声明序 / 逆序(N1 §4 / §5)', () => {
|
|
13
|
-
it('init:services 按对象声明序', async () => {
|
|
14
|
-
const calls = [];
|
|
15
|
-
const services = {
|
|
16
|
-
ledger: {
|
|
17
|
-
init: () => {
|
|
18
|
-
calls.push('init:ledger');
|
|
19
|
-
},
|
|
20
|
-
},
|
|
21
|
-
repository: {
|
|
22
|
-
init: () => {
|
|
23
|
-
calls.push('init:repository');
|
|
24
|
-
},
|
|
25
|
-
},
|
|
26
|
-
mailer: {
|
|
27
|
-
init: () => {
|
|
28
|
-
calls.push('init:mailer');
|
|
29
|
-
},
|
|
30
|
-
},
|
|
31
|
-
};
|
|
32
|
-
await initServiceUnits({ services });
|
|
33
|
-
expect(calls).toEqual(['init:ledger', 'init:repository', 'init:mailer']);
|
|
34
|
-
});
|
|
35
|
-
it('dispose:services 按声明序逆序', async () => {
|
|
36
|
-
const calls = [];
|
|
37
|
-
const services = {
|
|
38
|
-
ledger: {
|
|
39
|
-
dispose: () => {
|
|
40
|
-
calls.push('dispose:ledger');
|
|
41
|
-
},
|
|
42
|
-
},
|
|
43
|
-
repository: {
|
|
44
|
-
dispose: () => {
|
|
45
|
-
calls.push('dispose:repository');
|
|
46
|
-
},
|
|
47
|
-
},
|
|
48
|
-
};
|
|
49
|
-
for (const step of buildDisposeOrder({ services })) {
|
|
50
|
-
await step();
|
|
51
|
-
}
|
|
52
|
-
expect(calls).toEqual(['dispose:repository', 'dispose:ledger']);
|
|
53
|
-
});
|
|
54
|
-
it('不是 ServiceUnit 的值照样能放(框架只检测 init / dispose 是否为函数)', async () => {
|
|
55
|
-
const calls = [];
|
|
56
|
-
const services = {
|
|
57
|
-
plain: { hello: 'world' },
|
|
58
|
-
lifecycle: {
|
|
59
|
-
init: () => {
|
|
60
|
-
calls.push('init:lifecycle');
|
|
61
|
-
},
|
|
62
|
-
},
|
|
63
|
-
};
|
|
64
|
-
await initServiceUnits({ services });
|
|
65
|
-
expect(calls).toEqual(['init:lifecycle']);
|
|
66
|
-
});
|
|
67
|
-
it('单元名 = 对象键', () => {
|
|
68
|
-
expect(serviceUnitName('ledger')).toBe('ledger');
|
|
69
|
-
expect(serviceUnitName('repository')).toBe('repository');
|
|
70
|
-
});
|
|
71
|
-
});
|
|
72
|
-
describe('startServer 集成:声明序 init / 逆序 dispose', () => {
|
|
73
|
-
it('services 声明序 init;中间件按数组序注册但不参与生命周期;close 时 services 逆序 dispose', async () => {
|
|
74
|
-
const calls = [];
|
|
75
|
-
const server = defineServer({
|
|
76
|
-
app: { service: 'lifecycle-integration', title: 'Lifecycle Integration', version: '1.0.0' },
|
|
77
|
-
resources: () => ({}),
|
|
78
|
-
config: () => ({}),
|
|
79
|
-
services: () => ({
|
|
80
|
-
ledger: {
|
|
81
|
-
init: () => {
|
|
82
|
-
calls.push('init:ledger');
|
|
83
|
-
},
|
|
84
|
-
dispose: () => {
|
|
85
|
-
calls.push('dispose:ledger');
|
|
86
|
-
},
|
|
87
|
-
},
|
|
88
|
-
repository: {
|
|
89
|
-
init: () => {
|
|
90
|
-
calls.push('init:repository');
|
|
91
|
-
},
|
|
92
|
-
dispose: () => {
|
|
93
|
-
calls.push('dispose:repository');
|
|
94
|
-
},
|
|
95
|
-
},
|
|
96
|
-
mailer: {
|
|
97
|
-
init: () => {
|
|
98
|
-
calls.push('init:mailer');
|
|
99
|
-
},
|
|
100
|
-
dispose: () => {
|
|
101
|
-
calls.push('dispose:mailer');
|
|
102
|
-
},
|
|
103
|
-
},
|
|
104
|
-
}),
|
|
105
|
-
middlewares: () => [
|
|
106
|
-
{
|
|
107
|
-
name: 'm1',
|
|
108
|
-
register: () => {
|
|
109
|
-
calls.push('register:m1');
|
|
110
|
-
},
|
|
111
|
-
},
|
|
112
|
-
{
|
|
113
|
-
name: 'm2',
|
|
114
|
-
register: () => {
|
|
115
|
-
calls.push('register:m2');
|
|
116
|
-
},
|
|
117
|
-
},
|
|
118
|
-
],
|
|
119
|
-
routers: () => undefined,
|
|
120
|
-
});
|
|
121
|
-
const app = await startServer(server, { listen: false });
|
|
122
|
-
expect(calls).toEqual(['init:ledger', 'init:repository', 'init:mailer', 'register:m1', 'register:m2']);
|
|
123
|
-
await app.close();
|
|
124
|
-
expect(calls).toEqual([
|
|
125
|
-
'init:ledger',
|
|
126
|
-
'init:repository',
|
|
127
|
-
'init:mailer',
|
|
128
|
-
'register:m1',
|
|
129
|
-
'register:m2',
|
|
130
|
-
'dispose:mailer',
|
|
131
|
-
'dispose:repository',
|
|
132
|
-
'dispose:ledger',
|
|
133
|
-
]);
|
|
134
|
-
});
|
|
135
|
-
it('单元 init 抛错 → startServer 冒泡失败', async () => {
|
|
136
|
-
const server = defineServer({
|
|
137
|
-
app: { service: 'lifecycle-init-error', title: 'Lifecycle Init Error', version: '1.0.0' },
|
|
138
|
-
resources: () => ({}),
|
|
139
|
-
config: () => ({}),
|
|
140
|
-
services: () => ({
|
|
141
|
-
broken: {
|
|
142
|
-
init: () => {
|
|
143
|
-
throw new Error('init boom');
|
|
144
|
-
},
|
|
145
|
-
},
|
|
146
|
-
}),
|
|
147
|
-
middlewares: () => [],
|
|
148
|
-
routers: () => undefined,
|
|
149
|
-
});
|
|
150
|
-
await expect(startServer(server, { listen: false })).rejects.toThrow('init boom');
|
|
151
|
-
});
|
|
152
|
-
});
|
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
import type { MiddlewareContext, MiddlewareUnit } from '../types.js';
|
|
2
|
-
import type { FastifyRequest } from 'fastify';
|
|
3
|
-
/**
|
|
4
|
-
* 标准中间件单元 `auth`(可替换)。
|
|
5
|
-
*
|
|
6
|
-
* 校验下游 token(4/5 服务用)。默认 `skip`:`OPTIONS` → 未匹配路由 → `NoLoginRequired` → `docPath`。
|
|
7
|
-
* 默认 `verify` 为**框架内置 account HTTP 客户端**(`POST /gateway/verify` + 信封解析),可经
|
|
8
|
-
* `verify` 整体替换;account `serviceUrl` 门槛**仅作用于内置 verify**(自定义 `verify` 不受约束)。
|
|
9
|
-
*
|
|
10
|
-
* 另在 `onReady` 阶段默认(`registerPermissions !== false`)向 account **自注册权限操作目录**
|
|
11
|
-
* (`POST /permission/operation/register`)。
|
|
12
|
-
*/
|
|
13
|
-
export interface AuthVerifyMetadata {
|
|
14
|
-
requestId?: string;
|
|
15
|
-
method?: string;
|
|
16
|
-
url?: string;
|
|
17
|
-
ip?: string;
|
|
18
|
-
ips?: string[];
|
|
19
|
-
userAgent?: string;
|
|
20
|
-
referrer?: string;
|
|
21
|
-
}
|
|
22
|
-
export interface AuthVerifyInput {
|
|
23
|
-
token?: string;
|
|
24
|
-
apiKey?: string;
|
|
25
|
-
operation?: string;
|
|
26
|
-
/** 路由参数(`request.params`),如 `:id` 这类路径参数 */
|
|
27
|
-
resource?: Record<string, unknown>;
|
|
28
|
-
accessControls?: string[];
|
|
29
|
-
/** 请求元信息(仅供下游审计 / 日志;不参与鉴权判定) */
|
|
30
|
-
metadata?: AuthVerifyMetadata;
|
|
31
|
-
}
|
|
32
|
-
export interface AuthVerifyResult {
|
|
33
|
-
user?: unknown;
|
|
34
|
-
token?: unknown;
|
|
35
|
-
}
|
|
36
|
-
/** 跳过条件(返回 true 即放行);缺省为框架默认 skip 集合 */
|
|
37
|
-
export type AuthSkip<C = unknown, S = unknown> = (request: FastifyRequest, ctx: MiddlewareContext<C, S>) => boolean | undefined;
|
|
38
|
-
export interface AccountIntegrationConfig {
|
|
39
|
-
enabled?: boolean;
|
|
40
|
-
serviceUrl?: string;
|
|
41
|
-
accessKey?: string;
|
|
42
|
-
secretKey?: string;
|
|
43
|
-
}
|
|
44
|
-
export interface AuthMiddlewareOptions<C = unknown, S = unknown> {
|
|
45
|
-
/**
|
|
46
|
-
* 整体替换校验实现(缺省走框架内置 account HTTP 客户端)。
|
|
47
|
-
*
|
|
48
|
-
* 提供本项时**不做** account `serviceUrl` 门槛:`serviceUrl` 只服务于内置 verify。
|
|
49
|
-
*/
|
|
50
|
-
verify?: (input: AuthVerifyInput & {
|
|
51
|
-
service: string;
|
|
52
|
-
}, ctx: MiddlewareContext<C, S>) => Promise<AuthVerifyResult>;
|
|
53
|
-
/** 读取 token 的 cookie 名(缺省现读配置的 `server.cookieNames`) */
|
|
54
|
-
cookieNames?: string[];
|
|
55
|
-
/**
|
|
56
|
-
* 是否在 `startServer` 的 `onReady` 阶段向 account 自注册权限操作(默认 `true`)。
|
|
57
|
-
*
|
|
58
|
-
* 跳过条件:本项为 `false`;或配置的 `account` 无 `serviceUrl`(自然排除 account 自身);
|
|
59
|
-
* 或出 spec 路径(`generateOpenApi` 不跑 `config` 槽位,配置不可用)。注册失败**不致命**:
|
|
60
|
-
* `log.error` 后继续启动,不中断 `startServer`。
|
|
61
|
-
*/
|
|
62
|
-
registerPermissions?: boolean;
|
|
63
|
-
/** 跳过条件(返回 true 即放行);缺省为框架默认 skip 集合 */
|
|
64
|
-
skip?: AuthSkip<C, S>;
|
|
65
|
-
/** 错误映射(缺省:非 `UserError` / `SystemError` 一律 → `SystemError('EXTERNAL_SERVICE_ERROR')`) */
|
|
66
|
-
mapError?: (error: unknown) => Error;
|
|
67
|
-
}
|
|
68
|
-
/** 框架默认 skip:OPTIONS → 未匹配路由 → NoLoginRequired → docPath */
|
|
69
|
-
export declare function defaultAuthSkip(request: FastifyRequest, ctx: MiddlewareContext<unknown, unknown>): boolean;
|
|
70
|
-
export declare function createAuthMiddleware<C = unknown, S = unknown>(ctx: MiddlewareContext<C, S>, options?: AuthMiddlewareOptions<C, S>): MiddlewareUnit;
|
|
71
|
-
//# sourceMappingURL=auth.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../../source/app/middleware/auth.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAEpE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAE7C;;;;;;;;;GASG;AAEH,MAAM,WAAW,kBAAkB;IACjC,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,EAAE,CAAC,EAAE,MAAM,CAAA;IACX,GAAG,CAAC,EAAE,MAAM,EAAE,CAAA;IACd,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB;AAED,MAAM,WAAW,eAAe;IAC9B,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,4CAA4C;IAC5C,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAClC,cAAc,CAAC,EAAE,MAAM,EAAE,CAAA;IACzB,iCAAiC;IACjC,QAAQ,CAAC,EAAE,kBAAkB,CAAA;CAC9B;AAED,MAAM,WAAW,gBAAgB;IAC/B,IAAI,CAAC,EAAE,OAAO,CAAA;IACd,KAAK,CAAC,EAAE,OAAO,CAAA;CAChB;AAED,wCAAwC;AACxC,MAAM,MAAM,QAAQ,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,OAAO,IAAI,CAC/C,OAAO,EAAE,cAAc,EACvB,GAAG,EAAE,iBAAiB,CAAC,CAAC,EAAE,CAAC,CAAC,KACzB,OAAO,GAAG,SAAS,CAAA;AAExB,MAAM,WAAW,wBAAwB;IACvC,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB;AAED,MAAM,WAAW,qBAAqB,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,OAAO;IAC7D;;;;OAIG;IACH,MAAM,CAAC,EAAE,CACP,KAAK,EAAE,eAAe,GAAG;QAAE,OAAO,EAAE,MAAM,CAAA;KAAE,EAC5C,GAAG,EAAE,iBAAiB,CAAC,CAAC,EAAE,CAAC,CAAC,KACzB,OAAO,CAAC,gBAAgB,CAAC,CAAA;IAC9B,wDAAwD;IACxD,WAAW,CAAC,EAAE,MAAM,EAAE,CAAA;IACtB;;;;;;OAMG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAA;IAC7B,wCAAwC;IACxC,IAAI,CAAC,EAAE,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;IACrB,0FAA0F;IAC1F,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,KAAK,CAAA;CACrC;AAmCD,4DAA4D;AAC5D,wBAAgB,eAAe,CAAC,OAAO,EAAE,cAAc,EAAE,GAAG,EAAE,iBAAiB,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,OAAO,CAgB1G;AAgFD,wBAAgB,oBAAoB,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,OAAO,EAAE,GAAG,EAAE,iBAAiB,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,OAAO,GAAE,qBAAqB,CAAC,CAAC,EAAE,CAAC,CAAM,GAAG,cAAc,CAoGtJ"}
|
|
@@ -1,190 +0,0 @@
|
|
|
1
|
-
import { readConfigKey } from '../context.js';
|
|
2
|
-
import { readServerIdentity } from '../core/identity.js';
|
|
3
|
-
import { DOC_ROUTE_PREFIX } from '../core/openapi.js';
|
|
4
|
-
import { SystemError, UserError } from '../errors.js';
|
|
5
|
-
import { readRegisteredOperations, toPermissionOperations } from '../permission-operations.js';
|
|
6
|
-
function readAccount(config) {
|
|
7
|
-
return readConfigKey(config, 'account');
|
|
8
|
-
}
|
|
9
|
-
function readServer(config) {
|
|
10
|
-
return readConfigKey(config, 'server');
|
|
11
|
-
}
|
|
12
|
-
function readCookieNames(config, fallback) {
|
|
13
|
-
if (fallback && fallback.length > 0) {
|
|
14
|
-
return fallback;
|
|
15
|
-
}
|
|
16
|
-
const configured = readServer(config)?.cookieNames;
|
|
17
|
-
return Array.isArray(configured) && configured.length > 0 ? configured : ['token'];
|
|
18
|
-
}
|
|
19
|
-
function extractAuth(request, cookieNames) {
|
|
20
|
-
const authorization = request.headers.authorization;
|
|
21
|
-
if (typeof authorization === 'string' && authorization.startsWith('Bearer ')) {
|
|
22
|
-
return { token: authorization.slice('Bearer '.length).trim() };
|
|
23
|
-
}
|
|
24
|
-
if (typeof authorization === 'string' && authorization.startsWith('apikey-')) {
|
|
25
|
-
return { apiKey: authorization.slice('apikey-'.length).trim() };
|
|
26
|
-
}
|
|
27
|
-
for (const name of cookieNames) {
|
|
28
|
-
const value = request.cookies?.[name];
|
|
29
|
-
if (typeof value === 'string' && value) {
|
|
30
|
-
return { token: value };
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
return {};
|
|
34
|
-
}
|
|
35
|
-
/** 框架默认 skip:OPTIONS → 未匹配路由 → NoLoginRequired → docPath */
|
|
36
|
-
export function defaultAuthSkip(request, ctx) {
|
|
37
|
-
void ctx;
|
|
38
|
-
if (request.method === 'OPTIONS') {
|
|
39
|
-
return true;
|
|
40
|
-
}
|
|
41
|
-
const url = request.routeOptions?.url;
|
|
42
|
-
if (!url) {
|
|
43
|
-
return true;
|
|
44
|
-
}
|
|
45
|
-
if (url.startsWith(DOC_ROUTE_PREFIX)) {
|
|
46
|
-
return true;
|
|
47
|
-
}
|
|
48
|
-
if (request.routeOptions?.config?.accessControls?.includes('NoLoginRequired')) {
|
|
49
|
-
return true;
|
|
50
|
-
}
|
|
51
|
-
return false;
|
|
52
|
-
}
|
|
53
|
-
async function defaultVerify(input, account) {
|
|
54
|
-
const serviceUrl = account?.serviceUrl;
|
|
55
|
-
if (!serviceUrl) {
|
|
56
|
-
// 内置 verify 依赖 account `serviceUrl`;缺失时抛明确错误
|
|
57
|
-
// (不再 `new URL(path, undefined)` 抛 TypeError)
|
|
58
|
-
throw new SystemError('CONFIG_UNAVAILABLE', undefined, 'account 未配置 serviceUrl,无法使用内置 verify(可用 verify 选项整体替换校验实现)');
|
|
59
|
-
}
|
|
60
|
-
const target = new URL('/gateway/verify', serviceUrl);
|
|
61
|
-
const response = await fetch(target, {
|
|
62
|
-
method: 'POST',
|
|
63
|
-
headers: { 'content-type': 'application/json' },
|
|
64
|
-
body: JSON.stringify({
|
|
65
|
-
token: input.token,
|
|
66
|
-
apiKey: input.apiKey,
|
|
67
|
-
service: input.service,
|
|
68
|
-
operation: input.operation,
|
|
69
|
-
resource: input.resource,
|
|
70
|
-
accessControls: input.accessControls,
|
|
71
|
-
metadata: input.metadata,
|
|
72
|
-
}),
|
|
73
|
-
});
|
|
74
|
-
const payload = (await response.json());
|
|
75
|
-
if (!response.ok || payload.status !== 'SUCCESS') {
|
|
76
|
-
throw new UserError(payload.status ?? 'AUTH_FAILED', undefined, payload.message ?? '');
|
|
77
|
-
}
|
|
78
|
-
return { user: payload.data?.user, token: payload.data?.token ?? input.token };
|
|
79
|
-
}
|
|
80
|
-
/** account 权限操作注册端点(固定路径) */
|
|
81
|
-
const PERMISSION_OPERATION_REGISTER_PATH = '/permission/operation/register';
|
|
82
|
-
/**
|
|
83
|
-
* 框架内置 account HTTP 客户端:`POST /permission/operation/register`。
|
|
84
|
-
*
|
|
85
|
-
* 成功判定与 `/gateway/verify` 同口径:HTTP ok **且** 信封 `status === 'SUCCESS'`。
|
|
86
|
-
*/
|
|
87
|
-
async function requestPermissionRegistration(account, body) {
|
|
88
|
-
const target = new URL(PERMISSION_OPERATION_REGISTER_PATH, account.serviceUrl);
|
|
89
|
-
const response = await fetch(target, {
|
|
90
|
-
method: 'POST',
|
|
91
|
-
headers: { 'content-type': 'application/json' },
|
|
92
|
-
body: JSON.stringify(body),
|
|
93
|
-
});
|
|
94
|
-
const payload = (await response.json().catch(() => undefined));
|
|
95
|
-
if (!response.ok || payload?.status !== 'SUCCESS') {
|
|
96
|
-
throw new SystemError('EXTERNAL_SERVICE_ERROR', { cause: response }, payload?.message ?? `权限操作注册失败(HTTP ${response.status})`);
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
export function createAuthMiddleware(ctx, options = {}) {
|
|
100
|
-
const skip = options.skip ?? defaultAuthSkip;
|
|
101
|
-
const mapError = options.mapError ??
|
|
102
|
-
((error) => UserError.is(error) || SystemError.is(error)
|
|
103
|
-
? error
|
|
104
|
-
: new SystemError('EXTERNAL_SERVICE_ERROR', { cause: error }));
|
|
105
|
-
return {
|
|
106
|
-
name: 'auth',
|
|
107
|
-
register: (app) => {
|
|
108
|
-
const identity = readServerIdentity(app);
|
|
109
|
-
const service = identity?.service ?? '';
|
|
110
|
-
app.addHook('preValidation', async (request) => {
|
|
111
|
-
if (skip(request, ctx)) {
|
|
112
|
-
return;
|
|
113
|
-
}
|
|
114
|
-
const account = readAccount(ctx.config);
|
|
115
|
-
// account `serviceUrl` 门槛仅作用于内置 verify:自定义 verify 不受约束,仍照常校验
|
|
116
|
-
if (!options.verify && !account?.serviceUrl) {
|
|
117
|
-
return;
|
|
118
|
-
}
|
|
119
|
-
const { token, apiKey } = extractAuth(request, readCookieNames(ctx.config, options.cookieNames));
|
|
120
|
-
if (!token && !apiKey) {
|
|
121
|
-
throw new UserError('INVALID_TOKEN', undefined, '缺少访问凭证');
|
|
122
|
-
}
|
|
123
|
-
const verifyInput = {
|
|
124
|
-
token,
|
|
125
|
-
apiKey,
|
|
126
|
-
service,
|
|
127
|
-
// 权限目录同源、与 url 解耦:优先路由 `schema.operationId`,未声明时回落 url
|
|
128
|
-
operation: request.routeOptions?.schema?.operationId ?? request.routeOptions?.url,
|
|
129
|
-
resource: request.params,
|
|
130
|
-
accessControls: request.routeOptions?.config?.accessControls,
|
|
131
|
-
metadata: {
|
|
132
|
-
requestId: request.id,
|
|
133
|
-
method: request.method,
|
|
134
|
-
url: request.url,
|
|
135
|
-
ip: request.ip,
|
|
136
|
-
ips: request.ips,
|
|
137
|
-
userAgent: request.headers['user-agent'],
|
|
138
|
-
referrer: request.headers.referer,
|
|
139
|
-
},
|
|
140
|
-
};
|
|
141
|
-
try {
|
|
142
|
-
const result = options.verify
|
|
143
|
-
? await options.verify(verifyInput, ctx)
|
|
144
|
-
: await defaultVerify(verifyInput, account);
|
|
145
|
-
request.user = result.user;
|
|
146
|
-
request.token = result.token;
|
|
147
|
-
}
|
|
148
|
-
catch (error) {
|
|
149
|
-
throw mapError(error);
|
|
150
|
-
}
|
|
151
|
-
});
|
|
152
|
-
if (options.registerPermissions === false) {
|
|
153
|
-
return;
|
|
154
|
-
}
|
|
155
|
-
app.addHook('onReady', async () => {
|
|
156
|
-
let account;
|
|
157
|
-
try {
|
|
158
|
-
account = readAccount(ctx.config);
|
|
159
|
-
}
|
|
160
|
-
catch (error) {
|
|
161
|
-
if (SystemError.is(error) && error.type === 'CONFIG_UNAVAILABLE') {
|
|
162
|
-
// 出 spec 路径(generateOpenApi 不跑 config 槽位):配置不可用 → 跳过自注册
|
|
163
|
-
return;
|
|
164
|
-
}
|
|
165
|
-
ctx.log.error({ error }, '[PermissionOperation][auth] read account config failed');
|
|
166
|
-
return;
|
|
167
|
-
}
|
|
168
|
-
// 未配置 account `serviceUrl`(含 account 自身)→ 不注册
|
|
169
|
-
if (!account?.serviceUrl) {
|
|
170
|
-
return;
|
|
171
|
-
}
|
|
172
|
-
try {
|
|
173
|
-
const operations = toPermissionOperations(readRegisteredOperations(app));
|
|
174
|
-
if (operations.length === 0) {
|
|
175
|
-
return;
|
|
176
|
-
}
|
|
177
|
-
await requestPermissionRegistration(account, {
|
|
178
|
-
service,
|
|
179
|
-
version: identity?.version ?? '',
|
|
180
|
-
operations,
|
|
181
|
-
});
|
|
182
|
-
}
|
|
183
|
-
catch (error) {
|
|
184
|
-
// 失败不致命:只记日志、继续启动(不得抛错中断)
|
|
185
|
-
ctx.log.error({ error }, '[PermissionOperation][auth] self-registration failed');
|
|
186
|
-
}
|
|
187
|
-
});
|
|
188
|
-
},
|
|
189
|
-
};
|
|
190
|
-
}
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import type { MiddlewareUnit } from '../types.js';
|
|
2
|
-
/**
|
|
3
|
-
* 标准中间件单元 `context`(可替换)。
|
|
4
|
-
*
|
|
5
|
-
* `decorateRequest(decorateAs, ...)`(默认 `'ctx'`),消费既有 `context/createContext`。
|
|
6
|
-
* 装饰必须在 `ready()` 之前注册(`register` 期完成)。
|
|
7
|
-
*/
|
|
8
|
-
export interface ContextMiddlewareOptions {
|
|
9
|
-
/** 默认 `'ctx'` */
|
|
10
|
-
decorateAs?: string;
|
|
11
|
-
}
|
|
12
|
-
export declare function createContextMiddleware(options?: ContextMiddlewareOptions): MiddlewareUnit;
|
|
13
|
-
//# sourceMappingURL=context.d.ts.map
|