kauth-sdk-node 0.1.24

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 (45) hide show
  1. package/CHANGELOG.md +280 -0
  2. package/README.md +58 -0
  3. package/dist/authenticator/authenticator.d.ts +29 -0
  4. package/dist/authenticator/authenticator.js +90 -0
  5. package/dist/authenticator/base.d.ts +16 -0
  6. package/dist/authenticator/base.js +6 -0
  7. package/dist/authenticator/google.d.ts +21 -0
  8. package/dist/authenticator/google.js +12 -0
  9. package/dist/authenticator/index.d.ts +3 -0
  10. package/dist/authenticator/index.js +11 -0
  11. package/dist/authenticator/manager.d.ts +38 -0
  12. package/dist/authenticator/manager.js +165 -0
  13. package/dist/authenticator/miniprogram.d.ts +15 -0
  14. package/dist/authenticator/miniprogram.js +12 -0
  15. package/dist/authenticator/mozi.d.ts +21 -0
  16. package/dist/authenticator/mozi.js +12 -0
  17. package/dist/authenticator/provider.d.ts +28 -0
  18. package/dist/authenticator/provider.js +76 -0
  19. package/dist/authorizer/index.d.ts +1 -0
  20. package/dist/authorizer/index.js +4 -0
  21. package/dist/authorizer/permission.d.ts +9 -0
  22. package/dist/authorizer/permission.js +53 -0
  23. package/dist/common/config/config.d.ts +37 -0
  24. package/dist/common/config/config.js +2 -0
  25. package/dist/common/constant/http.d.ts +42 -0
  26. package/dist/common/constant/http.js +47 -0
  27. package/dist/common/http/kauth.d.ts +50 -0
  28. package/dist/common/http/kauth.js +177 -0
  29. package/dist/common/http/kflow.d.ts +12 -0
  30. package/dist/common/http/kflow.js +36 -0
  31. package/dist/common/http/request/kauth.d.ts +89 -0
  32. package/dist/common/http/request/kauth.js +2 -0
  33. package/dist/common/http/request/kflow.d.ts +16 -0
  34. package/dist/common/http/request/kflow.js +2 -0
  35. package/dist/common/http/response/kauth.d.ts +86 -0
  36. package/dist/common/http/response/kauth.js +8 -0
  37. package/dist/common/http/response/kflow.d.ts +33 -0
  38. package/dist/common/http/response/kflow.js +2 -0
  39. package/dist/common/http/tool/marmot.d.ts +48 -0
  40. package/dist/common/http/tool/marmot.js +97 -0
  41. package/dist/common/util/converter/permission.d.ts +12 -0
  42. package/dist/common/util/converter/permission.js +36 -0
  43. package/dist/index.d.ts +9 -0
  44. package/dist/index.js +29 -0
  45. package/package.json +84 -0
