@taicode/common-server 3.8.0 → 4.0.0-beta.2

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.
Files changed (145) hide show
  1. package/output/app/auth.test.d.ts +2 -0
  2. package/output/app/auth.test.d.ts.map +1 -0
  3. package/output/app/auth.test.js +148 -0
  4. package/output/app/boot.d.ts +39 -0
  5. package/output/app/boot.d.ts.map +1 -0
  6. package/output/app/boot.js +140 -0
  7. package/output/app/config.test.d.ts +2 -0
  8. package/output/app/config.test.d.ts.map +1 -0
  9. package/output/app/config.test.js +132 -0
  10. package/output/app/context.d.ts +70 -0
  11. package/output/app/context.d.ts.map +1 -0
  12. package/output/app/context.js +73 -0
  13. package/output/app/core/cookie.d.ts +25 -0
  14. package/output/app/core/cookie.d.ts.map +1 -0
  15. package/output/app/core/cookie.js +22 -0
  16. package/output/app/core/identity.d.ts +12 -0
  17. package/output/app/core/identity.d.ts.map +1 -0
  18. package/output/app/core/identity.js +14 -0
  19. package/output/app/core/index.d.ts +44 -0
  20. package/output/app/core/index.d.ts.map +1 -0
  21. package/output/app/core/index.js +57 -0
  22. package/output/app/core/logging.d.ts +13 -0
  23. package/output/app/core/logging.d.ts.map +1 -0
  24. package/output/app/core/logging.js +29 -0
  25. package/output/app/core/openapi.d.ts +17 -0
  26. package/output/app/core/openapi.d.ts.map +1 -0
  27. package/output/app/core/openapi.js +42 -0
  28. package/output/app/core/request-id.d.ts +36 -0
  29. package/output/app/core/request-id.d.ts.map +1 -0
  30. package/output/app/core/request-id.js +66 -0
  31. package/output/app/core/response.d.ts +41 -0
  32. package/output/app/core/response.d.ts.map +1 -0
  33. package/output/app/core/response.js +89 -0
  34. package/output/app/define-server.negative-cases.d.ts +40 -0
  35. package/output/app/define-server.negative-cases.d.ts.map +1 -0
  36. package/output/app/define-server.negative-cases.js +268 -0
  37. package/output/app/define-server.test.js +86 -288
  38. package/output/app/entries.d.ts +29 -0
  39. package/output/app/entries.d.ts.map +1 -0
  40. package/output/app/entries.js +64 -0
  41. package/output/app/env.d.ts +39 -4
  42. package/output/app/env.d.ts.map +1 -1
  43. package/output/app/env.js +32 -4
  44. package/output/app/env.test.js +67 -21
  45. package/output/app/error-contract.test.d.ts +2 -0
  46. package/output/app/error-contract.test.d.ts.map +1 -0
  47. package/output/app/error-contract.test.js +227 -0
  48. package/output/app/errors.d.ts +20 -0
  49. package/output/app/errors.d.ts.map +1 -0
  50. package/output/app/errors.js +51 -0
  51. package/output/app/generate-openapi.test.d.ts +2 -0
  52. package/output/app/generate-openapi.test.d.ts.map +1 -0
  53. package/output/app/generate-openapi.test.js +123 -0
  54. package/output/app/index.d.ts +15 -15
  55. package/output/app/index.d.ts.map +1 -1
  56. package/output/app/index.js +18 -9
  57. package/output/app/lifecycle-logging.test.d.ts +2 -0
  58. package/output/app/lifecycle-logging.test.d.ts.map +1 -0
  59. package/output/app/lifecycle-logging.test.js +155 -0
  60. package/output/app/lifecycle.d.ts +70 -0
  61. package/output/app/lifecycle.d.ts.map +1 -0
  62. package/output/app/lifecycle.js +99 -0
  63. package/output/app/lifecycle.test.d.ts +2 -0
  64. package/output/app/lifecycle.test.d.ts.map +1 -0
  65. package/output/app/lifecycle.test.js +152 -0
  66. package/output/app/middleware/auth.d.ts +71 -0
  67. package/output/app/middleware/auth.d.ts.map +1 -0
  68. package/output/app/middleware/auth.js +190 -0
  69. package/output/app/middleware/context.d.ts +13 -0
  70. package/output/app/middleware/context.d.ts.map +1 -0
  71. package/output/app/middleware/context.js +15 -0
  72. package/output/app/middleware/cors.d.ts +14 -0
  73. package/output/app/middleware/cors.d.ts.map +1 -0
  74. package/output/app/middleware/cors.js +30 -0
  75. package/output/app/middleware/index.d.ts +17 -0
  76. package/output/app/middleware/index.d.ts.map +1 -0
  77. package/output/app/middleware/index.js +16 -0
  78. package/output/app/middleware/rate-limit.d.ts +24 -0
  79. package/output/app/middleware/rate-limit.d.ts.map +1 -0
  80. package/output/app/middleware/rate-limit.js +46 -0
  81. package/output/app/middleware-order.test.d.ts +2 -0
  82. package/output/app/middleware-order.test.d.ts.map +1 -0
  83. package/output/app/middleware-order.test.js +148 -0
  84. package/output/app/permission-operations.d.ts +48 -0
  85. package/output/app/permission-operations.d.ts.map +1 -0
  86. package/output/app/permission-operations.js +77 -0
  87. package/output/app/permission-operations.test.d.ts +2 -0
  88. package/output/app/permission-operations.test.d.ts.map +1 -0
  89. package/output/app/permission-operations.test.js +72 -0
  90. package/output/app/permission-registration.test.d.ts +2 -0
  91. package/output/app/permission-registration.test.d.ts.map +1 -0
  92. package/output/app/permission-registration.test.js +138 -0
  93. package/output/app/redis.d.ts +45 -0
  94. package/output/app/redis.d.ts.map +1 -0
  95. package/output/app/redis.js +61 -0
  96. package/output/app/registered-operations.test.d.ts +2 -0
  97. package/output/app/registered-operations.test.d.ts.map +1 -0
  98. package/output/app/registered-operations.test.js +57 -0
  99. package/output/app/request-id.test.d.ts +2 -0
  100. package/output/app/request-id.test.d.ts.map +1 -0
  101. package/output/app/request-id.test.js +130 -0
  102. package/output/app/resources.test.d.ts +2 -0
  103. package/output/app/resources.test.d.ts.map +1 -0
  104. package/output/app/resources.test.js +199 -0
  105. package/output/app/shutdown.d.ts +17 -4
  106. package/output/app/shutdown.d.ts.map +1 -1
  107. package/output/app/shutdown.js +27 -12
  108. package/output/app/shutdown.test.js +78 -124
  109. package/output/app/signal.d.ts +4 -4
  110. package/output/app/signal.d.ts.map +1 -1
  111. package/output/app/signal.js +3 -3
  112. package/output/app/smoke.test.d.ts +2 -0
  113. package/output/app/smoke.test.d.ts.map +1 -0
  114. package/output/app/smoke.test.js +210 -0
  115. package/output/app/test-support.d.ts +21 -0
  116. package/output/app/test-support.d.ts.map +1 -0
  117. package/output/app/test-support.js +24 -0
  118. package/output/app/type-augment.d.ts +34 -0
  119. package/output/app/type-augment.d.ts.map +1 -0
  120. package/output/app/type-augment.js +7 -0
  121. package/output/app/types.d.ts +205 -126
  122. package/output/app/types.d.ts.map +1 -1
  123. package/output/app/types.js +2 -1
  124. package/package.json +10 -6
  125. package/output/app/assemble.d.ts +0 -16
  126. package/output/app/assemble.d.ts.map +0 -1
  127. package/output/app/assemble.js +0 -124
  128. package/output/app/database.d.ts +0 -36
  129. package/output/app/database.d.ts.map +0 -1
  130. package/output/app/database.js +0 -40
  131. package/output/app/database.test.d.ts +0 -2
  132. package/output/app/database.test.d.ts.map +0 -1
  133. package/output/app/database.test.js +0 -66
  134. package/output/app/default-modules.d.ts +0 -23
  135. package/output/app/default-modules.d.ts.map +0 -1
  136. package/output/app/default-modules.js +0 -40
  137. package/output/app/define-server.d.ts +0 -12
  138. package/output/app/define-server.d.ts.map +0 -1
  139. package/output/app/define-server.js +0 -289
  140. package/output/app/module.d.ts +0 -88
  141. package/output/app/module.d.ts.map +0 -1
  142. package/output/app/module.js +0 -34
  143. package/output/app/steps.d.ts +0 -17
  144. package/output/app/steps.d.ts.map +0 -1
  145. package/output/app/steps.js +0 -41
