@aomex/auth 3.30.6 → 3.30.8-alpha.62.sha-92b25bb
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/CHANGELOG.md +8 -0
- package/README.md +5 -0
- package/dist/auth-error-BlqNQFwu.js +14 -0
- package/dist/auth-error-BlqNQFwu.js.map +1 -0
- package/dist/index.d.ts +36 -48
- package/dist/index.js +67 -106
- package/dist/index.js.map +1 -1
- package/dist/strategies/auth-api-key-strategy.d.ts +90 -0
- package/dist/strategies/auth-api-key-strategy.js +104 -0
- package/dist/strategies/auth-api-key-strategy.js.map +1 -0
- package/dist/strategies/auth-bearer-strategy.d.ts +100 -0
- package/dist/strategies/auth-bearer-strategy.js +114 -0
- package/dist/strategies/auth-bearer-strategy.js.map +1 -0
- package/dist/strategy-B0bAl8FM.d.ts +8 -0
- package/package.json +31 -16
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,14 @@
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
|
5
5
|
|
|
6
|
+
## [3.30.7](https://github.com/aomex/aomex/compare/v3.30.6...v3.30.7) (2026-11-01)
|
|
7
|
+
|
|
8
|
+
**Note:** Version bump only for package @aomex/auth
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
6
14
|
## [3.30.6](https://github.com/aomex/aomex/compare/v3.30.5...v3.30.6) (2026-10-19)
|
|
7
15
|
|
|
8
16
|
**Note:** Version bump only for package @aomex/auth
|
package/README.md
CHANGED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { statuses } from "@aomex/web";
|
|
2
|
+
// src/strategy.ts
|
|
3
|
+
var Strategy = class {
|
|
4
|
+
openapi() {
|
|
5
|
+
return { postMethod(methodItem) {
|
|
6
|
+
methodItem.responses[401] ||= { description: statuses.message[401] };
|
|
7
|
+
} };
|
|
8
|
+
}
|
|
9
|
+
};
|
|
10
|
+
// src/auth-error.ts
|
|
11
|
+
var AuthError = class extends Error {};
|
|
12
|
+
export { Strategy as n, AuthError as t };
|
|
13
|
+
|
|
14
|
+
//# sourceMappingURL=auth-error-BlqNQFwu.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth-error-BlqNQFwu.js","names":[],"sources":["../src/strategy.ts","../src/auth-error.ts"],"sourcesContent":["import { statuses, type OpenApiInjector, type WebContext } from '@aomex/web';\nimport type { AuthError } from './auth-error';\n\nexport abstract class Strategy<\n Payload extends object | string | number,\n AuthorizeArgs extends any[] = any[],\n> {\n protected abstract authenticate(\n ctx: WebContext,\n ): Payload | false | AuthError | Promise<Payload | false | AuthError>;\n\n protected abstract authorize(\n payload: Payload,\n ...args: AuthorizeArgs\n ): boolean | AuthError | Promise<boolean | AuthError>;\n\n protected openapi(): OpenApiInjector {\n return {\n postMethod(methodItem) {\n methodItem.responses[401] ||= {\n description: statuses.message[401]!,\n };\n },\n };\n }\n}\n","export class AuthError extends Error {}\n"],"mappings":";;AAGA,IAAsB,WAAtB,MAGE;CAUA,UAAqC;EACnC,OAAO,EACL,WAAW,YAAY;GACrB,WAAW,UAAU,SAAS,EAC5B,aAAa,SAAS,QAAQ,KAChC;EACF,EACF;CACF;AACF;;ACzBA,IAAa,YAAb,cAA+B,MAAM,CAAC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,51 +1,39 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
declare
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
declare abstract class Strategy<Payload extends object | string | number, AuthorizeArgs extends any[] = any[]> {
|
|
7
|
-
protected abstract authenticate(ctx: WebContext): Payload | false | AuthError | Promise<Payload | false | AuthError>;
|
|
8
|
-
protected abstract authorize(payload: Payload, ...args: AuthorizeArgs): boolean | AuthError | Promise<boolean | AuthError>;
|
|
9
|
-
protected openapi(): OpenApiInjector;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
declare namespace Auth {
|
|
13
|
-
interface Options<S extends {
|
|
14
|
-
[K: string]: Strategy<object | string | number, any[]>;
|
|
15
|
-
}> {
|
|
16
|
-
strategies: S;
|
|
17
|
-
}
|
|
18
|
-
type DetermineAuthorizeArgs<S extends {
|
|
19
|
-
[K: string]: Strategy<object | string | number, any[]>;
|
|
20
|
-
}, StrategyName extends keyof S> = S[StrategyName] extends Strategy<any, infer Args> ? unknown[] extends Args ? [] : Args : never;
|
|
21
|
-
type DetermineMiddlewareProps<S extends {
|
|
22
|
-
[K: string]: Strategy<object | string | number, any[]>;
|
|
23
|
-
}, StrategyName extends keyof S> = {
|
|
24
|
-
readonly auth: {
|
|
25
|
-
readonly [K in StrategyName]: S[StrategyName] extends Strategy<infer P, any> ? P : never;
|
|
26
|
-
};
|
|
27
|
-
};
|
|
28
|
-
}
|
|
29
|
-
declare class Auth<S extends {
|
|
1
|
+
import { n as AuthError, t as Strategy } from "./strategy-B0bAl8FM.js";
|
|
2
|
+
import { WebContext, WebMiddleware } from "@aomex/web";
|
|
3
|
+
export declare namespace Auth {
|
|
4
|
+
interface Options<S extends {
|
|
30
5
|
[K: string]: Strategy<object | string | number, any[]>;
|
|
6
|
+
}> {
|
|
7
|
+
strategies: S;
|
|
8
|
+
}
|
|
9
|
+
type DetermineAuthorizeArgs<S extends {
|
|
10
|
+
[K: string]: Strategy<object | string | number, any[]>;
|
|
11
|
+
}, StrategyName extends keyof S> = S[StrategyName] extends Strategy<any, infer Args> ? unknown[] extends Args ? [] : Args : never;
|
|
12
|
+
type DetermineMiddlewareProps<S extends {
|
|
13
|
+
[K: string]: Strategy<object | string | number, any[]>;
|
|
14
|
+
}, StrategyName extends keyof S> = {
|
|
15
|
+
readonly auth: { readonly [K in StrategyName]: S[StrategyName] extends Strategy<infer P, any> ? P : never; };
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export declare class Auth<S extends {
|
|
19
|
+
[K: string]: Strategy<object | string | number, any[]>;
|
|
31
20
|
}> {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
21
|
+
protected readonly options: Auth.Options<S>;
|
|
22
|
+
constructor(options: Auth.Options<S>);
|
|
23
|
+
/**
|
|
24
|
+
* 获取策略实例
|
|
25
|
+
*/
|
|
26
|
+
strategy<StrategyName extends keyof S>(name: StrategyName): S[StrategyName];
|
|
27
|
+
/**
|
|
28
|
+
* 在已经身份认证(authenticate)的基础上进行访问权限认证,不满足时响应`403`状态码
|
|
29
|
+
*/
|
|
30
|
+
authorize<StrategyName extends keyof S>(name: StrategyName, ...args: Auth.DetermineAuthorizeArgs<S, StrategyName>): WebMiddleware<object>;
|
|
31
|
+
/**
|
|
32
|
+
* 对访问凭证(token,cookie,session等)进行身份确认,不满足时响应`401`状态码
|
|
33
|
+
*/
|
|
34
|
+
authenticate<StrategyName extends keyof S>(name: StrategyName): WebMiddleware<Auth.DetermineMiddlewareProps<S, StrategyName>> & {
|
|
35
|
+
authorize: (...args: Auth.DetermineAuthorizeArgs<S, StrategyName>) => WebMiddleware<Auth.DetermineMiddlewareProps<S, StrategyName>>;
|
|
36
|
+
};
|
|
37
|
+
protected internalAuthorize(ctx: WebContext, strategy: Strategy<any>, payload: any, authorizeArgs: any[]): Promise<undefined>;
|
|
49
38
|
}
|
|
50
|
-
|
|
51
|
-
export { Auth, AuthError, Strategy };
|
|
39
|
+
export { AuthError, Strategy };
|
package/dist/index.js
CHANGED
|
@@ -1,111 +1,72 @@
|
|
|
1
|
-
|
|
2
|
-
import { statuses } from "@aomex/web";
|
|
3
|
-
var Strategy = class {
|
|
4
|
-
openapi() {
|
|
5
|
-
return {
|
|
6
|
-
postMethod(methodItem) {
|
|
7
|
-
methodItem.responses[401] ||= {
|
|
8
|
-
description: statuses.message[401]
|
|
9
|
-
};
|
|
10
|
-
}
|
|
11
|
-
};
|
|
12
|
-
}
|
|
13
|
-
};
|
|
14
|
-
|
|
15
|
-
// src/auth.ts
|
|
1
|
+
import { n as Strategy, t as AuthError } from "./auth-error-BlqNQFwu.js";
|
|
16
2
|
import { middleware } from "@aomex/common";
|
|
17
|
-
|
|
18
|
-
// src/auth-error.ts
|
|
19
|
-
var AuthError = class extends Error {
|
|
20
|
-
};
|
|
21
|
-
|
|
22
3
|
// src/auth.ts
|
|
23
4
|
var Auth = class {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
let authorized = false;
|
|
89
|
-
try {
|
|
90
|
-
authorized = await strategy["authorize"](payload, ...authorizeArgs);
|
|
91
|
-
} catch (e) {
|
|
92
|
-
if (e instanceof AuthError) {
|
|
93
|
-
return ctx.throw(403, e);
|
|
94
|
-
} else {
|
|
95
|
-
throw e;
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
if (authorized instanceof AuthError) {
|
|
99
|
-
return ctx.throw(403, authorized.message);
|
|
100
|
-
}
|
|
101
|
-
if (!authorized) {
|
|
102
|
-
return ctx.throw(403);
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
};
|
|
106
|
-
export {
|
|
107
|
-
Auth,
|
|
108
|
-
AuthError,
|
|
109
|
-
Strategy
|
|
5
|
+
options;
|
|
6
|
+
constructor(options) {
|
|
7
|
+
this.options = options;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* 获取策略实例
|
|
11
|
+
*/
|
|
12
|
+
strategy(name) {
|
|
13
|
+
return this.options.strategies[name];
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* 在已经身份认证(authenticate)的基础上进行访问权限认证,不满足时响应`403`状态码
|
|
17
|
+
*/
|
|
18
|
+
authorize(name, ...args) {
|
|
19
|
+
const strategy = this.strategy(name);
|
|
20
|
+
return middleware.web({ fn: async (ctx, next) => {
|
|
21
|
+
const payload = ctx.auth[name];
|
|
22
|
+
await this.internalAuthorize(ctx, strategy, payload, args);
|
|
23
|
+
return next();
|
|
24
|
+
} });
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* 对访问凭证(token,cookie,session等)进行身份确认,不满足时响应`401`状态码
|
|
28
|
+
*/
|
|
29
|
+
authenticate(name) {
|
|
30
|
+
const strategy = this.strategy(name);
|
|
31
|
+
let withAuthorize = false;
|
|
32
|
+
const authorizeArgs = [];
|
|
33
|
+
const md = middleware.web({
|
|
34
|
+
fn: async (ctx, next) => {
|
|
35
|
+
let payload = false;
|
|
36
|
+
try {
|
|
37
|
+
payload = await strategy["authenticate"](ctx);
|
|
38
|
+
} catch (e) {
|
|
39
|
+
if (e instanceof AuthError) return ctx.throw(401, e);
|
|
40
|
+
else throw e;
|
|
41
|
+
}
|
|
42
|
+
if (payload instanceof AuthError) return ctx.throw(401, payload.message);
|
|
43
|
+
if (payload === false) return ctx.throw(401);
|
|
44
|
+
if (withAuthorize) await this.internalAuthorize(ctx, strategy, payload, authorizeArgs);
|
|
45
|
+
ctx.auth ||= {};
|
|
46
|
+
ctx.auth[name] = payload;
|
|
47
|
+
return next();
|
|
48
|
+
},
|
|
49
|
+
openapi: strategy["openapi"]()
|
|
50
|
+
});
|
|
51
|
+
md.authorize = (...args) => {
|
|
52
|
+
withAuthorize = true;
|
|
53
|
+
authorizeArgs.push(...args);
|
|
54
|
+
return md;
|
|
55
|
+
};
|
|
56
|
+
return md;
|
|
57
|
+
}
|
|
58
|
+
async internalAuthorize(ctx, strategy, payload, authorizeArgs) {
|
|
59
|
+
let authorized = false;
|
|
60
|
+
try {
|
|
61
|
+
authorized = await strategy["authorize"](payload, ...authorizeArgs);
|
|
62
|
+
} catch (e) {
|
|
63
|
+
if (e instanceof AuthError) return ctx.throw(403, e);
|
|
64
|
+
else throw e;
|
|
65
|
+
}
|
|
66
|
+
if (authorized instanceof AuthError) return ctx.throw(403, authorized.message);
|
|
67
|
+
if (!authorized) return ctx.throw(403);
|
|
68
|
+
}
|
|
110
69
|
};
|
|
70
|
+
export { Auth, AuthError, Strategy };
|
|
71
|
+
|
|
111
72
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/auth.ts"],"sourcesContent":["import type { WebContext, WebMiddleware } from '@aomex/web';\nimport { Strategy } from './strategy';\nimport { middleware } from '@aomex/common';\nimport { AuthError } from './auth-error';\n\nexport namespace Auth {\n export interface Options<\n S extends { [K: string]: Strategy<object | string | number, any[]> },\n > {\n strategies: S;\n }\n\n export type DetermineAuthorizeArgs<\n S extends { [K: string]: Strategy<object | string | number, any[]> },\n StrategyName extends keyof S,\n > =\n S[StrategyName] extends Strategy<any, infer Args>\n ? unknown[] extends Args\n ? []\n : Args\n : never;\n\n export type DetermineMiddlewareProps<\n S extends { [K: string]: Strategy<object | string | number, any[]> },\n StrategyName extends keyof S,\n > = {\n readonly auth: {\n readonly [K in StrategyName]: S[StrategyName] extends Strategy<infer P, any>\n ? P\n : never;\n };\n };\n}\n\nexport class Auth<S extends { [K: string]: Strategy<object | string | number, any[]> }> {\n constructor(protected readonly options: Auth.Options<S>) {}\n\n /**\n * 获取策略实例\n */\n public strategy<StrategyName extends keyof S>(name: StrategyName) {\n return this.options.strategies[name]! as S[StrategyName];\n }\n\n /**\n * 在已经身份认证(authenticate)的基础上进行访问权限认证,不满足时响应`403`状态码\n */\n public authorize<StrategyName extends keyof S>(\n name: StrategyName,\n ...args: Auth.DetermineAuthorizeArgs<S, StrategyName>\n ): WebMiddleware<object /* 身份认证时已经给过类型,仅授权不需要返回类型 */> {\n const strategy = this.strategy(name);\n\n return middleware.web<Auth.DetermineMiddlewareProps<S, StrategyName>>({\n fn: async (ctx, next) => {\n const payload = ctx.auth[name];\n await this.internalAuthorize(ctx, strategy, payload, args);\n return next();\n },\n });\n }\n\n /**\n * 对访问凭证(token,cookie,session等)进行身份确认,不满足时响应`401`状态码\n */\n public authenticate<StrategyName extends keyof S>(\n name: StrategyName,\n ): WebMiddleware<Auth.DetermineMiddlewareProps<S, StrategyName>> & {\n authorize: (\n ...args: Auth.DetermineAuthorizeArgs<S, StrategyName>\n ) => WebMiddleware<Auth.DetermineMiddlewareProps<S, StrategyName>>;\n } {\n const strategy = this.strategy(name);\n let withAuthorize = false;\n const authorizeArgs: any[] = [];\n\n const md = middleware.web<{ readonly auth: Record<any, any> }>({\n fn: async (ctx, next) => {\n let payload: string | number | false | object | AuthError = false;\n try {\n payload = await strategy['authenticate'](ctx);\n } catch (e) {\n if (e instanceof AuthError) {\n return ctx.throw(401, e);\n } else {\n throw e;\n }\n }\n if (payload instanceof AuthError) {\n return ctx.throw(401, payload.message);\n }\n if (payload === false) {\n return ctx.throw(401);\n }\n if (withAuthorize) {\n await this.internalAuthorize(ctx, strategy, payload, authorizeArgs);\n }\n ctx.auth ||= {};\n ctx.auth[name] = payload;\n return next();\n },\n openapi: strategy['openapi'](),\n });\n\n // @ts-expect-error\n md.authorize = (...args: any[]) => {\n withAuthorize = true;\n authorizeArgs.push(...args);\n return md;\n };\n\n // @ts-expect-error\n return md;\n }\n\n protected async internalAuthorize(\n ctx: WebContext,\n strategy: Strategy<any>,\n payload: any,\n authorizeArgs: any[],\n ) {\n let authorized: AuthError | boolean = false;\n try {\n authorized = await strategy['authorize'](payload, ...authorizeArgs);\n } catch (e) {\n if (e instanceof AuthError) {\n return ctx.throw(403, e);\n } else {\n throw e;\n }\n }\n if (authorized instanceof AuthError) {\n return ctx.throw(403, authorized.message);\n }\n if (!authorized) {\n return ctx.throw(403);\n }\n }\n}\n"],"mappings":";;;AAkCA,IAAa,OAAb,MAAwF;CACvD;CAA/B,YAAY,SAA6C;EAA1B,KAAA,UAAA;CAA2B;;;;CAK1D,SAA8C,MAAoB;EAChE,OAAO,KAAK,QAAQ,WAAW;CACjC;;;;CAKA,UACE,MACA,GAAG,MACiD;EACpD,MAAM,WAAW,KAAK,SAAS,IAAI;EAEnC,OAAO,WAAW,IAAoD,EACpE,IAAI,OAAO,KAAK,SAAS;GACvB,MAAM,UAAU,IAAI,KAAK;GACzB,MAAM,KAAK,kBAAkB,KAAK,UAAU,SAAS,IAAI;GACzD,OAAO,KAAK;EACd,EACF,CAAC;CACH;;;;CAKA,aACE,MAKA;EACA,MAAM,WAAW,KAAK,SAAS,IAAI;EACnC,IAAI,gBAAgB;EACpB,MAAM,gBAAuB,CAAC;EAE9B,MAAM,KAAK,WAAW,IAAyC;GAC7D,IAAI,OAAO,KAAK,SAAS;IACvB,IAAI,UAAwD;IAC5D,IAAI;KACF,UAAU,MAAM,SAAS,eAAe,CAAC,GAAG;IAC9C,SAAS,GAAG;KACV,IAAI,aAAa,WACf,OAAO,IAAI,MAAM,KAAK,CAAC;UAEvB,MAAM;IAEV;IACA,IAAI,mBAAmB,WACrB,OAAO,IAAI,MAAM,KAAK,QAAQ,OAAO;IAEvC,IAAI,YAAY,OACd,OAAO,IAAI,MAAM,GAAG;IAEtB,IAAI,eACF,MAAM,KAAK,kBAAkB,KAAK,UAAU,SAAS,aAAa;IAEpE,IAAI,SAAS,CAAC;IACd,IAAI,KAAK,QAAQ;IACjB,OAAO,KAAK;GACd;GACA,SAAS,SAAS,UAAU,CAAC;EAC/B,CAAC;EAGD,GAAG,aAAa,GAAG,SAAgB;GACjC,gBAAgB;GAChB,cAAc,KAAK,GAAG,IAAI;GAC1B,OAAO;EACT;EAGA,OAAO;CACT;CAEA,MAAgB,kBACd,KACA,UACA,SACA,eACA;EACA,IAAI,aAAkC;EACtC,IAAI;GACF,aAAa,MAAM,SAAS,YAAY,CAAC,SAAS,GAAG,aAAa;EACpE,SAAS,GAAG;GACV,IAAI,aAAa,WACf,OAAO,IAAI,MAAM,KAAK,CAAC;QAEvB,MAAM;EAEV;EACA,IAAI,sBAAsB,WACxB,OAAO,IAAI,MAAM,KAAK,WAAW,OAAO;EAE1C,IAAI,CAAC,YACH,OAAO,IAAI,MAAM,GAAG;CAExB;AACF"}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { n as AuthError, t as Strategy } from "../strategy-B0bAl8FM.js";
|
|
2
|
+
import { OpenApiInjector, WebContext } from "@aomex/web";
|
|
3
|
+
export type AuthApiKeyLoaderItem = {
|
|
4
|
+
/**
|
|
5
|
+
* 从报文中读取裸值作为 API Key(不解析 Bearer 等 scheme)
|
|
6
|
+
*/
|
|
7
|
+
type: 'header';
|
|
8
|
+
key: `x-api-key` | (string & {});
|
|
9
|
+
} | {
|
|
10
|
+
/**
|
|
11
|
+
* 从查询字符串中读取 API Key。可能进入访问日志与 Referer,生产环境慎用
|
|
12
|
+
*/
|
|
13
|
+
type: 'query';
|
|
14
|
+
key: `api_key` | (string & {});
|
|
15
|
+
} | {
|
|
16
|
+
/**
|
|
17
|
+
* 从 cookie 中读取 API Key
|
|
18
|
+
*/
|
|
19
|
+
type: 'cookie';
|
|
20
|
+
key: `api_key` | (string & {});
|
|
21
|
+
};
|
|
22
|
+
export declare namespace AuthApiKeyStrategy {
|
|
23
|
+
type Options<T extends object | string | number, AuthorizeArgs extends any[]> = {
|
|
24
|
+
/**
|
|
25
|
+
* 找到 API Key 后的回调,解析并返回真正的身份数据
|
|
26
|
+
*/
|
|
27
|
+
onLoaded: (apiKey: string, ctx: WebContext) => T | AuthError | false | Promise<T | AuthError | false>;
|
|
28
|
+
/**
|
|
29
|
+
* 按从左到右的顺序获取 API Key。默认:`[{ type: 'header', key: 'x-api-key' }]`
|
|
30
|
+
*/
|
|
31
|
+
keyLoaders?: AuthApiKeyLoaderItem[];
|
|
32
|
+
} & ({
|
|
33
|
+
/**
|
|
34
|
+
* 身份认证后的权限判断,如果权限不足,则返回`false`,系统会自动响应`403`状态码
|
|
35
|
+
*
|
|
36
|
+
* 有两种方式可以获得认证的身份数据
|
|
37
|
+
* ```
|
|
38
|
+
* {
|
|
39
|
+
* onLoaded(apiKey) {
|
|
40
|
+
* return { appId: 1, role: 1 };
|
|
41
|
+
* },
|
|
42
|
+
* // 方式一:
|
|
43
|
+
* onAuthorize(role: number) {
|
|
44
|
+
* const identity = this.getIdentity();
|
|
45
|
+
* return identity.role === role;
|
|
46
|
+
* },
|
|
47
|
+
* // 方式二:
|
|
48
|
+
* onAuthorize: (role: number) => (identity) => {
|
|
49
|
+
* return identity.role === role;
|
|
50
|
+
* }
|
|
51
|
+
* }
|
|
52
|
+
* ```
|
|
53
|
+
*/
|
|
54
|
+
onAuthorize?: (...args: AuthorizeArgs) => boolean | Promise<boolean> | ((data: T) => boolean | AuthError | Promise<boolean | AuthError>);
|
|
55
|
+
} & ThisType<{
|
|
56
|
+
getIdentity: () => T;
|
|
57
|
+
}>);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* 从请求中获取 API Key
|
|
61
|
+
*
|
|
62
|
+
* 默认从报头 `x-api-key` 读取裸值;也可配置 query / cookie。不支持 body,避免密钥进入请求体日志。
|
|
63
|
+
*/
|
|
64
|
+
export declare class AuthApiKeyStrategy<T extends object | string | number, AuthorizeArgs extends any[]> extends Strategy<{
|
|
65
|
+
readonly key: string;
|
|
66
|
+
readonly data: T;
|
|
67
|
+
}, AuthorizeArgs> {
|
|
68
|
+
protected readonly opts: AuthApiKeyStrategy.Options<T, AuthorizeArgs>;
|
|
69
|
+
protected readonly loaders: AuthApiKeyLoaderItem[];
|
|
70
|
+
constructor(opts: AuthApiKeyStrategy.Options<T, AuthorizeArgs>);
|
|
71
|
+
/**
|
|
72
|
+
* 生成 API Key 字符串(密码学安全随机熵 + 可选业务唯一键)
|
|
73
|
+
* @param algorithm 摘要算法
|
|
74
|
+
* @param uniqueKey 加入唯一的值(比如应用 id)做域隔离
|
|
75
|
+
*/
|
|
76
|
+
signature(algorithm: 'md5' | 'sha1' | 'sha256' | 'sha512' | (string & {}), uniqueKey?: string | number): string;
|
|
77
|
+
protected loadKey(ctx: WebContext): string | false;
|
|
78
|
+
protected loadFromHeader(ctx: WebContext, key: string): string | false;
|
|
79
|
+
protected loadFromQuery(ctx: WebContext, key: string): string | false;
|
|
80
|
+
protected loadFromCookie(ctx: WebContext, key: string): string | false;
|
|
81
|
+
protected authenticate(ctx: WebContext): Promise<{
|
|
82
|
+
readonly key: string;
|
|
83
|
+
readonly data: T;
|
|
84
|
+
} | false>;
|
|
85
|
+
protected authorize(payload: {
|
|
86
|
+
readonly key: string;
|
|
87
|
+
readonly data: T;
|
|
88
|
+
}, ...args: AuthorizeArgs): boolean | AuthError | Promise<boolean | AuthError>;
|
|
89
|
+
protected openapi(): OpenApiInjector;
|
|
90
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { n as Strategy, t as AuthError } from "../auth-error-BlqNQFwu.js";
|
|
2
|
+
import "@aomex/web";
|
|
3
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
4
|
+
// src/strategies/auth-api-key-strategy.ts
|
|
5
|
+
/**
|
|
6
|
+
* 从请求中获取 API Key
|
|
7
|
+
*
|
|
8
|
+
* 默认从报头 `x-api-key` 读取裸值;也可配置 query / cookie。不支持 body,避免密钥进入请求体日志。
|
|
9
|
+
*/
|
|
10
|
+
var AuthApiKeyStrategy = class extends Strategy {
|
|
11
|
+
opts;
|
|
12
|
+
loaders;
|
|
13
|
+
constructor(opts) {
|
|
14
|
+
super();
|
|
15
|
+
this.opts = opts;
|
|
16
|
+
this.loaders = opts.keyLoaders || [{
|
|
17
|
+
type: "header",
|
|
18
|
+
key: "x-api-key"
|
|
19
|
+
}];
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* 生成 API Key 字符串(密码学安全随机熵 + 可选业务唯一键)
|
|
23
|
+
* @param algorithm 摘要算法
|
|
24
|
+
* @param uniqueKey 加入唯一的值(比如应用 id)做域隔离
|
|
25
|
+
*/
|
|
26
|
+
signature(algorithm, uniqueKey) {
|
|
27
|
+
return createHash(algorithm).update(String(uniqueKey ?? "")).update(randomBytes(32)).digest("hex");
|
|
28
|
+
}
|
|
29
|
+
loadKey(ctx) {
|
|
30
|
+
let apiKey = false;
|
|
31
|
+
for (const { type, key } of this.loaders) {
|
|
32
|
+
switch (type) {
|
|
33
|
+
case "header":
|
|
34
|
+
apiKey = this.loadFromHeader(ctx, key);
|
|
35
|
+
break;
|
|
36
|
+
case "query":
|
|
37
|
+
apiKey = this.loadFromQuery(ctx, key);
|
|
38
|
+
break;
|
|
39
|
+
case "cookie": apiKey = this.loadFromCookie(ctx, key);
|
|
40
|
+
}
|
|
41
|
+
if (apiKey) break;
|
|
42
|
+
}
|
|
43
|
+
return apiKey;
|
|
44
|
+
}
|
|
45
|
+
loadFromHeader(ctx, key) {
|
|
46
|
+
if (!key) return false;
|
|
47
|
+
const headerValue = ctx.request.headers[key.toLowerCase()];
|
|
48
|
+
if (headerValue == null) return false;
|
|
49
|
+
const raw = Array.isArray(headerValue) ? headerValue[0] : headerValue;
|
|
50
|
+
if (typeof raw !== "string") return false;
|
|
51
|
+
return raw.trim() || false;
|
|
52
|
+
}
|
|
53
|
+
loadFromQuery(ctx, key) {
|
|
54
|
+
if (!key) return false;
|
|
55
|
+
const value = ctx.request.query[key];
|
|
56
|
+
if (typeof value !== "string") return false;
|
|
57
|
+
return value.trim() || false;
|
|
58
|
+
}
|
|
59
|
+
loadFromCookie(ctx, key) {
|
|
60
|
+
if (!key) return false;
|
|
61
|
+
const value = ctx.request.cookies[key];
|
|
62
|
+
if (typeof value !== "string") return false;
|
|
63
|
+
return value.trim() || false;
|
|
64
|
+
}
|
|
65
|
+
async authenticate(ctx) {
|
|
66
|
+
const { onLoaded } = this.opts;
|
|
67
|
+
const apiKey = this.loadKey(ctx);
|
|
68
|
+
const data = apiKey ? await onLoaded(apiKey, ctx) : false;
|
|
69
|
+
if (data instanceof AuthError) throw data;
|
|
70
|
+
return data !== false && apiKey !== false ? {
|
|
71
|
+
key: apiKey,
|
|
72
|
+
data
|
|
73
|
+
} : false;
|
|
74
|
+
}
|
|
75
|
+
authorize(payload, ...args) {
|
|
76
|
+
if (!this.opts.onAuthorize) return false;
|
|
77
|
+
const result = this.opts.onAuthorize.call({ getIdentity: () => payload.data }, ...args);
|
|
78
|
+
if (typeof result === "function") return result(payload.data);
|
|
79
|
+
return result;
|
|
80
|
+
}
|
|
81
|
+
openapi() {
|
|
82
|
+
const primary = this.loaders[0];
|
|
83
|
+
const scheme = {
|
|
84
|
+
type: "apiKey",
|
|
85
|
+
in: primary.type,
|
|
86
|
+
name: primary.key
|
|
87
|
+
};
|
|
88
|
+
return {
|
|
89
|
+
...super.openapi(),
|
|
90
|
+
onDocument(document) {
|
|
91
|
+
document.components ||= {};
|
|
92
|
+
document.components.securitySchemes ||= {};
|
|
93
|
+
document.components.securitySchemes["apiKey"] ||= scheme;
|
|
94
|
+
},
|
|
95
|
+
onMethod(methodItem) {
|
|
96
|
+
methodItem.security ||= [];
|
|
97
|
+
methodItem.security.push({ apiKey: [] });
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
export { AuthApiKeyStrategy };
|
|
103
|
+
|
|
104
|
+
//# sourceMappingURL=auth-api-key-strategy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth-api-key-strategy.js","names":[],"sources":["../../src/strategies/auth-api-key-strategy.ts"],"sourcesContent":["import { WebContext, type OpenApiInjector } from '@aomex/web';\nimport { createHash, randomBytes } from 'node:crypto';\nimport { AuthError } from '../auth-error';\nimport { Strategy } from '../strategy';\n\nexport type AuthApiKeyLoaderItem =\n | {\n /**\n * 从报文中读取裸值作为 API Key(不解析 Bearer 等 scheme)\n */\n type: 'header';\n key: `x-api-key` | (string & {});\n }\n | {\n /**\n * 从查询字符串中读取 API Key。可能进入访问日志与 Referer,生产环境慎用\n */\n type: 'query';\n key: `api_key` | (string & {});\n }\n | {\n /**\n * 从 cookie 中读取 API Key\n */\n type: 'cookie';\n key: `api_key` | (string & {});\n };\n\nexport namespace AuthApiKeyStrategy {\n export type Options<T extends object | string | number, AuthorizeArgs extends any[]> = {\n /**\n * 找到 API Key 后的回调,解析并返回真正的身份数据\n */\n onLoaded: (\n apiKey: string,\n ctx: WebContext,\n ) => T | AuthError | false | Promise<T | AuthError | false>;\n\n /**\n * 按从左到右的顺序获取 API Key。默认:`[{ type: 'header', key: 'x-api-key' }]`\n */\n keyLoaders?: AuthApiKeyLoaderItem[];\n } & ({\n /**\n * 身份认证后的权限判断,如果权限不足,则返回`false`,系统会自动响应`403`状态码\n *\n * 有两种方式可以获得认证的身份数据\n * ```\n * {\n * onLoaded(apiKey) {\n * return { appId: 1, role: 1 };\n * },\n * // 方式一:\n * onAuthorize(role: number) {\n * const identity = this.getIdentity();\n * return identity.role === role;\n * },\n * // 方式二:\n * onAuthorize: (role: number) => (identity) => {\n * return identity.role === role;\n * }\n * }\n * ```\n */\n onAuthorize?: (\n ...args: AuthorizeArgs\n ) =>\n | boolean\n | Promise<boolean>\n | ((data: T) => boolean | AuthError | Promise<boolean | AuthError>);\n } & ThisType<{ getIdentity: () => T }>);\n}\n\n/**\n * 从请求中获取 API Key\n *\n * 默认从报头 `x-api-key` 读取裸值;也可配置 query / cookie。不支持 body,避免密钥进入请求体日志。\n */\nexport class AuthApiKeyStrategy<\n T extends object | string | number,\n AuthorizeArgs extends any[],\n> extends Strategy<\n {\n readonly key: string;\n readonly data: T;\n },\n AuthorizeArgs\n> {\n protected readonly loaders: AuthApiKeyLoaderItem[];\n\n constructor(protected readonly opts: AuthApiKeyStrategy.Options<T, AuthorizeArgs>) {\n super();\n this.loaders = opts.keyLoaders || [{ type: 'header', key: 'x-api-key' }];\n }\n\n /**\n * 生成 API Key 字符串(密码学安全随机熵 + 可选业务唯一键)\n * @param algorithm 摘要算法\n * @param uniqueKey 加入唯一的值(比如应用 id)做域隔离\n */\n signature(\n algorithm: 'md5' | 'sha1' | 'sha256' | 'sha512' | (string & {}),\n uniqueKey?: string | number,\n ): string {\n return createHash(algorithm)\n .update(String(uniqueKey ?? ''))\n .update(randomBytes(32))\n .digest('hex');\n }\n\n protected loadKey(ctx: WebContext) {\n let apiKey: string | false = false;\n for (const { type, key } of this.loaders) {\n switch (type) {\n case 'header':\n apiKey = this.loadFromHeader(ctx, key);\n break;\n case 'query':\n apiKey = this.loadFromQuery(ctx, key);\n break;\n case 'cookie':\n apiKey = this.loadFromCookie(ctx, key);\n break;\n }\n if (apiKey) break;\n }\n return apiKey;\n }\n\n protected loadFromHeader(ctx: WebContext, key: string): string | false {\n if (!key) return false;\n const headerValue = ctx.request.headers[key.toLowerCase()];\n if (headerValue == null) return false;\n const raw = Array.isArray(headerValue) ? headerValue[0] : headerValue;\n if (typeof raw !== 'string') return false;\n const apiKey = raw.trim();\n return apiKey || false;\n }\n\n protected loadFromQuery(ctx: WebContext, key: string): string | false {\n if (!key) return false;\n const value = ctx.request.query[key];\n if (typeof value !== 'string') return false;\n const apiKey = value.trim();\n return apiKey || false;\n }\n\n protected loadFromCookie(ctx: WebContext, key: string): string | false {\n if (!key) return false;\n const value = ctx.request.cookies[key];\n if (typeof value !== 'string') return false;\n const apiKey = value.trim();\n return apiKey || false;\n }\n\n protected async authenticate(\n ctx: WebContext,\n ): Promise<{ readonly key: string; readonly data: T } | false> {\n const { onLoaded } = this.opts;\n const apiKey = this.loadKey(ctx);\n const data = apiKey ? await onLoaded(apiKey, ctx) : false;\n if (data instanceof AuthError) throw data;\n return data !== false && apiKey !== false ? { key: apiKey, data } : false;\n }\n\n protected override authorize(\n payload: { readonly key: string; readonly data: T },\n ...args: AuthorizeArgs\n ) {\n if (!this.opts.onAuthorize) return false;\n const result = this.opts.onAuthorize.call(\n { getIdentity: () => payload.data },\n ...args,\n );\n if (typeof result === 'function') {\n return result(payload.data);\n }\n return result;\n }\n\n protected override openapi(): OpenApiInjector {\n const primary = this.loaders[0]!;\n const scheme = {\n type: 'apiKey' as const,\n in: primary.type,\n name: primary.key,\n };\n\n return {\n ...super.openapi(),\n onDocument(document) {\n document.components ||= {};\n document.components.securitySchemes ||= {};\n document.components.securitySchemes['apiKey'] ||= scheme;\n },\n onMethod(methodItem) {\n methodItem.security ||= [];\n methodItem.security.push({ apiKey: [] });\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;AA8EA,IAAa,qBAAb,cAGU,SAMR;CAG+B;CAF/B;CAEA,YAAY,MAAuE;EACjF,MAAM;EADuB,KAAA,OAAA;EAE7B,KAAK,UAAU,KAAK,cAAc,CAAC;GAAE,MAAM;GAAU,KAAK;EAAY,CAAC;CACzE;;;;;;CAOA,UACE,WACA,WACQ;EACR,OAAO,WAAW,SAAS,CAAC,CACzB,OAAO,OAAO,aAAa,EAAE,CAAC,CAAC,CAC/B,OAAO,YAAY,EAAE,CAAC,CAAC,CACvB,OAAO,KAAK;CACjB;CAEA,QAAkB,KAAiB;EACjC,IAAI,SAAyB;EAC7B,KAAK,MAAM,EAAE,MAAM,SAAS,KAAK,SAAS;GACxC,QAAQ,MAAR;IACE,KAAK;KACH,SAAS,KAAK,eAAe,KAAK,GAAG;KACrC;IACF,KAAK;KACH,SAAS,KAAK,cAAc,KAAK,GAAG;KACpC;IACF,KAAK,UACH,SAAS,KAAK,eAAe,KAAK,GAAG;GAEzC;GACA,IAAI,QAAQ;EACd;EACA,OAAO;CACT;CAEA,eAAyB,KAAiB,KAA6B;EACrE,IAAI,CAAC,KAAK,OAAO;EACjB,MAAM,cAAc,IAAI,QAAQ,QAAQ,IAAI,YAAY;EACxD,IAAI,eAAe,MAAM,OAAO;EAChC,MAAM,MAAM,MAAM,QAAQ,WAAW,IAAI,YAAY,KAAK;EAC1D,IAAI,OAAO,QAAQ,UAAU,OAAO;EAEpC,OADe,IAAI,KACP,KAAK;CACnB;CAEA,cAAwB,KAAiB,KAA6B;EACpE,IAAI,CAAC,KAAK,OAAO;EACjB,MAAM,QAAQ,IAAI,QAAQ,MAAM;EAChC,IAAI,OAAO,UAAU,UAAU,OAAO;EAEtC,OADe,MAAM,KACT,KAAK;CACnB;CAEA,eAAyB,KAAiB,KAA6B;EACrE,IAAI,CAAC,KAAK,OAAO;EACjB,MAAM,QAAQ,IAAI,QAAQ,QAAQ;EAClC,IAAI,OAAO,UAAU,UAAU,OAAO;EAEtC,OADe,MAAM,KACT,KAAK;CACnB;CAEA,MAAgB,aACd,KAC6D;EAC7D,MAAM,EAAE,aAAa,KAAK;EAC1B,MAAM,SAAS,KAAK,QAAQ,GAAG;EAC/B,MAAM,OAAO,SAAS,MAAM,SAAS,QAAQ,GAAG,IAAI;EACpD,IAAI,gBAAgB,WAAW,MAAM;EACrC,OAAO,SAAS,SAAS,WAAW,QAAQ;GAAE,KAAK;GAAQ;EAAK,IAAI;CACtE;CAEA,UACE,SACA,GAAG,MACH;EACA,IAAI,CAAC,KAAK,KAAK,aAAa,OAAO;EACnC,MAAM,SAAS,KAAK,KAAK,YAAY,KACnC,EAAE,mBAAmB,QAAQ,KAAK,GAClC,GAAG,IACL;EACA,IAAI,OAAO,WAAW,YACpB,OAAO,OAAO,QAAQ,IAAI;EAE5B,OAAO;CACT;CAEA,UAA8C;EAC5C,MAAM,UAAU,KAAK,QAAQ;EAC7B,MAAM,SAAS;GACb,MAAM;GACN,IAAI,QAAQ;GACZ,MAAM,QAAQ;EAChB;EAEA,OAAO;GACL,GAAG,MAAM,QAAQ;GACjB,WAAW,UAAU;IACnB,SAAS,eAAe,CAAC;IACzB,SAAS,WAAW,oBAAoB,CAAC;IACzC,SAAS,WAAW,gBAAgB,cAAc;GACpD;GACA,SAAS,YAAY;IACnB,WAAW,aAAa,CAAC;IACzB,WAAW,SAAS,KAAK,EAAE,QAAQ,CAAC,EAAE,CAAC;GACzC;EACF;CACF;AACF"}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { n as AuthError, t as Strategy } from "../strategy-B0bAl8FM.js";
|
|
2
|
+
import { OpenApiInjector, WebContext } from "@aomex/web";
|
|
3
|
+
export type AuthBearerTokenLoaderItem = {
|
|
4
|
+
/**
|
|
5
|
+
* 从报文中寻找指定的值作为token
|
|
6
|
+
*/
|
|
7
|
+
type: 'header';
|
|
8
|
+
key: `authorization` | (string & {});
|
|
9
|
+
} | {
|
|
10
|
+
/**
|
|
11
|
+
* 从请求实体中寻找指定的值作为token
|
|
12
|
+
*/
|
|
13
|
+
type: 'body';
|
|
14
|
+
key: `access_token` | (string & {});
|
|
15
|
+
} | {
|
|
16
|
+
/**
|
|
17
|
+
* 从查询字符串中寻找指定的值作为token
|
|
18
|
+
*/
|
|
19
|
+
type: 'query';
|
|
20
|
+
key: `access_token` | (string & {});
|
|
21
|
+
} | {
|
|
22
|
+
/**
|
|
23
|
+
* 从cookie中寻找指定的值作为token
|
|
24
|
+
*/
|
|
25
|
+
type: 'cookie';
|
|
26
|
+
key: `access_token` | (string & {});
|
|
27
|
+
};
|
|
28
|
+
export declare abstract class AuthBaseBearerStrategy<T extends object | string | number, AuthorizeArgs extends any[]> extends Strategy<T, AuthorizeArgs> {
|
|
29
|
+
protected readonly loaders: AuthBearerTokenLoaderItem[];
|
|
30
|
+
constructor(loaders?: AuthBearerTokenLoaderItem[]);
|
|
31
|
+
protected loadToken(ctx: WebContext): string | false;
|
|
32
|
+
protected loadFromHeader(ctx: WebContext, key: string): string | false;
|
|
33
|
+
protected loadFromBody(ctx: WebContext, key: string): string | false;
|
|
34
|
+
protected loadFromQuery(ctx: WebContext, key: string): string | false;
|
|
35
|
+
protected loadFromCookie(ctx: WebContext, key: string): string | false;
|
|
36
|
+
}
|
|
37
|
+
export declare namespace AuthBearerStrategy {
|
|
38
|
+
type Options<T extends object | string | number, AuthorizeArgs extends any[]> = {
|
|
39
|
+
/**
|
|
40
|
+
* 找到token后的回调,解析并返回真正的身份数据
|
|
41
|
+
*/
|
|
42
|
+
onLoaded: (token: string, ctx: WebContext) => T | AuthError | false | Promise<T | AuthError | false>;
|
|
43
|
+
/**
|
|
44
|
+
* 按从左到右的顺序获取token。默认:`[{ type: 'header', key: 'authorization' }]`
|
|
45
|
+
*/
|
|
46
|
+
tokenLoaders?: AuthBearerTokenLoaderItem[];
|
|
47
|
+
} & ({
|
|
48
|
+
/**
|
|
49
|
+
* 身份认证后的权限判断,如果权限不足,则返回`false`,系统会自动响应`403`状态码
|
|
50
|
+
*
|
|
51
|
+
* 有两种方式可以获得认证的身份数据
|
|
52
|
+
* ```
|
|
53
|
+
* {
|
|
54
|
+
* onLoaded(token) {
|
|
55
|
+
* return { userId: 1, role: 1 };
|
|
56
|
+
* },
|
|
57
|
+
* // 方式一:
|
|
58
|
+
* onAuthorize(role: number) {
|
|
59
|
+
* const identity = this.getIdentity();
|
|
60
|
+
* return identity.role === role;
|
|
61
|
+
* },
|
|
62
|
+
* // 方式二:
|
|
63
|
+
* onAuthorize: (role: number) => (identity) => {
|
|
64
|
+
* return identity.role === role;
|
|
65
|
+
* }
|
|
66
|
+
* }
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
69
|
+
onAuthorize?: (...args: AuthorizeArgs) => boolean | Promise<boolean> | ((data: T) => boolean | AuthError | Promise<boolean | AuthError>);
|
|
70
|
+
} & ThisType<{
|
|
71
|
+
getIdentity: () => T;
|
|
72
|
+
}>);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* 从请求中获取token
|
|
76
|
+
*
|
|
77
|
+
* 解析优先级: 自定义 -> header -> body -> query -> cookie
|
|
78
|
+
*/
|
|
79
|
+
export declare class AuthBearerStrategy<T extends object | string | number, AuthorizeArgs extends any[]> extends AuthBaseBearerStrategy<{
|
|
80
|
+
readonly token: string;
|
|
81
|
+
readonly data: T;
|
|
82
|
+
}, AuthorizeArgs> {
|
|
83
|
+
protected readonly opts: AuthBearerStrategy.Options<T, AuthorizeArgs>;
|
|
84
|
+
constructor(opts: AuthBearerStrategy.Options<T, AuthorizeArgs>);
|
|
85
|
+
/**
|
|
86
|
+
* 生成token字符串(密码学安全随机熵 + 可选业务唯一键)
|
|
87
|
+
* @param algorithm 摘要算法
|
|
88
|
+
* @param uniqueKey 加入唯一的值(比如用户id,手机号)做域隔离
|
|
89
|
+
*/
|
|
90
|
+
signature(algorithm: 'md5' | 'sha1' | 'sha256' | 'sha512' | (string & {}), uniqueKey?: string | number): string;
|
|
91
|
+
protected authenticate(ctx: WebContext): Promise<{
|
|
92
|
+
readonly token: string;
|
|
93
|
+
readonly data: T;
|
|
94
|
+
} | false>;
|
|
95
|
+
protected authorize(payload: {
|
|
96
|
+
readonly token: string;
|
|
97
|
+
readonly data: T;
|
|
98
|
+
}, ...args: AuthorizeArgs): boolean | AuthError | Promise<boolean | AuthError>;
|
|
99
|
+
protected openapi(): OpenApiInjector;
|
|
100
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { n as Strategy, t as AuthError } from "../auth-error-BlqNQFwu.js";
|
|
2
|
+
import "@aomex/web";
|
|
3
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
4
|
+
// src/strategies/auth-bearer-strategy.ts
|
|
5
|
+
var AuthBaseBearerStrategy = class extends Strategy {
|
|
6
|
+
loaders;
|
|
7
|
+
constructor(loaders) {
|
|
8
|
+
super();
|
|
9
|
+
this.loaders = loaders || [{
|
|
10
|
+
type: "header",
|
|
11
|
+
key: "authorization"
|
|
12
|
+
}];
|
|
13
|
+
}
|
|
14
|
+
loadToken(ctx) {
|
|
15
|
+
let token = false;
|
|
16
|
+
for (const { type, key } of this.loaders) {
|
|
17
|
+
switch (type) {
|
|
18
|
+
case "header":
|
|
19
|
+
token = this.loadFromHeader(ctx, key);
|
|
20
|
+
break;
|
|
21
|
+
case "body":
|
|
22
|
+
token = this.loadFromBody(ctx, key);
|
|
23
|
+
break;
|
|
24
|
+
case "query":
|
|
25
|
+
token = this.loadFromQuery(ctx, key);
|
|
26
|
+
break;
|
|
27
|
+
case "cookie": token = this.loadFromCookie(ctx, key);
|
|
28
|
+
}
|
|
29
|
+
if (token) break;
|
|
30
|
+
}
|
|
31
|
+
return token;
|
|
32
|
+
}
|
|
33
|
+
loadFromHeader(ctx, key) {
|
|
34
|
+
const headerValue = ctx.request.headers[key];
|
|
35
|
+
if (!headerValue) return false;
|
|
36
|
+
const parts = String(headerValue).split(" ");
|
|
37
|
+
if (parts.length !== 2) return false;
|
|
38
|
+
if (parts[0].toLowerCase() === "bearer") return parts[1];
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
loadFromBody(ctx, key) {
|
|
42
|
+
if (!key) return false;
|
|
43
|
+
const body = ctx.request.body;
|
|
44
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) return false;
|
|
45
|
+
const token = Reflect.get(body, key);
|
|
46
|
+
return typeof token === "string" && token;
|
|
47
|
+
}
|
|
48
|
+
loadFromQuery(ctx, key) {
|
|
49
|
+
if (!key) return false;
|
|
50
|
+
const token = ctx.request.query[key];
|
|
51
|
+
return typeof token === "string" && token;
|
|
52
|
+
}
|
|
53
|
+
loadFromCookie(ctx, key) {
|
|
54
|
+
if (!key) return false;
|
|
55
|
+
const token = ctx.request.cookies[key];
|
|
56
|
+
return typeof token === "string" && token;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* 从请求中获取token
|
|
61
|
+
*
|
|
62
|
+
* 解析优先级: 自定义 -> header -> body -> query -> cookie
|
|
63
|
+
*/
|
|
64
|
+
var AuthBearerStrategy = class extends AuthBaseBearerStrategy {
|
|
65
|
+
opts;
|
|
66
|
+
constructor(opts) {
|
|
67
|
+
super(opts.tokenLoaders);
|
|
68
|
+
this.opts = opts;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* 生成token字符串(密码学安全随机熵 + 可选业务唯一键)
|
|
72
|
+
* @param algorithm 摘要算法
|
|
73
|
+
* @param uniqueKey 加入唯一的值(比如用户id,手机号)做域隔离
|
|
74
|
+
*/
|
|
75
|
+
signature(algorithm, uniqueKey) {
|
|
76
|
+
return createHash(algorithm).update(String(uniqueKey ?? "")).update(randomBytes(32)).digest("hex");
|
|
77
|
+
}
|
|
78
|
+
async authenticate(ctx) {
|
|
79
|
+
const { onLoaded } = this.opts;
|
|
80
|
+
const token = this.loadToken(ctx);
|
|
81
|
+
const data = token ? await onLoaded(token, ctx) : false;
|
|
82
|
+
if (data instanceof AuthError) throw data;
|
|
83
|
+
return data !== false && token !== false ? {
|
|
84
|
+
token,
|
|
85
|
+
data
|
|
86
|
+
} : false;
|
|
87
|
+
}
|
|
88
|
+
authorize(payload, ...args) {
|
|
89
|
+
if (!this.opts.onAuthorize) return false;
|
|
90
|
+
const result = this.opts.onAuthorize.call({ getIdentity: () => payload.data }, ...args);
|
|
91
|
+
if (typeof result === "function") return result(payload.data);
|
|
92
|
+
return result;
|
|
93
|
+
}
|
|
94
|
+
openapi() {
|
|
95
|
+
return {
|
|
96
|
+
...super.openapi(),
|
|
97
|
+
onDocument(document) {
|
|
98
|
+
document.components ||= {};
|
|
99
|
+
document.components.securitySchemes ||= {};
|
|
100
|
+
document.components.securitySchemes["bearerAuth"] ||= {
|
|
101
|
+
type: "http",
|
|
102
|
+
scheme: "bearer"
|
|
103
|
+
};
|
|
104
|
+
},
|
|
105
|
+
onMethod(methodItem) {
|
|
106
|
+
methodItem.security ||= [];
|
|
107
|
+
methodItem.security.push({ bearerAuth: [] });
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
export { AuthBaseBearerStrategy, AuthBearerStrategy };
|
|
113
|
+
|
|
114
|
+
//# sourceMappingURL=auth-bearer-strategy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth-bearer-strategy.js","names":[],"sources":["../../src/strategies/auth-bearer-strategy.ts"],"sourcesContent":["import { WebContext, type OpenApiInjector } from '@aomex/web';\nimport { createHash, randomBytes } from 'node:crypto';\nimport { AuthError } from '../auth-error';\nimport { Strategy } from '../strategy';\n\nexport type AuthBearerTokenLoaderItem =\n | {\n /**\n * 从报文中寻找指定的值作为token\n */\n type: 'header';\n key: `authorization` | (string & {});\n }\n | {\n /**\n * 从请求实体中寻找指定的值作为token\n */\n type: 'body';\n key: `access_token` | (string & {});\n }\n | {\n /**\n * 从查询字符串中寻找指定的值作为token\n */\n type: 'query';\n key: `access_token` | (string & {});\n }\n | {\n /**\n * 从cookie中寻找指定的值作为token\n */\n type: 'cookie';\n key: `access_token` | (string & {});\n };\n\nexport abstract class AuthBaseBearerStrategy<\n T extends object | string | number,\n AuthorizeArgs extends any[],\n> extends Strategy<T, AuthorizeArgs> {\n protected readonly loaders: AuthBearerTokenLoaderItem[];\n\n constructor(loaders?: AuthBearerTokenLoaderItem[]) {\n super();\n this.loaders = loaders || [{ type: 'header', key: 'authorization' }];\n }\n\n protected loadToken(ctx: WebContext) {\n let token: string | false = false;\n for (const { type, key } of this.loaders) {\n switch (type) {\n case 'header':\n token = this.loadFromHeader(ctx, key);\n break;\n case 'body':\n token = this.loadFromBody(ctx, key);\n break;\n case 'query':\n token = this.loadFromQuery(ctx, key);\n break;\n case 'cookie':\n token = this.loadFromCookie(ctx, key);\n break;\n }\n if (token) break;\n }\n return token;\n }\n\n protected loadFromHeader(ctx: WebContext, key: string): string | false {\n const headerValue = ctx.request.headers[key];\n if (!headerValue) return false;\n const parts = String(headerValue).split(' ');\n if (parts.length !== 2) return false;\n if (parts[0]!.toLowerCase() === 'bearer') {\n return parts[1]!;\n }\n return false;\n }\n\n protected loadFromBody(ctx: WebContext, key: string): string | false {\n if (!key) return false;\n const body = ctx.request.body;\n if (!body || typeof body !== 'object' || Array.isArray(body)) return false;\n const token = Reflect.get(body, key);\n return typeof token === 'string' && token;\n }\n\n protected loadFromQuery(ctx: WebContext, key: string): string | false {\n if (!key) return false;\n const token = ctx.request.query[key];\n return typeof token === 'string' && token;\n }\n\n protected loadFromCookie(ctx: WebContext, key: string): string | false {\n if (!key) return false;\n const token = ctx.request.cookies[key];\n return typeof token === 'string' && token;\n }\n}\n\nexport namespace AuthBearerStrategy {\n export type Options<T extends object | string | number, AuthorizeArgs extends any[]> = {\n /**\n * 找到token后的回调,解析并返回真正的身份数据\n */\n onLoaded: (\n token: string,\n ctx: WebContext,\n ) => T | AuthError | false | Promise<T | AuthError | false>;\n\n /**\n * 按从左到右的顺序获取token。默认:`[{ type: 'header', key: 'authorization' }]`\n */\n tokenLoaders?: AuthBearerTokenLoaderItem[];\n } & ({\n /**\n * 身份认证后的权限判断,如果权限不足,则返回`false`,系统会自动响应`403`状态码\n *\n * 有两种方式可以获得认证的身份数据\n * ```\n * {\n * onLoaded(token) {\n * return { userId: 1, role: 1 };\n * },\n * // 方式一:\n * onAuthorize(role: number) {\n * const identity = this.getIdentity();\n * return identity.role === role;\n * },\n * // 方式二:\n * onAuthorize: (role: number) => (identity) => {\n * return identity.role === role;\n * }\n * }\n * ```\n */\n onAuthorize?: (\n ...args: AuthorizeArgs\n ) =>\n | boolean\n | Promise<boolean>\n | ((data: T) => boolean | AuthError | Promise<boolean | AuthError>);\n } & ThisType<{ getIdentity: () => T }>);\n}\n\n/**\n * 从请求中获取token\n *\n * 解析优先级: 自定义 -> header -> body -> query -> cookie\n */\nexport class AuthBearerStrategy<\n T extends object | string | number,\n AuthorizeArgs extends any[],\n> extends AuthBaseBearerStrategy<\n {\n readonly token: string;\n readonly data: T;\n },\n AuthorizeArgs\n> {\n constructor(protected readonly opts: AuthBearerStrategy.Options<T, AuthorizeArgs>) {\n super(opts.tokenLoaders);\n }\n\n /**\n * 生成token字符串(密码学安全随机熵 + 可选业务唯一键)\n * @param algorithm 摘要算法\n * @param uniqueKey 加入唯一的值(比如用户id,手机号)做域隔离\n */\n signature(\n algorithm: 'md5' | 'sha1' | 'sha256' | 'sha512' | (string & {}),\n uniqueKey?: string | number,\n ): string {\n return createHash(algorithm)\n .update(String(uniqueKey ?? ''))\n .update(randomBytes(32))\n .digest('hex');\n }\n\n protected async authenticate(\n ctx: WebContext,\n ): Promise<{ readonly token: string; readonly data: T } | false> {\n const { onLoaded } = this.opts;\n const token = this.loadToken(ctx);\n const data = token ? await onLoaded(token, ctx) : false;\n if (data instanceof AuthError) throw data;\n return data !== false && token !== false ? { token, data } : false;\n }\n\n protected override authorize(\n payload: { readonly token: string; readonly data: T },\n ...args: AuthorizeArgs\n ) {\n if (!this.opts.onAuthorize) return false;\n const result = this.opts.onAuthorize.call(\n { getIdentity: () => payload.data },\n ...args,\n );\n if (typeof result === 'function') {\n return result(payload.data);\n }\n return result;\n }\n\n protected override openapi(): OpenApiInjector {\n return {\n ...super.openapi(),\n onDocument(document) {\n document.components ||= {};\n document.components.securitySchemes ||= {};\n document.components.securitySchemes['bearerAuth'] ||= {\n type: 'http',\n scheme: 'bearer',\n };\n },\n onMethod(methodItem) {\n methodItem.security ||= [];\n methodItem.security.push({ bearerAuth: [] });\n },\n };\n }\n}\n"],"mappings":"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"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { OpenApiInjector, WebContext } from "@aomex/web";
|
|
2
|
+
declare class AuthError extends Error {}
|
|
3
|
+
declare abstract class Strategy<Payload extends object | string | number, AuthorizeArgs extends any[] = any[]> {
|
|
4
|
+
protected abstract authenticate(ctx: WebContext): Payload | false | AuthError | Promise<Payload | false | AuthError>;
|
|
5
|
+
protected abstract authorize(payload: Payload, ...args: AuthorizeArgs): boolean | AuthError | Promise<boolean | AuthError>;
|
|
6
|
+
protected openapi(): OpenApiInjector;
|
|
7
|
+
}
|
|
8
|
+
export { AuthError as n, Strategy as t };
|
package/package.json
CHANGED
|
@@ -1,17 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aomex/auth",
|
|
3
|
-
"version": "3.30.
|
|
3
|
+
"version": "3.30.8-alpha.62.sha-92b25bb",
|
|
4
4
|
"description": "身份认证统一入口",
|
|
5
|
+
"scripts": {
|
|
6
|
+
"prepublishOnly": "tsdown"
|
|
7
|
+
},
|
|
5
8
|
"type": "module",
|
|
6
|
-
"types": "
|
|
9
|
+
"types": "src/index.ts",
|
|
7
10
|
"exports": {
|
|
8
|
-
".":
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
},
|
|
11
|
+
".": "./src/index.ts",
|
|
12
|
+
"./bearer": "./src/strategies/auth-bearer-strategy.ts",
|
|
13
|
+
"./api-key": "./src/strategies/auth-api-key-strategy.ts",
|
|
12
14
|
"./package.json": "./package.json"
|
|
13
15
|
},
|
|
14
16
|
"publishConfig": {
|
|
17
|
+
"types": "dist/index.d.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"import": "./dist/index.js"
|
|
22
|
+
},
|
|
23
|
+
"./bearer": {
|
|
24
|
+
"types": "./dist/strategies/auth-bearer-strategy.d.ts",
|
|
25
|
+
"import": "./dist/strategies/auth-bearer-strategy.js"
|
|
26
|
+
},
|
|
27
|
+
"./api-key": {
|
|
28
|
+
"types": "./dist/strategies/auth-api-key-strategy.d.ts",
|
|
29
|
+
"import": "./dist/strategies/auth-api-key-strategy.js"
|
|
30
|
+
},
|
|
31
|
+
"./package.json": "./package.json"
|
|
32
|
+
},
|
|
15
33
|
"access": "public"
|
|
16
34
|
},
|
|
17
35
|
"files": [
|
|
@@ -21,19 +39,16 @@
|
|
|
21
39
|
"README.md",
|
|
22
40
|
"CHANGELOG.md"
|
|
23
41
|
],
|
|
24
|
-
"repository":
|
|
25
|
-
"type": "git",
|
|
26
|
-
"url": "git@github.com:aomex/aomex.git"
|
|
27
|
-
},
|
|
42
|
+
"repository": "git@github.com:aomex/aomex.git",
|
|
28
43
|
"homepage": "https://aomex.js.org",
|
|
29
44
|
"license": "MIT",
|
|
30
45
|
"peerDependencies": {
|
|
31
|
-
"@aomex/common": "^
|
|
32
|
-
"@aomex/web": "^
|
|
46
|
+
"@aomex/common": "^4.0.0",
|
|
47
|
+
"@aomex/web": "^4.0.0"
|
|
33
48
|
},
|
|
34
49
|
"devDependencies": {
|
|
35
|
-
"@aomex/common": "3.30.
|
|
36
|
-
"@aomex/web": "3.30.
|
|
50
|
+
"@aomex/common": "3.30.8-alpha.62.sha-92b25bb",
|
|
51
|
+
"@aomex/web": "3.30.8-alpha.62.sha-92b25bb"
|
|
37
52
|
},
|
|
38
|
-
"
|
|
39
|
-
}
|
|
53
|
+
"gitHead": "92b25bbcd6c3ae28160316117a74c88619b5bc8d"
|
|
54
|
+
}
|