@@ -0,0 +1,177 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.KauthApi = void 0;
7
+ const marmot_1 = require("./tool/marmot");
8
+ const http_1 = require("../constant/http");
9
+ const lru_cache_1 = __importDefault(require("lru-cache"));
10
+ let cache;
11
+ class KauthApi {
12
+ constructor({ kauthOrigin, marmotTenantId, marmotAccessKeyId, marmotAccessKeySecret, kauthServiceName, kauthServicePort, lruMaxAge = 10000, lruMax = 100, }) {
13
+ this.marmotUtil = new marmot_1.MarmotUtil(kauthOrigin, marmotTenantId, marmotAccessKeyId, marmotAccessKeySecret, kauthServiceName, kauthServicePort);
14
+ if (cache) {
15
+ this.cache = cache;
16
+ }
17
+ else {
18
+ this.cache = cache = new lru_cache_1.default({
19
+ max: lruMax,
20
+ maxAge: lruMaxAge,
21
+ });
22
+ }
23
+ }
24
+ async moziAuthorizeURL(callback, state, prompt) {
25
+ return this.marmotUtil.get(http_1.MoziAuthorizeUri, { callback, state, prompt });
26
+ }
27
+ async moziAuthenticate(data) {
28
+ return this.marmotUtil.post(http_1.MoziAuthenticateUri, data);
29
+ }
30
+ async moziBind(data) {
31
+ return this.marmotUtil.post(http_1.MoziBindUri + data.user_id, data);
32
+ }
33
+ async getMoziAuthenticationInformation(id) {
34
+ return this.marmotUtil.get(http_1.MoziAuthenticationInformationUri, { id });
35
+ }
36
+ async googleAuthorizeURL(callback, state, prompt) {
37
+ return this.marmotUtil.get(http_1.GoogleAuthorizeUri, { callback, state, prompt });
38
+ }
39
+ async googleAuthenticate(data) {
40
+ return this.marmotUtil.post(http_1.GoogleAuthenticateUri, data);
41
+ }
42
+ async googleBind(data) {
43
+ return this.marmotUtil.post(http_1.GoogleBindUri + data.user_id, data);
44
+ }
45
+ async getGoogleAuthenticationInformation(id) {
46
+ return this.marmotUtil.get(http_1.GoogleAuthenticationInformationUri, { id });
47
+ }
48
+ async miniprogramAuthorizeURL(callback, state, prompt) {
49
+ return this.marmotUtil.get(http_1.MiniprogramAuthorizeUri, { callback, state, prompt });
50
+ }
51
+ async miniprogramAuthenticate(data) {
52
+ return this.marmotUtil.post(http_1.MiniprogramAuthenticateUri, data);
53
+ }
54
+ async miniprogramBind(data) {
55
+ return this.marmotUtil.post(http_1.MiniprogramBindUri + data.user_id, data);
56
+ }
57
+ async getMiniprogramAuthenticationInformation(id) {
58
+ return this.marmotUtil.get(http_1.MiniprogramAuthenticationInformationUri, { id });
59
+ }
60
+ async getUserById(id) {
61
+ return this.marmotUtil.get(http_1.GetUserByIdUri, { id });
62
+ }
63
+ async listUsers() {
64
+ return this.marmotUtil.get(http_1.ListUsersUri);
65
+ }
66
+ async listUsersWithUserAccountsAndRoles() {
67
+ return this.marmotUtil.get(http_1.ListUsersWithUserAccountsAndRolesUri);
68
+ }
69
+ async listUsersWithUserAccountsAndRolesByRoleExtendValue(roleExtendValue) {
70
+ return this.marmotUtil.get(http_1.ListUsersWithUserAccountsAndRolesByRoleExtendValueUri, { roleExtendValue });
71
+ }
72
+ async listUsersByRoleId(roleId) {
73
+ return this.marmotUtil.get(http_1.ListUsersByRoleIdUri, { roleId });
74
+ }
75
+ async listUsersByRoleNameAndExtendValue(roleName, roleExtendValue) {
76
+ return this.marmotUtil.get(http_1.ListUsersByRoleNameAndExtendValueUri, {
77
+ roleName,
78
+ roleExtendValue,
79
+ });
80
+ }
81
+ async listUsersByPermissionId(permissionId) {
82
+ return this.marmotUtil.get(http_1.ListUsersByPermissionIdUri, { permissionId });
83
+ }
84
+ async listUsersByPermissionNameAndExtendValue(permissionName, permissionExtendValue) {
85
+ return this.marmotUtil.get(http_1.ListUsersByPermissionNameAndExtendValueUri, {
86
+ permissionName,
87
+ permissionExtendValue,
88
+ });
89
+ }
90
+ async listPermissions() {
91
+ return this.marmotUtil.get(http_1.ListPermissionsUri);
92
+ }
93
+ async createPermission(data) {
94
+ return this.marmotUtil.post(http_1.CreatePermissionUri, data);
95
+ }
96
+ async getRoleWithUsers(name, extendValue) {
97
+ return this.marmotUtil.get(http_1.GetRoleWithUsersUri, {
98
+ name,
99
+ extendValue,
100
+ });
101
+ }
102
+ async listRoles() {
103
+ return this.marmotUtil.get(http_1.ListRolesUri);
104
+ }
105
+ async listRolesByExtendValue(extendValue) {
106
+ return this.marmotUtil.get(http_1.ListRolesByExtendValueUri, { extendValue });
107
+ }
108
+ async listRolesByUserId(id) {
109
+ return this.marmotUtil.get(http_1.ListRolesByUserIdUri, { id });
110
+ }
111
+ async listRolesByNamesAndExtendValue(names, extendValue) {
112
+ const namesStr = names.join(',');
113
+ return this.marmotUtil.get(http_1.ListRolesByNamesAndExtendValueUri, { names: namesStr, extendValue });
114
+ }
115
+ async createRole(data) {
116
+ return this.marmotUtil.post(http_1.CreateRoleUri, data);
117
+ }
118
+ async unbind(userAccountId) {
119
+ return this.marmotUtil.post(http_1.UnbindUri + userAccountId);
120
+ }
121
+ /**
122
+ * cache with user and permission
123
+ * @param id
124
+ */
125
+ async listPermissionsByUserId(id) {
126
+ const permissions = this.cache.get(id);
127
+ if (permissions) {
128
+ return permissions;
129
+ }
130
+ const refreshedPermissions = await this.marmotUtil.get(http_1.ListPermissionsByUserIdUri, { id });
131
+ this.cache.set(id, refreshedPermissions);
132
+ return refreshedPermissions;
133
+ }
134
+ async createRolesByUsersAndPermissions(data) {
135
+ const result = await this.marmotUtil.post(http_1.CreateRolesByUsersAndPermissionsUri, data);
136
+ data.roles.forEach((role) => {
137
+ if (role.users) {
138
+ role.users.forEach((user) => {
139
+ this.cache.del(user.id);
140
+ });
141
+ }
142
+ });
143
+ return result;
144
+ }
145
+ async updateRolesWithPermissions(data) {
146
+ return this.marmotUtil.post(http_1.UpdateRolesWithPermissionsUri, data);
147
+ }
148
+ async bindUserByRoles(data) {
149
+ await this.marmotUtil.post(http_1.BindUserByRolesUri, data);
150
+ this.cache.del(data.id);
151
+ }
152
+ async bindUserByRolesInRoleNamesAndExtendValue(data) {
153
+ await this.marmotUtil.post(http_1.BindUserByRoleNamesAndExtendValueUri, data);
154
+ this.cache.del(data.id);
155
+ }
156
+ async bindUserByRolesAndExtendValue(data) {
157
+ await this.marmotUtil.post(http_1.BindUserByRolesAndExtendValueUri, data);
158
+ this.cache.del(data.id);
159
+ }
160
+ async bindUsersByRoleNameAndExtendValue(data) {
161
+ await this.marmotUtil.post(http_1.BindUsersByRoleNameAndExtendValueUri, data);
162
+ data.users.forEach((user) => {
163
+ this.cache.del(user.id);
164
+ });
165
+ }
166
+ async bindRoleByPermissions(data) {
167
+ await this.marmotUtil.post(http_1.BindRoleByPermissionsUri, data);
168
+ this.cache.del(data.id);
169
+ }
170
+ async bindRoleWithUsers(data) {
171
+ await this.marmotUtil.post(http_1.BindRoleWithUsersUri, data);
172
+ data.users.forEach((user) => {
173
+ this.cache.del(user.id);
174
+ });
175
+ }
176
+ }
177
+ exports.KauthApi = KauthApi;
@@ -0,0 +1,12 @@
1
+ import { KauthConfig } from '../config/config';
2
+ import { KflowCreateProcessRequest, KflowCompleteTaskServiceRequest, KflowGetProcinstUserRequest } from './request/kflow';
3
+ import { KflowStateMachineAndNodes } from './response/kflow';
4
+ export declare class KflowApi {
5
+ private marmotUtil;
6
+ constructor({ kflowOrigin, marmotTenantId, marmotAccessKeyId, marmotAccessKeySecret, kflowServiceName, kflowServicePort, }: KauthConfig);
7
+ startProcessInstanceByKey(body: KflowCreateProcessRequest): Promise<string>;
8
+ completeTaskService(userId: string | number, body: KflowCompleteTaskServiceRequest): Promise<void>;
9
+ deleteProcessInstance(userId: string | number, instanceId: string, reason: string): Promise<void>;
10
+ getStateMachineAndNodes(userId: string | number, instanceId: string): Promise<KflowStateMachineAndNodes>;
11
+ getProcinstUsers(body: KflowGetProcinstUserRequest): Promise<unknown>;
12
+ }
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.KflowApi = void 0;
4
+ const marmot_1 = require("./tool/marmot");
5
+ const http_1 = require("../constant/http");
6
+ class KflowApi {
7
+ constructor({ kflowOrigin, marmotTenantId, marmotAccessKeyId, marmotAccessKeySecret, kflowServiceName, kflowServicePort, }) {
8
+ this.marmotUtil = new marmot_1.MarmotUtil(kflowOrigin, marmotTenantId, marmotAccessKeyId, marmotAccessKeySecret, kflowServiceName, kflowServicePort);
9
+ }
10
+ async startProcessInstanceByKey(body) {
11
+ return this.marmotUtil.post(http_1.ProcessUri, body);
12
+ }
13
+ async completeTaskService(userId, body) {
14
+ return this.marmotUtil.post(http_1.ServiceTaskUri, {
15
+ userId: Number(userId),
16
+ ...body,
17
+ });
18
+ }
19
+ async deleteProcessInstance(userId, instanceId, reason) {
20
+ const params = {
21
+ userId: Number(userId),
22
+ instanceId,
23
+ reason,
24
+ };
25
+ return this.marmotUtil.del(http_1.ProcessUri, params);
26
+ }
27
+ async getStateMachineAndNodes(userId, instanceId) {
28
+ return this.marmotUtil.get(http_1.InstanceUri + instanceId, {
29
+ userId: Number(userId),
30
+ });
31
+ }
32
+ async getProcinstUsers(body) {
33
+ return this.marmotUtil.get(http_1.GetProcinstUserUri, body);
34
+ }
35
+ }
36
+ exports.KflowApi = KflowApi;
@@ -0,0 +1,89 @@
1
+ /// <reference types="node" />
2
+ import { ParsedUrlQueryInput } from 'querystring';
3
+ import { MarmotOptions } from '../tool/marmot';
4
+ export interface KauthAuthenticateRequest extends ParsedUrlQueryInput, MarmotOptions {
5
+ code: string;
6
+ redirect_uri: string;
7
+ }
8
+ export interface KauthBindRequest extends ParsedUrlQueryInput, MarmotOptions {
9
+ user_id: number;
10
+ code: string;
11
+ redirect_uri: string;
12
+ }
13
+ export interface KauthCreatePermissionRequest extends MarmotOptions {
14
+ name: string;
15
+ type: number;
16
+ extend_value: string;
17
+ }
18
+ export interface KauthCreateRoleRequest extends MarmotOptions {
19
+ name: string;
20
+ extend_value: string;
21
+ }
22
+ export interface KauthCreateRolesByPermissionsAndUsersRequest extends MarmotOptions {
23
+ roles: Array<{
24
+ name: string;
25
+ extend_value: string;
26
+ permissions: Array<{
27
+ name: string;
28
+ type?: number;
29
+ extend_value: string;
30
+ }>;
31
+ users?: Array<{
32
+ id: number;
33
+ }>;
34
+ }>;
35
+ }
36
+ export interface KauthBindUserByRolesRequest extends MarmotOptions {
37
+ id: number;
38
+ roles: Array<{
39
+ id: number;
40
+ }>;
41
+ }
42
+ export interface KauthBindUserByRoleNamesAndExtendValueRequest extends MarmotOptions {
43
+ id: number;
44
+ roles: Array<{
45
+ id: number;
46
+ }>;
47
+ range: {
48
+ role_names: string[];
49
+ role_extend_value: string;
50
+ };
51
+ }
52
+ export interface KauthBindUserByRolesAndExtendValueRequest extends MarmotOptions {
53
+ id: number;
54
+ status?: number;
55
+ roles: Array<{
56
+ id: number;
57
+ }>;
58
+ role_extend_value: string;
59
+ }
60
+ export interface KauthBindUsersByRoleNameAndExtendValueRequest extends MarmotOptions {
61
+ users: Array<{
62
+ id: number;
63
+ }>;
64
+ role_name: string;
65
+ role_extend_value: string;
66
+ }
67
+ export interface KauthBindRoleByPermissionsRequest extends MarmotOptions {
68
+ id: number;
69
+ permissions: Array<{
70
+ id: number;
71
+ }>;
72
+ }
73
+ export interface KauthUpdateRolesWithPermissionsRequest extends MarmotOptions {
74
+ roles: Array<{
75
+ name: string;
76
+ extend_value: string;
77
+ permissions: Array<{
78
+ name: string;
79
+ type?: number;
80
+ extend_value: string;
81
+ }>;
82
+ }>;
83
+ }
84
+ export interface KauthBindRoleWithUsersRequest extends MarmotOptions {
85
+ id: number;
86
+ users: Array<{
87
+ id: number;
88
+ }>;
89
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,16 @@
1
+ import { MarmotOptions } from '../tool/marmot';
2
+ export interface KflowCreateProcessRequest extends MarmotOptions {
3
+ key: string;
4
+ map: any;
5
+ }
6
+ export interface KflowCompleteTaskServiceRequest extends MarmotOptions {
7
+ instanceId: string;
8
+ assignee?: string;
9
+ candidateGroup?: string;
10
+ map: Object;
11
+ }
12
+ export declare type ProcinstUserActionType = 'startProcessInstance' | 'nextApprovers' | 'completeTaskService';
13
+ export interface KflowGetProcinstUserRequest extends MarmotOptions {
14
+ action: ProcinstUserActionType;
15
+ instanceId?: string;
16
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,86 @@
1
+ import { PrimaryPrincipal } from '../../../authenticator/base';
2
+ export declare enum KauthPrincipalStatus {
3
+ Normal = 0,
4
+ Locked = 1
5
+ }
6
+ export interface KauthPrimaryPrincipal {
7
+ id: number;
8
+ name: string;
9
+ email: string;
10
+ avatar: string;
11
+ status: KauthPrincipalStatus;
12
+ }
13
+ export interface KauthMoziPrincipal {
14
+ account: string;
15
+ employeeCode: string;
16
+ lastName: string;
17
+ namespace: string;
18
+ nickNameCn: string;
19
+ openid: string;
20
+ realmId: number;
21
+ realmName: string;
22
+ }
23
+ export interface KauthMoziCredential {
24
+ accessToken: string;
25
+ expiresIn: number;
26
+ refreshToken: string;
27
+ }
28
+ export interface KauthMoziAuthenticationInformation {
29
+ primaryPrincipal: KauthPrimaryPrincipal;
30
+ principal: KauthMoziPrincipal;
31
+ credential: KauthMoziCredential;
32
+ }
33
+ export interface KauthGooglePrincipal {
34
+ sub: string;
35
+ name: string;
36
+ givenName: string;
37
+ familyName: string;
38
+ picture: string;
39
+ email: string;
40
+ emailVerified: boolean;
41
+ locale: string;
42
+ }
43
+ export interface KauthGoogleCredential {
44
+ accessToken: string;
45
+ expiresIn: number;
46
+ refreshToken: string;
47
+ }
48
+ export interface KauthGoogleAuthenticationInformation {
49
+ primaryPrincipal: KauthPrimaryPrincipal;
50
+ principal: KauthGooglePrincipal;
51
+ credential: KauthGoogleCredential;
52
+ }
53
+ export interface KauthMiniprogramPrincipal {
54
+ trustLoginId: string;
55
+ customerId: string;
56
+ email: string;
57
+ nickName: string;
58
+ }
59
+ export interface KauthMiniprogramCredential {
60
+ accessToken: string;
61
+ }
62
+ export interface KauthMiniprogramAuthenticationInformation {
63
+ primaryPrincipal: PrimaryPrincipal;
64
+ principal: KauthMiniprogramPrincipal;
65
+ credential: KauthMiniprogramCredential;
66
+ }
67
+ export interface KauthPermission {
68
+ id: number;
69
+ name: string;
70
+ type: number;
71
+ extendValue: string;
72
+ }
73
+ export interface KauthRole {
74
+ id: number;
75
+ name: string;
76
+ extendValue: string;
77
+ }
78
+ export interface KauthUser {
79
+ id: number;
80
+ name: string;
81
+ avatar: string;
82
+ email: string;
83
+ status: number;
84
+ roles?: any[];
85
+ accounts?: any[];
86
+ }
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.KauthPrincipalStatus = void 0;
4
+ var KauthPrincipalStatus;
5
+ (function (KauthPrincipalStatus) {
6
+ KauthPrincipalStatus[KauthPrincipalStatus["Normal"] = 0] = "Normal";
7
+ KauthPrincipalStatus[KauthPrincipalStatus["Locked"] = 1] = "Locked";
8
+ })(KauthPrincipalStatus = exports.KauthPrincipalStatus || (exports.KauthPrincipalStatus = {}));
@@ -0,0 +1,33 @@
1
+ export interface InternalState {
2
+ index: number;
3
+ action: {
4
+ [name: string]: string;
5
+ };
6
+ jump: string;
7
+ meta: {
8
+ title: string;
9
+ candidateGroup: string;
10
+ };
11
+ view: {
12
+ timestamp: number;
13
+ userId: number;
14
+ userName: string;
15
+ candidateGroup: string;
16
+ candidateUserNames: string[];
17
+ };
18
+ }
19
+ export interface HierarchyState extends InternalState {
20
+ children: StateMachine;
21
+ }
22
+ export interface StateMachine {
23
+ [key: string]: HierarchyState;
24
+ }
25
+ export interface StateMachineNode {
26
+ index: number;
27
+ key: string;
28
+ value: InternalState;
29
+ }
30
+ export interface KflowStateMachineAndNodes {
31
+ stateMachine: StateMachine;
32
+ nodes: StateMachineNode[];
33
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,48 @@
1
+ /// <reference types="node" />
2
+ import { AxiosRequestConfig, AxiosResponse } from 'axios';
3
+ import { ParsedUrlQueryInput } from 'querystring';
4
+ declare enum BasicStatus {
5
+ OK = 0,
6
+ UnAuthenticated = 10401,
7
+ Forbidden = 10403,
8
+ InternalServerError = 10500
9
+ }
10
+ interface BasicReponse<T> {
11
+ status: BasicStatus;
12
+ body: T;
13
+ message: string;
14
+ }
15
+ export interface MarmotOptions {
16
+ userId?: number;
17
+ timestamp?: number;
18
+ }
19
+ export declare class MarmotUtil {
20
+ private origin;
21
+ private tenantId?;
22
+ private accessKeyId?;
23
+ private accessKeySecret?;
24
+ private serviceName?;
25
+ private servicePort?;
26
+ private proxyMatched;
27
+ constructor(origin: string, tenantId?: number, accessKeyId?: string, accessKeySecret?: string, serviceName?: string, servicePort?: string);
28
+ get<RequestType extends ParsedUrlQueryInput | MarmotOptions, ResponseType>(path: string, params?: RequestType): Promise<ResponseType>;
29
+ post<RequestType extends MarmotOptions, ResponseType>(path: string, params?: RequestType, config?: AxiosRequestConfig): Promise<ResponseType>;
30
+ del<RequestType extends MarmotOptions | ParsedUrlQueryInput, ResponseType>(path: string, params?: RequestType): Promise<ResponseType>;
31
+ resolveUri(path: string, params?: any): string;
32
+ resolveHeaders(method: string, uri: string, userId?: number): {
33
+ 'x-service-name': string;
34
+ 'x-service-port': string;
35
+ 'x-kauth-user-id': number;
36
+ authorization: string;
37
+ 'x-gw-tenant-id'?: undefined;
38
+ } | {
39
+ 'x-kauth-user-id': number;
40
+ 'x-gw-tenant-id': number;
41
+ 'x-service-name'?: undefined;
42
+ 'x-service-port'?: undefined;
43
+ authorization?: undefined;
44
+ };
45
+ sign(method: string, path: string, accessKeySecret?: string): string;
46
+ format<T>(response: AxiosResponse<BasicReponse<any>>): Promise<T>;
47
+ }
48
+ export {};
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.MarmotUtil = void 0;
7
+ const axios_1 = __importDefault(require("axios"));
8
+ const camelcase_keys_1 = __importDefault(require("camelcase-keys"));
9
+ const querystring_1 = __importDefault(require("querystring"));
10
+ const crypto_1 = __importDefault(require("crypto"));
11
+ const path_1 = __importDefault(require("path"));
12
+ // todo https://yuque.antfin.com/marmot/marmot/openapi
13
+ var BasicStatus;
14
+ (function (BasicStatus) {
15
+ BasicStatus[BasicStatus["OK"] = 0] = "OK";
16
+ BasicStatus[BasicStatus["UnAuthenticated"] = 10401] = "UnAuthenticated";
17
+ BasicStatus[BasicStatus["Forbidden"] = 10403] = "Forbidden";
18
+ BasicStatus[BasicStatus["InternalServerError"] = 10500] = "InternalServerError";
19
+ })(BasicStatus || (BasicStatus = {}));
20
+ class MarmotUtil {
21
+ constructor(origin, tenantId, accessKeyId, accessKeySecret, serviceName, servicePort) {
22
+ this.origin = origin.replace(/\/+$/, '');
23
+ this.tenantId = tenantId;
24
+ this.accessKeyId = accessKeyId;
25
+ this.accessKeySecret = accessKeySecret;
26
+ this.serviceName = serviceName;
27
+ this.servicePort = servicePort;
28
+ this.proxyMatched = Boolean(accessKeyId && accessKeySecret && serviceName && servicePort);
29
+ }
30
+ async get(path, params) {
31
+ const { userId, ...data } = params || {};
32
+ const uri = this.resolveUri(path, data);
33
+ const response = await axios_1.default.get(this.origin + uri, {
34
+ headers: this.resolveHeaders('GET', uri, userId),
35
+ });
36
+ return this.format(response);
37
+ }
38
+ async post(path, params, config) {
39
+ const { userId, ...data } = params || {};
40
+ const uri = this.resolveUri(path);
41
+ const response = await axios_1.default.post(this.origin + uri, data, {
42
+ ...config,
43
+ headers: this.resolveHeaders('POST', uri, userId),
44
+ });
45
+ return this.format(response);
46
+ }
47
+ async del(path, params) {
48
+ const { userId, ...data } = params || {};
49
+ const uri = this.resolveUri(path, data);
50
+ const response = await axios_1.default.delete(this.origin + uri, {
51
+ headers: this.resolveHeaders('DELETE', uri, userId),
52
+ });
53
+ return this.format(response);
54
+ }
55
+ resolveUri(path, params = {}) {
56
+ if (path.startsWith('.')) {
57
+ throw new Error('path cannot start with .');
58
+ }
59
+ if (this.proxyMatched) {
60
+ params.timestamp = Date.now();
61
+ return `${path_1.default.resolve('/gw/' + path)}?${querystring_1.default.stringify(params)}`;
62
+ }
63
+ return `${path_1.default.normalize(path)}?${querystring_1.default.stringify(params)}`;
64
+ }
65
+ resolveHeaders(method, uri, userId) {
66
+ if (this.proxyMatched) {
67
+ const signature = this.sign(method.toUpperCase(), uri, this.accessKeySecret);
68
+ return {
69
+ 'x-service-name': this.serviceName,
70
+ 'x-service-port': this.servicePort,
71
+ 'x-kauth-user-id': userId,
72
+ authorization: `Marmot ${this.accessKeyId}:${signature}`,
73
+ };
74
+ }
75
+ return {
76
+ 'x-kauth-user-id': userId,
77
+ 'x-gw-tenant-id': this.tenantId || 0,
78
+ };
79
+ }
80
+ sign(method, path, accessKeySecret) {
81
+ const str = `method:${method.toUpperCase()},url:${path}`;
82
+ return crypto_1.default.createHmac('sha256', accessKeySecret).update(Buffer.from(str, 'utf8')).digest('base64');
83
+ }
84
+ async format(response) {
85
+ if (response.status != 200) {
86
+ throw new Error('internal server error');
87
+ }
88
+ const json = response.data;
89
+ if (json.status !== BasicStatus.OK) {
90
+ throw new Error(json.message);
91
+ }
92
+ return camelcase_keys_1.default(json.body, {
93
+ deep: true,
94
+ });
95
+ }
96
+ }
97
+ exports.MarmotUtil = MarmotUtil;
@@ -0,0 +1,12 @@
1
+ interface Permission {
2
+ name: string;
3
+ extendValue?: string;
4
+ }
5
+ export declare class PermissionConverter {
6
+ static permission2candidateGroup(permission: Permission | string): string;
7
+ static candidateGroup2permission(candidateGroup: string): Permission;
8
+ static isBase64PermissionLike(str: string): boolean;
9
+ static base64URLEncode(str: string): string;
10
+ static base64URLDecode(str: string): string;
11
+ }
12
+ export {};
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PermissionConverter = void 0;
4
+ class PermissionConverter {
5
+ static permission2candidateGroup(permission) {
6
+ if (typeof permission === 'string') {
7
+ return PermissionConverter.base64URLEncode(permission) + '.';
8
+ }
9
+ return (PermissionConverter.base64URLEncode(permission.name) +
10
+ '.' +
11
+ PermissionConverter.base64URLEncode(permission.extendValue));
12
+ }
13
+ static candidateGroup2permission(candidateGroup) {
14
+ if (PermissionConverter.isBase64PermissionLike(candidateGroup)) {
15
+ const parts = candidateGroup.split('.');
16
+ return {
17
+ name: PermissionConverter.base64URLDecode(parts[0]),
18
+ extendValue: PermissionConverter.base64URLDecode(parts[1]),
19
+ };
20
+ }
21
+ return {
22
+ name: candidateGroup,
23
+ extendValue: '',
24
+ };
25
+ }
26
+ static isBase64PermissionLike(str) {
27
+ return /^[^.]+\.[^.]*$/.test(str);
28
+ }
29
+ static base64URLEncode(str) {
30
+ return Buffer.from(str).toString('base64');
31
+ }
32
+ static base64URLDecode(str) {
33
+ return Buffer.from(str, 'base64').toString('utf8');
34
+ }
35
+ }
36
+ exports.PermissionConverter = PermissionConverter;
@@ -0,0 +1,9 @@
1
+ export { KauthConfig } from './common/config/config';
2
+ export { KauthApi } from './common/http/kauth';
3
+ export { KflowApi } from './common/http/kflow';
4
+ export { GoogleAuthenticator, MoziAuthenticator, MiniprogramAuthenticator, AuthenticationInformation, PrimaryPrincipal, JsonWebTokenSubjectProvider, JsonWebTokenAuthenticationProvider, } from './authenticator';
5
+ export { PermissionCore } from './authorizer';
6
+ export { MoziAuthenticationInformation, MoziPrincipal, MoziCredential } from './authenticator/mozi';
7
+ export { GoogleAuthenticationInformation, GooglePrincipal, GoogleCredential } from './authenticator/google';
8
+ export { MiniprogramAuthenticationInformation, MiniprogramPrincipal, MiniprogramCredential, } from './authenticator/miniprogram';
9
+ export { PermissionConverter } from './common/util/converter/permission';