@@ -0,0 +1,152 @@
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
+ });
@@ -0,0 +1,71 @@
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
@@ -0,0 +1 @@
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"}
@@ -0,0 +1,190 @@
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
+ }
@@ -0,0 +1,13 @@
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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../../source/app/middleware/context.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAEjD;;;;;GAKG;AAEH,MAAM,WAAW,wBAAwB;IACvC,iBAAiB;IACjB,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAED,wBAAgB,uBAAuB,CAAC,OAAO,GAAE,wBAA6B,GAAG,cAAc,CAa9F"}
@@ -0,0 +1,15 @@
1
+ import { createContext } from '../../context/index.js';
2
+ export function createContextMiddleware(options = {}) {
3
+ const decorateAs = options.decorateAs ?? 'ctx';
4
+ return {
5
+ name: 'context',
6
+ register: (app) => {
7
+ app.decorateRequest(decorateAs, null);
8
+ app.addHook('onRequest', (request, _reply, done) => {
9
+ ;
10
+ request[decorateAs] = createContext(request);
11
+ done();
12
+ });
13
+ },
14
+ };
15
+ }
@@ -0,0 +1,14 @@
1
+ import type { MiddlewareContext, MiddlewareUnit } from '../types.js';
2
+ /**
3
+ * 标准中间件单元 `cors`(可替换)。
4
+ *
5
+ * 不传 `origins` → **每次请求现读**配置的 `cors` 键(配置加载后即生效,不得缓存);
6
+ * **未配置即放行任意源 + 首次请求 warn 一次**(对齐四家现状)。构造期**不读配置**,
7
+ * 故出 spec 路径(配置不可用)不受影响。
8
+ */
9
+ export interface CorsMiddlewareOptions {
10
+ origins?: string[] | '*';
11
+ credentials?: boolean;
12
+ }
13
+ export declare function createCorsMiddleware<C = unknown, S = unknown>(ctx: MiddlewareContext<C, S>, options?: CorsMiddlewareOptions): MiddlewareUnit;
14
+ //# sourceMappingURL=cors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cors.d.ts","sourceRoot":"","sources":["../../../source/app/middleware/cors.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAEpE;;;;;;GAMG;AAEH,MAAM,WAAW,qBAAqB;IACpC,OAAO,CAAC,EAAE,MAAM,EAAE,GAAG,GAAG,CAAA;IACxB,WAAW,CAAC,EAAE,OAAO,CAAA;CACtB;AAOD,wBAAgB,oBAAoB,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,OAAO,EAAE,GAAG,EAAE,iBAAiB,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,OAAO,GAAE,qBAA0B,GAAG,cAAc,CA6BhJ"}
@@ -0,0 +1,30 @@
1
+ import cors from '@fastify/cors';
2
+ import { readConfigKey } from '../context.js';
3
+ export function createCorsMiddleware(ctx, options = {}) {
4
+ return {
5
+ name: 'cors',
6
+ register: async (app) => {
7
+ let warned = false;
8
+ // 请求期现读:`cors` 配置变化立即生效;构造期不读
9
+ const resolveOrigins = () => {
10
+ const configured = readConfigKey(ctx.config, 'cors');
11
+ return options.origins ?? (configured?.enabled ? configured.origins : undefined);
12
+ };
13
+ await app.register(cors, {
14
+ origin: (origin, callback) => {
15
+ const origins = resolveOrigins();
16
+ if (origins === undefined || origins === '*') {
17
+ if (!warned) {
18
+ warned = true;
19
+ ctx.log.warn({}, '[middleware] cors origins not configured; allowing any origin');
20
+ }
21
+ callback(null, true);
22
+ return;
23
+ }
24
+ callback(null, origins.includes(origin ?? ''));
25
+ },
26
+ credentials: options.credentials ?? true,
27
+ });
28
+ },
29
+ };
30
+ }
@@ -0,0 +1,17 @@
1
+ import type { MiddlewareContext, MiddlewareUnit } from '../types.js';
2
+ export { createCorsMiddleware } from './cors.js';
3
+ export { createContextMiddleware } from './context.js';
4
+ export { createAuthMiddleware, defaultAuthSkip } from './auth.js';
5
+ export { createRateLimitMiddleware } from './rate-limit.js';
6
+ export type { CorsMiddlewareOptions } from './cors.js';
7
+ export type { ContextMiddlewareOptions } from './context.js';
8
+ export type { AccountIntegrationConfig, AuthMiddlewareOptions, AuthSkip, AuthVerifyInput, AuthVerifyMetadata, AuthVerifyResult, } from './auth.js';
9
+ export type { RateLimitMiddlewareOptions } from './rate-limit.js';
10
+ /**
11
+ * 默认中间件预设:`[cors, context, auth]`。
12
+ *
13
+ * 顺序 `cors → context → auth` 只是**预设内容**,不是框架常量:可 `...defaultMiddlewares(ctx)`
14
+ * 后替换 / 插入 / 删除任意项。`rateLimit` **不在**预设内(唯一一个默认不装的项)。
15
+ */
16
+ export declare function defaultMiddlewares<C = unknown, S = unknown>(ctx: MiddlewareContext<C, S>): MiddlewareUnit[];
17
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../source/app/middleware/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAEpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAA;AAChD,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAA;AACtD,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,MAAM,WAAW,CAAA;AACjE,OAAO,EAAE,yBAAyB,EAAE,MAAM,iBAAiB,CAAA;AAE3D,YAAY,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAA;AACtD,YAAY,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAA;AAC5D,YAAY,EACV,wBAAwB,EACxB,qBAAqB,EACrB,QAAQ,EACR,eAAe,EACf,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,WAAW,CAAA;AAClB,YAAY,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAA;AAEjE;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,OAAO,EACzD,GAAG,EAAE,iBAAiB,CAAC,CAAC,EAAE,CAAC,CAAC,GAC3B,cAAc,EAAE,CAElB"}
@@ -0,0 +1,16 @@
1
+ import { createAuthMiddleware } from './auth.js';
2
+ import { createContextMiddleware } from './context.js';
3
+ import { createCorsMiddleware } from './cors.js';
4
+ export { createCorsMiddleware } from './cors.js';
5
+ export { createContextMiddleware } from './context.js';
6
+ export { createAuthMiddleware, defaultAuthSkip } from './auth.js';
7
+ export { createRateLimitMiddleware } from './rate-limit.js';
8
+ /**
9
+ * 默认中间件预设:`[cors, context, auth]`。
10
+ *
11
+ * 顺序 `cors → context → auth` 只是**预设内容**,不是框架常量:可 `...defaultMiddlewares(ctx)`
12
+ * 后替换 / 插入 / 删除任意项。`rateLimit` **不在**预设内(唯一一个默认不装的项)。
13
+ */
14
+ export function defaultMiddlewares(ctx) {
15
+ return [createCorsMiddleware(ctx), createContextMiddleware(), createAuthMiddleware(ctx)];
16
+ }
@@ -0,0 +1,24 @@
1
+ import type { MiddlewareContext, MiddlewareUnit } from '../types.js';
2
+ import type { RateLimitStore } from '../../rate-limiter/types.js';
3
+ /**
4
+ * 标准中间件单元 `rateLimit`(可替换;**不在默认预设内**)。
5
+ *
6
+ * 路由级限流;存储后端由调用方注入(缺省进程内 memory)。`TOO_MANY_REQUESTS` 经 `UserError`
7
+ * 仍映射 **400**。路由未声明 `config.rateLimit` 且未给 `defaultLimit` 时该项空转。
8
+ *
9
+ * 注:中间件的 ctx 看不到 `resources`(中间件不得直连数据层),因此 Redis store 需由调用方
10
+ * 在 `services` 侧构造后注入(`store`),框架不再自行探测 Redis。
11
+ */
12
+ export interface RateLimitMiddlewareOptions {
13
+ /** 存储后端(缺省进程内 memory) */
14
+ store?: RateLimitStore;
15
+ /** 限流键前缀(缺省 `<service>:`) */
16
+ keyPrefix?: string;
17
+ /** 缺省规则:路由未声明 `config.rateLimit` 时使用 */
18
+ defaultLimit?: {
19
+ max: number;
20
+ windowMs: number;
21
+ };
22
+ }
23
+ export declare function createRateLimitMiddleware<C = unknown, S = unknown>(ctx: MiddlewareContext<C, S>, options?: RateLimitMiddlewareOptions): MiddlewareUnit;
24
+ //# sourceMappingURL=rate-limit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-limit.d.ts","sourceRoot":"","sources":["../../../source/app/middleware/rate-limit.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AACpE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAA;AAGjE;;;;;;;;GAQG;AAEH,MAAM,WAAW,0BAA0B;IACzC,yBAAyB;IACzB,KAAK,CAAC,EAAE,cAAc,CAAA;IACtB,6BAA6B;IAC7B,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,wCAAwC;IACxC,YAAY,CAAC,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAA;CACjD;AAsBD,wBAAgB,yBAAyB,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,OAAO,EAAE,GAAG,EAAE,iBAAiB,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,OAAO,GAAE,0BAA+B,GAAG,cAAc,CA0B1J"}
@@ -0,0 +1,46 @@
1
+ import { createRateLimitKey, RateLimiter } from '../../rate-limiter/rate-limiter.js';
2
+ import { MemoryRateLimitStore } from '../../rate-limiter/memory-store.js';
3
+ import { readServerIdentity } from '../core/identity.js';
4
+ import { UserError } from '../errors.js';
5
+ function resolveRule(request, defaultRule) {
6
+ const configured = request.routeOptions?.config?.rateLimit;
7
+ return configured ?? defaultRule;
8
+ }
9
+ function buildKeys(request, keys) {
10
+ return keys.map((key) => {
11
+ if (key === 'ip') {
12
+ return `ip:${request.ip}`;
13
+ }
14
+ if (key === 'user') {
15
+ return `user:${String(request.user?.id ?? 'anonymous')}`;
16
+ }
17
+ if (key === 'path') {
18
+ return `path:${request.routeOptions?.url ?? request.url}`;
19
+ }
20
+ return `${key}:${String(request[key] ?? '')}`;
21
+ });
22
+ }
23
+ export function createRateLimitMiddleware(ctx, options = {}) {
24
+ void ctx;
25
+ return {
26
+ name: 'rateLimit',
27
+ register: (app) => {
28
+ const limiter = new RateLimiter({ store: options.store ?? new MemoryRateLimitStore() });
29
+ const prefix = options.keyPrefix ?? `${readServerIdentity(app)?.service ?? ''}:`;
30
+ const defaultRule = options.defaultLimit
31
+ ? { limit: options.defaultLimit.max, window: options.defaultLimit.windowMs / 1000 }
32
+ : undefined;
33
+ app.addHook('preValidation', async (request) => {
34
+ const rule = resolveRule(request, defaultRule);
35
+ if (!rule) {
36
+ return;
37
+ }
38
+ const keys = buildKeys(request, rule.keys ?? ['ip']).map((key) => createRateLimitKey(prefix, key));
39
+ const result = await limiter.checkMultiLimit(keys, { limit: rule.limit, window: rule.window });
40
+ if (!result.allowed) {
41
+ throw new UserError('TOO_MANY_REQUESTS', undefined, '请求过于频繁');
42
+ }
43
+ });
44
+ },
45
+ };
46
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=middleware-order.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware-order.test.d.ts","sourceRoot":"","sources":["../../source/app/middleware-order.test.ts"],"names":[],"mappings":""}