@ahoo-wang/fetcher-cosec 0.3.0
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/LICENSE +201 -0
- package/README.md +204 -0
- package/README.zh-CN.md +202 -0
- package/dist/cosecRequestInterceptor.d.ts +20 -0
- package/dist/cosecRequestInterceptor.d.ts.map +1 -0
- package/dist/cosecResponseInterceptor.d.ts +13 -0
- package/dist/cosecResponseInterceptor.d.ts.map +1 -0
- package/dist/deviceIdStorage.d.ts +29 -0
- package/dist/deviceIdStorage.d.ts.map +1 -0
- package/dist/idGenerator.d.ts +15 -0
- package/dist/idGenerator.d.ts.map +1 -0
- package/dist/inMemoryStorage.d.ts +14 -0
- package/dist/inMemoryStorage.d.ts.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.es.js +162 -0
- package/dist/index.umd.js +1 -0
- package/dist/tokenRefresher.d.ts +31 -0
- package/dist/tokenRefresher.d.ts.map +1 -0
- package/dist/tokenStorage.d.ts +22 -0
- package/dist/tokenStorage.d.ts.map +1 -0
- package/dist/types.d.ts +70 -0
- package/dist/types.d.ts.map +1 -0
- package/package.json +55 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
# @ahoo-wang/fetcher-cosec
|
|
2
|
+
|
|
3
|
+
Support for CoSec authentication in Fetcher HTTP client.
|
|
4
|
+
|
|
5
|
+
[CoSec](https://github.com/Ahoo-Wang/CoSec) is a comprehensive authentication and authorization framework.
|
|
6
|
+
|
|
7
|
+
This package provides integration between the Fetcher HTTP client and the CoSec authentication framework.
|
|
8
|
+
|
|
9
|
+
## Features
|
|
10
|
+
|
|
11
|
+
- Automatic CoSec authentication headers
|
|
12
|
+
- Device ID management with localStorage persistence
|
|
13
|
+
- Automatic token refresh based on response codes (401)
|
|
14
|
+
- Request ID generation for tracking
|
|
15
|
+
- Token storage management
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm install @ahoo-wang/fetcher-cosec
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Usage
|
|
24
|
+
|
|
25
|
+
### Basic Setup
|
|
26
|
+
|
|
27
|
+
```typescript
|
|
28
|
+
import { Fetcher } from '@ahoo-wang/fetcher';
|
|
29
|
+
import {
|
|
30
|
+
CoSecRequestInterceptor,
|
|
31
|
+
CoSecResponseInterceptor,
|
|
32
|
+
DeviceIdStorage,
|
|
33
|
+
TokenStorage,
|
|
34
|
+
TokenRefresher,
|
|
35
|
+
CompositeToken,
|
|
36
|
+
} from '@ahoo-wang/fetcher-cosec';
|
|
37
|
+
|
|
38
|
+
// Create a Fetcher instance
|
|
39
|
+
const fetcher = new Fetcher({
|
|
40
|
+
baseURL: 'https://api.example.com',
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
// Create storage instances
|
|
44
|
+
const deviceIdStorage = new DeviceIdStorage();
|
|
45
|
+
const tokenStorage = new TokenStorage();
|
|
46
|
+
|
|
47
|
+
// Create token refresher
|
|
48
|
+
const tokenRefresher: TokenRefresher = {
|
|
49
|
+
async refresh(token: CompositeToken): Promise<CompositeToken> {
|
|
50
|
+
// Refresh token logic here
|
|
51
|
+
const response = await fetcher.fetch('/auth/refresh', {
|
|
52
|
+
method: 'POST',
|
|
53
|
+
headers: {
|
|
54
|
+
'Content-Type': 'application/json',
|
|
55
|
+
},
|
|
56
|
+
body: token,
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
const tokens = await response.json();
|
|
60
|
+
return {
|
|
61
|
+
accessToken: tokens.access_token,
|
|
62
|
+
refreshToken: tokens.refresh_token,
|
|
63
|
+
};
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
// Add CoSec request interceptor
|
|
68
|
+
fetcher.interceptors.request.use(
|
|
69
|
+
new CoSecRequestInterceptor({
|
|
70
|
+
appId: 'your-app-id',
|
|
71
|
+
deviceIdStorage,
|
|
72
|
+
tokenStorage,
|
|
73
|
+
tokenRefresher,
|
|
74
|
+
}),
|
|
75
|
+
);
|
|
76
|
+
|
|
77
|
+
// Add CoSec response interceptor
|
|
78
|
+
fetcher.interceptors.response.use(
|
|
79
|
+
new CoSecResponseInterceptor({
|
|
80
|
+
appId: 'your-app-id',
|
|
81
|
+
deviceIdStorage,
|
|
82
|
+
tokenStorage,
|
|
83
|
+
tokenRefresher,
|
|
84
|
+
}),
|
|
85
|
+
);
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### Configuration Options
|
|
89
|
+
|
|
90
|
+
```typescript
|
|
91
|
+
interface CoSecOptions {
|
|
92
|
+
/**
|
|
93
|
+
* Application ID to be sent in the CoSec-App-Id header
|
|
94
|
+
*/
|
|
95
|
+
appId: string;
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Device ID storage instance
|
|
99
|
+
*/
|
|
100
|
+
deviceIdStorage: DeviceIdStorage;
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Token storage instance
|
|
104
|
+
*/
|
|
105
|
+
tokenStorage: TokenStorage;
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Token refresher function
|
|
109
|
+
*/
|
|
110
|
+
tokenRefresher: TokenRefresher;
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### Headers Added
|
|
115
|
+
|
|
116
|
+
The interceptor automatically adds the following headers to requests:
|
|
117
|
+
|
|
118
|
+
1. `CoSec-Device-Id`: Device identifier (stored in localStorage or generated)
|
|
119
|
+
2. `CoSec-App-Id`: Application identifier
|
|
120
|
+
3. `Authorization`: Bearer token
|
|
121
|
+
4. `CoSec-Request-Id`: Unique request identifier for each request
|
|
122
|
+
|
|
123
|
+
### Token Refresh
|
|
124
|
+
|
|
125
|
+
The response interceptor automatically handles token refresh when the server returns status code 401. When this happens,
|
|
126
|
+
the `tokenRefresher.refresh` function is called to obtain new access and refresh tokens.
|
|
127
|
+
|
|
128
|
+
### Token Storage
|
|
129
|
+
|
|
130
|
+
The package includes a `TokenStorage` class for managing tokens in localStorage:
|
|
131
|
+
|
|
132
|
+
```typescript
|
|
133
|
+
import { TokenStorage } from '@ahoo-wang/fetcher-cosec';
|
|
134
|
+
|
|
135
|
+
const tokenStorage = new TokenStorage();
|
|
136
|
+
|
|
137
|
+
// Store tokens
|
|
138
|
+
tokenStorage.set({
|
|
139
|
+
accessToken: 'access-token',
|
|
140
|
+
refreshToken: 'refresh-token',
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
// Get tokens
|
|
144
|
+
const token = tokenStorage.get();
|
|
145
|
+
if (token) {
|
|
146
|
+
console.log('Access token:', token.accessToken);
|
|
147
|
+
console.log('Refresh token:', token.refreshToken);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Clear tokens
|
|
151
|
+
tokenStorage.clear();
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
### Device ID Storage
|
|
155
|
+
|
|
156
|
+
The package includes a `DeviceIdStorage` class for managing device identifiers in localStorage:
|
|
157
|
+
|
|
158
|
+
```typescript
|
|
159
|
+
import { DeviceIdStorage } from '@ahoo-wang/fetcher-cosec';
|
|
160
|
+
|
|
161
|
+
const deviceIdStorage = new DeviceIdStorage();
|
|
162
|
+
|
|
163
|
+
// Get or create a device ID
|
|
164
|
+
const deviceId = deviceIdStorage.getOrCreate();
|
|
165
|
+
|
|
166
|
+
// Store a specific device ID
|
|
167
|
+
deviceIdStorage.set('specific-device-id');
|
|
168
|
+
|
|
169
|
+
// Get the current device ID
|
|
170
|
+
const currentDeviceId = deviceIdStorage.get();
|
|
171
|
+
|
|
172
|
+
// Clear the stored device ID
|
|
173
|
+
deviceIdStorage.clear();
|
|
174
|
+
|
|
175
|
+
// Generate a new device ID (without storing it)
|
|
176
|
+
const newDeviceId = deviceIdStorage.generateDeviceId();
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
## API
|
|
180
|
+
|
|
181
|
+
### Interfaces
|
|
182
|
+
|
|
183
|
+
- `AccessToken`: Contains an access token
|
|
184
|
+
- `RefreshToken`: Contains a refresh token
|
|
185
|
+
- `CompositeToken`: Contains both access and refresh tokens
|
|
186
|
+
- `TokenRefresher`: Provides a method to refresh tokens
|
|
187
|
+
|
|
188
|
+
### Classes
|
|
189
|
+
|
|
190
|
+
- `TokenStorage`: Manages token storage in localStorage
|
|
191
|
+
- `DeviceIdStorage`: Manages device ID storage in localStorage
|
|
192
|
+
- `CoSecRequestInterceptor`: Adds CoSec headers to requests
|
|
193
|
+
- `CoSecResponseInterceptor`: Handles token refresh on 401 responses
|
|
194
|
+
- `InMemoryStorage`: In-memory storage fallback for environments without localStorage
|
|
195
|
+
|
|
196
|
+
## CoSec Framework
|
|
197
|
+
|
|
198
|
+
This package is designed to work with the [CoSec authentication framework](https://github.com/Ahoo-Wang/CoSec). For more
|
|
199
|
+
information about CoSec features and capabilities, please visit
|
|
200
|
+
the [CoSec GitHub repository](https://github.com/Ahoo-Wang/CoSec).
|
|
201
|
+
|
|
202
|
+
## License
|
|
203
|
+
|
|
204
|
+
Apache-2.0
|
package/README.zh-CN.md
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
# @ahoo-wang/fetcher-cosec
|
|
2
|
+
|
|
3
|
+
Fetcher HTTP 客户端的 CoSec 认证支持。
|
|
4
|
+
|
|
5
|
+
[CoSec](https://github.com/Ahoo-Wang/CoSec) 是一个全面的身份认证和授权框架。
|
|
6
|
+
|
|
7
|
+
此包提供了 Fetcher HTTP 客户端与 CoSec 认证框架之间的集成。
|
|
8
|
+
|
|
9
|
+
## 功能特性
|
|
10
|
+
|
|
11
|
+
- 自动添加 CoSec 认证头
|
|
12
|
+
- 设备 ID 管理与 localStorage 持久化
|
|
13
|
+
- 基于响应码(401)的自动令牌刷新
|
|
14
|
+
- 请求 ID 生成用于跟踪
|
|
15
|
+
- 令牌存储管理
|
|
16
|
+
|
|
17
|
+
## 安装
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm install @ahoo-wang/fetcher-cosec
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## 使用方法
|
|
24
|
+
|
|
25
|
+
### 基本设置
|
|
26
|
+
|
|
27
|
+
```typescript
|
|
28
|
+
import { Fetcher } from '@ahoo-wang/fetcher';
|
|
29
|
+
import {
|
|
30
|
+
CoSecRequestInterceptor,
|
|
31
|
+
CoSecResponseInterceptor,
|
|
32
|
+
DeviceIdStorage,
|
|
33
|
+
TokenStorage,
|
|
34
|
+
TokenRefresher,
|
|
35
|
+
CompositeToken,
|
|
36
|
+
} from '@ahoo-wang/fetcher-cosec';
|
|
37
|
+
|
|
38
|
+
// 创建 Fetcher 实例
|
|
39
|
+
const fetcher = new Fetcher({
|
|
40
|
+
baseURL: 'https://api.example.com',
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
// 创建存储实例
|
|
44
|
+
const deviceIdStorage = new DeviceIdStorage();
|
|
45
|
+
const tokenStorage = new TokenStorage();
|
|
46
|
+
|
|
47
|
+
// 创建令牌刷新器
|
|
48
|
+
const tokenRefresher: TokenRefresher = {
|
|
49
|
+
async refresh(token: CompositeToken): Promise<CompositeToken> {
|
|
50
|
+
// 刷新令牌逻辑
|
|
51
|
+
const response = await fetcher.fetch('/auth/refresh', {
|
|
52
|
+
method: 'POST',
|
|
53
|
+
headers: {
|
|
54
|
+
'Content-Type': 'application/json',
|
|
55
|
+
},
|
|
56
|
+
body: token,
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
const tokens = await response.json();
|
|
60
|
+
return {
|
|
61
|
+
accessToken: tokens.access_token,
|
|
62
|
+
refreshToken: tokens.refresh_token,
|
|
63
|
+
};
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
// 添加 CoSec 请求拦截器
|
|
68
|
+
fetcher.interceptors.request.use(
|
|
69
|
+
new CoSecRequestInterceptor({
|
|
70
|
+
appId: 'your-app-id',
|
|
71
|
+
deviceIdStorage,
|
|
72
|
+
tokenStorage,
|
|
73
|
+
tokenRefresher,
|
|
74
|
+
}),
|
|
75
|
+
);
|
|
76
|
+
|
|
77
|
+
// 添加 CoSec 响应拦截器
|
|
78
|
+
fetcher.interceptors.response.use(
|
|
79
|
+
new CoSecResponseInterceptor({
|
|
80
|
+
appId: 'your-app-id',
|
|
81
|
+
deviceIdStorage,
|
|
82
|
+
tokenStorage,
|
|
83
|
+
tokenRefresher,
|
|
84
|
+
}),
|
|
85
|
+
);
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### 配置选项
|
|
89
|
+
|
|
90
|
+
```typescript
|
|
91
|
+
interface CoSecOptions {
|
|
92
|
+
/**
|
|
93
|
+
* 应用程序 ID,将在 CoSec-App-Id 头部中发送
|
|
94
|
+
*/
|
|
95
|
+
appId: string;
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* 设备 ID 存储实例
|
|
99
|
+
*/
|
|
100
|
+
deviceIdStorage: DeviceIdStorage;
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 令牌存储实例
|
|
104
|
+
*/
|
|
105
|
+
tokenStorage: TokenStorage;
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* 令牌刷新函数
|
|
109
|
+
*/
|
|
110
|
+
tokenRefresher: TokenRefresher;
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### 添加的头部
|
|
115
|
+
|
|
116
|
+
拦截器会自动向请求添加以下头部:
|
|
117
|
+
|
|
118
|
+
1. `CoSec-Device-Id`: 设备标识符(存储在 localStorage 中或生成)
|
|
119
|
+
2. `CoSec-App-Id`: 应用程序标识符
|
|
120
|
+
3. `Authorization`: Bearer 令牌
|
|
121
|
+
4. `CoSec-Request-Id`: 每个请求的唯一请求标识符
|
|
122
|
+
|
|
123
|
+
### 令牌刷新
|
|
124
|
+
|
|
125
|
+
响应拦截器会在服务器返回状态码 401 时自动处理令牌刷新。此时会调用 `tokenRefresher.refresh` 函数来获取新的访问和刷新令牌。
|
|
126
|
+
|
|
127
|
+
### 令牌存储
|
|
128
|
+
|
|
129
|
+
包中包含一个 `TokenStorage` 类,用于管理 localStorage 中的令牌:
|
|
130
|
+
|
|
131
|
+
```typescript
|
|
132
|
+
import { TokenStorage } from '@ahoo-wang/fetcher-cosec';
|
|
133
|
+
|
|
134
|
+
const tokenStorage = new TokenStorage();
|
|
135
|
+
|
|
136
|
+
// 存储令牌
|
|
137
|
+
tokenStorage.set({
|
|
138
|
+
accessToken: 'access-token',
|
|
139
|
+
refreshToken: 'refresh-token',
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
// 获取令牌
|
|
143
|
+
const token = tokenStorage.get();
|
|
144
|
+
if (token) {
|
|
145
|
+
console.log('访问令牌:', token.accessToken);
|
|
146
|
+
console.log('刷新令牌:', token.refreshToken);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// 清除令牌
|
|
150
|
+
tokenStorage.clear();
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### 设备 ID 存储
|
|
154
|
+
|
|
155
|
+
包中包含一个 `DeviceIdStorage` 类,用于管理 localStorage 中的设备标识符:
|
|
156
|
+
|
|
157
|
+
```typescript
|
|
158
|
+
import { DeviceIdStorage } from '@ahoo-wang/fetcher-cosec';
|
|
159
|
+
|
|
160
|
+
const deviceIdStorage = new DeviceIdStorage();
|
|
161
|
+
|
|
162
|
+
// 获取或创建设备 ID
|
|
163
|
+
const deviceId = deviceIdStorage.getOrCreate();
|
|
164
|
+
|
|
165
|
+
// 存储特定的设备 ID
|
|
166
|
+
deviceIdStorage.set('specific-device-id');
|
|
167
|
+
|
|
168
|
+
// 获取当前设备 ID
|
|
169
|
+
const currentDeviceId = deviceIdStorage.get();
|
|
170
|
+
|
|
171
|
+
// 清除存储的设备 ID
|
|
172
|
+
deviceIdStorage.clear();
|
|
173
|
+
|
|
174
|
+
// 生成新的设备 ID(不存储)
|
|
175
|
+
const newDeviceId = deviceIdStorage.generateDeviceId();
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
## API
|
|
179
|
+
|
|
180
|
+
### 接口
|
|
181
|
+
|
|
182
|
+
- `AccessToken`: 包含访问令牌
|
|
183
|
+
- `RefreshToken`: 包含刷新令牌
|
|
184
|
+
- `CompositeToken`: 包含访问和刷新令牌
|
|
185
|
+
- `TokenRefresher`: 提供刷新令牌的方法
|
|
186
|
+
|
|
187
|
+
### 类
|
|
188
|
+
|
|
189
|
+
- `TokenStorage`: 管理 localStorage 中的令牌存储
|
|
190
|
+
- `DeviceIdStorage`: 管理 localStorage 中的设备 ID 存储
|
|
191
|
+
- `CoSecRequestInterceptor`: 向请求添加 CoSec 头部
|
|
192
|
+
- `CoSecResponseInterceptor`: 处理 401 响应的令牌刷新
|
|
193
|
+
- `InMemoryStorage`: 无 localStorage 环境的内存存储后备
|
|
194
|
+
|
|
195
|
+
## CoSec 框架
|
|
196
|
+
|
|
197
|
+
此包设计用于与 [CoSec 认证框架](https://github.com/Ahoo-Wang/CoSec) 配合使用。有关 CoSec
|
|
198
|
+
功能和特性的更多信息,请访问 [CoSec GitHub 仓库](https://github.com/Ahoo-Wang/CoSec)。
|
|
199
|
+
|
|
200
|
+
## 许可证
|
|
201
|
+
|
|
202
|
+
Apache-2.0
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { Interceptor, FetchExchange } from '@ahoo-wang/fetcher';
|
|
2
|
+
import { CoSecOptions } from './types';
|
|
3
|
+
/**
|
|
4
|
+
* CoSec Request Interceptor
|
|
5
|
+
*
|
|
6
|
+
* Automatically adds CoSec authentication headers to requests:
|
|
7
|
+
* - CoSec-Device-Id: Device identifier (stored in localStorage or generated)
|
|
8
|
+
* - CoSec-App-Id: Application identifier
|
|
9
|
+
* - Authorization: Bearer token
|
|
10
|
+
* - CoSec-Request-Id: Unique request identifier for each request
|
|
11
|
+
*/
|
|
12
|
+
export declare class CoSecRequestInterceptor implements Interceptor {
|
|
13
|
+
private options;
|
|
14
|
+
constructor(options: CoSecOptions);
|
|
15
|
+
/**
|
|
16
|
+
* Intercept requests to add CoSec authentication headers
|
|
17
|
+
*/
|
|
18
|
+
intercept(exchange: FetchExchange): FetchExchange;
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=cosecRequestInterceptor.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cosecRequestInterceptor.d.ts","sourceRoot":"","sources":["../src/cosecRequestInterceptor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAkB,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAChF,OAAO,EAAgB,YAAY,EAAE,MAAM,SAAS,CAAC;AAGrD;;;;;;;;GAQG;AACH,qBAAa,uBAAwB,YAAW,WAAW;IACzD,OAAO,CAAC,OAAO,CAAe;gBAElB,OAAO,EAAE,YAAY;IAIjC;;OAEG;IACH,SAAS,CAAC,QAAQ,EAAE,aAAa,GAAG,aAAa;CAuBlD"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { CoSecOptions } from './types';
|
|
2
|
+
import { FetchExchange, Interceptor } from '@ahoo-wang/fetcher';
|
|
3
|
+
/**
|
|
4
|
+
* CoSec Response Interceptor
|
|
5
|
+
*
|
|
6
|
+
* Handles automatic token refresh based on response codes
|
|
7
|
+
*/
|
|
8
|
+
export declare class CoSecResponseInterceptor implements Interceptor {
|
|
9
|
+
private options;
|
|
10
|
+
constructor(options: CoSecOptions);
|
|
11
|
+
intercept(exchange: FetchExchange): Promise<FetchExchange>;
|
|
12
|
+
}
|
|
13
|
+
//# sourceMappingURL=cosecResponseInterceptor.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cosecResponseInterceptor.d.ts","sourceRoot":"","sources":["../src/cosecResponseInterceptor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAiB,MAAM,SAAS,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAEhE;;;;GAIG;AACH,qBAAa,wBAAyB,YAAW,WAAW;IAC1D,OAAO,CAAC,OAAO,CAAe;gBAElB,OAAO,EAAE,YAAY;IAI3B,SAAS,CAAC,QAAQ,EAAE,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;CAsBjE"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Device ID storage class for managing device identifiers
|
|
3
|
+
*/
|
|
4
|
+
export declare class DeviceIdStorage {
|
|
5
|
+
private readonly deviceIdKey;
|
|
6
|
+
private storage;
|
|
7
|
+
constructor(deviceIdKey?: string, storage?: Storage);
|
|
8
|
+
/**
|
|
9
|
+
* Get the current device ID
|
|
10
|
+
*/
|
|
11
|
+
get(): string | null;
|
|
12
|
+
/**
|
|
13
|
+
* Set a device ID
|
|
14
|
+
*/
|
|
15
|
+
set(deviceId: string): void;
|
|
16
|
+
/**
|
|
17
|
+
* Generate a new device ID
|
|
18
|
+
*/
|
|
19
|
+
generateDeviceId(): string;
|
|
20
|
+
/**
|
|
21
|
+
* Get or create a device ID
|
|
22
|
+
*/
|
|
23
|
+
getOrCreate(): string;
|
|
24
|
+
/**
|
|
25
|
+
* Clear the stored device ID
|
|
26
|
+
*/
|
|
27
|
+
clear(): void;
|
|
28
|
+
}
|
|
29
|
+
//# sourceMappingURL=deviceIdStorage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"deviceIdStorage.d.ts","sourceRoot":"","sources":["../src/deviceIdStorage.ts"],"names":[],"mappings":"AAKA;;GAEG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,OAAO,CAAU;gBAGvB,WAAW,GAAE,MAAgC,EAC7C,OAAO,GAAE,OAAsB;IAMjC;;OAEG;IACH,GAAG,IAAI,MAAM,GAAG,IAAI;IAIpB;;OAEG;IACH,GAAG,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI;IAI3B;;OAEG;IACH,gBAAgB,IAAI,MAAM;IAI1B;;OAEG;IACH,WAAW,IAAI,MAAM;IAYrB;;OAEG;IACH,KAAK,IAAI,IAAI;CAGd"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export interface IdGenerator {
|
|
2
|
+
generateId(): string;
|
|
3
|
+
}
|
|
4
|
+
/**
|
|
5
|
+
* Nano ID implementation of IdGenerator
|
|
6
|
+
* Generates unique request IDs using Nano ID
|
|
7
|
+
*/
|
|
8
|
+
export declare class NanoIdGenerator implements IdGenerator {
|
|
9
|
+
/**
|
|
10
|
+
* Generate a unique request ID
|
|
11
|
+
*/
|
|
12
|
+
generateId(): string;
|
|
13
|
+
}
|
|
14
|
+
export declare const idGenerator: NanoIdGenerator;
|
|
15
|
+
//# sourceMappingURL=idGenerator.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"idGenerator.d.ts","sourceRoot":"","sources":["../src/idGenerator.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,WAAW;IAC1B,UAAU,IAAI,MAAM,CAAC;CACtB;AAED;;;GAGG;AACH,qBAAa,eAAgB,YAAW,WAAW;IACjD;;OAEG;IACH,UAAU,IAAI,MAAM;CAGrB;AAED,eAAO,MAAM,WAAW,iBAAwB,CAAC"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory storage fallback for environments without localStorage
|
|
3
|
+
*/
|
|
4
|
+
export declare class InMemoryStorage implements Storage {
|
|
5
|
+
private store;
|
|
6
|
+
get length(): number;
|
|
7
|
+
clear(): void;
|
|
8
|
+
getItem(key: string): string | null;
|
|
9
|
+
key(index: number): string | null;
|
|
10
|
+
removeItem(key: string): void;
|
|
11
|
+
setItem(key: string, value: string): void;
|
|
12
|
+
}
|
|
13
|
+
export declare function getStorage(): Storage;
|
|
14
|
+
//# sourceMappingURL=inMemoryStorage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inMemoryStorage.d.ts","sourceRoot":"","sources":["../src/inMemoryStorage.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,qBAAa,eAAgB,YAAW,OAAO;IAC7C,OAAO,CAAC,KAAK,CAAkC;IAE/C,IAAI,MAAM,IAAI,MAAM,CAEnB;IAED,KAAK,IAAI,IAAI;IAIb,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI;IAKnC,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI;IAKjC,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAM7B,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;CAG1C;AAED,wBAAgB,UAAU,IAAI,OAAO,CAOpC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export * from './cosecRequestInterceptor';
|
|
2
|
+
export * from './cosecResponseInterceptor';
|
|
3
|
+
export * from './deviceIdStorage';
|
|
4
|
+
export * from './idGenerator';
|
|
5
|
+
export * from './inMemoryStorage';
|
|
6
|
+
export * from './tokenRefresher';
|
|
7
|
+
export * from './tokenStorage';
|
|
8
|
+
export * from './types';
|
|
9
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,2BAA2B,CAAC;AAC1C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,mBAAmB,CAAC;AAClC,cAAc,eAAe,CAAC;AAC9B,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,SAAS,CAAC"}
|
package/dist/index.es.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
var o = /* @__PURE__ */ ((t) => (t.DEVICE_ID = "CoSec-Device-Id", t.APP_ID = "CoSec-App-Id", t.AUTHORIZATION = "Authorization", t.REQUEST_ID = "CoSec-Request-Id", t))(o || {}), c = /* @__PURE__ */ ((t) => (t[t.UNAUTHORIZED = 401] = "UNAUTHORIZED", t))(c || {});
|
|
2
|
+
const S = {
|
|
3
|
+
ALLOW: { authorized: !0, reason: "Allow" },
|
|
4
|
+
EXPLICIT_DENY: { authorized: !1, reason: "Explicit Deny" },
|
|
5
|
+
IMPLICIT_DENY: { authorized: !1, reason: "Implicit Deny" },
|
|
6
|
+
TOKEN_EXPIRED: { authorized: !1, reason: "Token Expired" },
|
|
7
|
+
TOO_MANY_REQUESTS: { authorized: !1, reason: "Too Many Requests" }
|
|
8
|
+
}, d = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
|
|
9
|
+
let h = (t = 21) => {
|
|
10
|
+
let e = "", r = crypto.getRandomValues(new Uint8Array(t |= 0));
|
|
11
|
+
for (; t--; )
|
|
12
|
+
e += d[r[t] & 63];
|
|
13
|
+
return e;
|
|
14
|
+
};
|
|
15
|
+
class l {
|
|
16
|
+
/**
|
|
17
|
+
* Generate a unique request ID
|
|
18
|
+
*/
|
|
19
|
+
generateId() {
|
|
20
|
+
return h();
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
const u = new l();
|
|
24
|
+
class k {
|
|
25
|
+
constructor(e) {
|
|
26
|
+
this.options = e;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Intercept requests to add CoSec authentication headers
|
|
30
|
+
*/
|
|
31
|
+
intercept(e) {
|
|
32
|
+
const r = u.generateId(), n = this.options.deviceIdStorage.getOrCreate(), s = this.options.tokenStorage.get(), a = {
|
|
33
|
+
...e.request,
|
|
34
|
+
headers: {
|
|
35
|
+
...e.request.headers
|
|
36
|
+
}
|
|
37
|
+
}, i = a.headers;
|
|
38
|
+
return i[o.APP_ID] = this.options.appId, i[o.DEVICE_ID] = n, i[o.REQUEST_ID] = r, s && (i[o.AUTHORIZATION] = `Bearer ${s.accessToken}`), { ...e, request: a };
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
class f {
|
|
42
|
+
constructor(e) {
|
|
43
|
+
this.options = e;
|
|
44
|
+
}
|
|
45
|
+
async intercept(e) {
|
|
46
|
+
const r = e.response;
|
|
47
|
+
if (!r || r.status !== c.UNAUTHORIZED)
|
|
48
|
+
return e;
|
|
49
|
+
const n = this.options.tokenStorage.get();
|
|
50
|
+
if (!n)
|
|
51
|
+
return e;
|
|
52
|
+
try {
|
|
53
|
+
const s = await this.options.tokenRefresher.refresh(n);
|
|
54
|
+
return this.options.tokenStorage.set(s), e.fetcher.request(e.url, e.request);
|
|
55
|
+
} catch (s) {
|
|
56
|
+
throw this.options.tokenStorage.clear(), s;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
class g {
|
|
61
|
+
constructor() {
|
|
62
|
+
this.store = /* @__PURE__ */ new Map();
|
|
63
|
+
}
|
|
64
|
+
get length() {
|
|
65
|
+
return this.store.size;
|
|
66
|
+
}
|
|
67
|
+
clear() {
|
|
68
|
+
this.store.clear();
|
|
69
|
+
}
|
|
70
|
+
getItem(e) {
|
|
71
|
+
const r = this.store.get(e);
|
|
72
|
+
return r !== void 0 ? r : null;
|
|
73
|
+
}
|
|
74
|
+
key(e) {
|
|
75
|
+
return Array.from(this.store.keys())[e] || null;
|
|
76
|
+
}
|
|
77
|
+
removeItem(e) {
|
|
78
|
+
this.store.has(e) && this.store.delete(e);
|
|
79
|
+
}
|
|
80
|
+
setItem(e, r) {
|
|
81
|
+
this.store.set(e, r);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
function I() {
|
|
85
|
+
return typeof window < "u" && window.localStorage ? window.localStorage : new g();
|
|
86
|
+
}
|
|
87
|
+
const p = "cosec-device-id";
|
|
88
|
+
class D {
|
|
89
|
+
constructor(e = p, r = I()) {
|
|
90
|
+
this.deviceIdKey = e, this.storage = r;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Get the current device ID
|
|
94
|
+
*/
|
|
95
|
+
get() {
|
|
96
|
+
return this.storage.getItem(this.deviceIdKey);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Set a device ID
|
|
100
|
+
*/
|
|
101
|
+
set(e) {
|
|
102
|
+
this.storage.setItem(this.deviceIdKey, e);
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Generate a new device ID
|
|
106
|
+
*/
|
|
107
|
+
generateDeviceId() {
|
|
108
|
+
return u.generateId();
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Get or create a device ID
|
|
112
|
+
*/
|
|
113
|
+
getOrCreate() {
|
|
114
|
+
let e = this.get();
|
|
115
|
+
return e || (e = this.generateDeviceId(), this.set(e)), e;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Clear the stored device ID
|
|
119
|
+
*/
|
|
120
|
+
clear() {
|
|
121
|
+
this.storage.removeItem(this.deviceIdKey);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const y = "cosec-token";
|
|
125
|
+
class E {
|
|
126
|
+
constructor(e = y, r = I()) {
|
|
127
|
+
this.tokenKey = e, this.storage = r;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Get the current access token
|
|
131
|
+
*/
|
|
132
|
+
get() {
|
|
133
|
+
const e = this.storage.getItem(this.tokenKey);
|
|
134
|
+
return e ? JSON.parse(e) : null;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Store a composite token
|
|
138
|
+
*/
|
|
139
|
+
set(e) {
|
|
140
|
+
const r = JSON.stringify(e);
|
|
141
|
+
this.storage.setItem(this.tokenKey, r);
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Clear all tokens
|
|
145
|
+
*/
|
|
146
|
+
clear() {
|
|
147
|
+
this.storage.removeItem(this.tokenKey);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
export {
|
|
151
|
+
S as AuthorizeResults,
|
|
152
|
+
o as CoSecHeaders,
|
|
153
|
+
k as CoSecRequestInterceptor,
|
|
154
|
+
f as CoSecResponseInterceptor,
|
|
155
|
+
D as DeviceIdStorage,
|
|
156
|
+
g as InMemoryStorage,
|
|
157
|
+
l as NanoIdGenerator,
|
|
158
|
+
c as ResponseCodes,
|
|
159
|
+
E as TokenStorage,
|
|
160
|
+
I as getStorage,
|
|
161
|
+
u as idGenerator
|
|
162
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(function(o,s){typeof exports=="object"&&typeof module<"u"?s(exports):typeof define=="function"&&define.amd?define(["exports"],s):(o=typeof globalThis<"u"?globalThis:o||self,s(o.FetcherCoSec={}))})(this,(function(o){"use strict";var s=(t=>(t.DEVICE_ID="CoSec-Device-Id",t.APP_ID="CoSec-App-Id",t.AUTHORIZATION="Authorization",t.REQUEST_ID="CoSec-Request-Id",t))(s||{}),c=(t=>(t[t.UNAUTHORIZED=401]="UNAUTHORIZED",t))(c||{});const g={ALLOW:{authorized:!0,reason:"Allow"},EXPLICIT_DENY:{authorized:!1,reason:"Explicit Deny"},IMPLICIT_DENY:{authorized:!1,reason:"Implicit Deny"},TOKEN_EXPIRED:{authorized:!1,reason:"Token Expired"},TOO_MANY_REQUESTS:{authorized:!1,reason:"Too Many Requests"}},f="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let S=(t=21)=>{let e="",r=crypto.getRandomValues(new Uint8Array(t|=0));for(;t--;)e+=f[r[t]&63];return e};class I{generateId(){return S()}}const u=new I;class y{constructor(e){this.options=e}intercept(e){const r=u.generateId(),i=this.options.deviceIdStorage.getOrCreate(),n=this.options.tokenStorage.get(),l={...e.request,headers:{...e.request.headers}},a=l.headers;return a[s.APP_ID]=this.options.appId,a[s.DEVICE_ID]=i,a[s.REQUEST_ID]=r,n&&(a[s.AUTHORIZATION]=`Bearer ${n.accessToken}`),{...e,request:l}}}class p{constructor(e){this.options=e}async intercept(e){const r=e.response;if(!r||r.status!==c.UNAUTHORIZED)return e;const i=this.options.tokenStorage.get();if(!i)return e;try{const n=await this.options.tokenRefresher.refresh(i);return this.options.tokenStorage.set(n),e.fetcher.request(e.url,e.request)}catch(n){throw this.options.tokenStorage.clear(),n}}}class h{constructor(){this.store=new Map}get length(){return this.store.size}clear(){this.store.clear()}getItem(e){const r=this.store.get(e);return r!==void 0?r:null}key(e){return Array.from(this.store.keys())[e]||null}removeItem(e){this.store.has(e)&&this.store.delete(e)}setItem(e,r){this.store.set(e,r)}}function d(){return typeof window<"u"&&window.localStorage?window.localStorage:new h}const T="cosec-device-id";class k{constructor(e=T,r=d()){this.deviceIdKey=e,this.storage=r}get(){return this.storage.getItem(this.deviceIdKey)}set(e){this.storage.setItem(this.deviceIdKey,e)}generateDeviceId(){return u.generateId()}getOrCreate(){let e=this.get();return e||(e=this.generateDeviceId(),this.set(e)),e}clear(){this.storage.removeItem(this.deviceIdKey)}}const v="cosec-token";class D{constructor(e=v,r=d()){this.tokenKey=e,this.storage=r}get(){const e=this.storage.getItem(this.tokenKey);return e?JSON.parse(e):null}set(e){const r=JSON.stringify(e);this.storage.setItem(this.tokenKey,r)}clear(){this.storage.removeItem(this.tokenKey)}}o.AuthorizeResults=g,o.CoSecHeaders=s,o.CoSecRequestInterceptor=y,o.CoSecResponseInterceptor=p,o.DeviceIdStorage=k,o.InMemoryStorage=h,o.NanoIdGenerator=I,o.ResponseCodes=c,o.TokenStorage=D,o.getStorage=d,o.idGenerator=u,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})}));
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Access token interface
|
|
3
|
+
*/
|
|
4
|
+
export interface AccessToken {
|
|
5
|
+
accessToken: string;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Refresh token interface
|
|
9
|
+
*/
|
|
10
|
+
export interface RefreshToken {
|
|
11
|
+
refreshToken: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Composite token interface that contains both access and refresh tokens
|
|
15
|
+
* accessToken and refreshToken always appear in pairs, no need to split them
|
|
16
|
+
*/
|
|
17
|
+
export interface CompositeToken extends AccessToken, RefreshToken {
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Token refresher interface
|
|
21
|
+
* Provides a method to refresh tokens
|
|
22
|
+
*/
|
|
23
|
+
export interface TokenRefresher {
|
|
24
|
+
/**
|
|
25
|
+
* Refresh the given token and return a new CompositeToken
|
|
26
|
+
* @param token The token to refresh
|
|
27
|
+
* @returns A Promise that resolves to a new CompositeToken
|
|
28
|
+
*/
|
|
29
|
+
refresh(token: CompositeToken): Promise<CompositeToken>;
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=tokenRefresher.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tokenRefresher.d.ts","sourceRoot":"","sources":["../src/tokenRefresher.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,WAAW,EAAE,MAAM,CAAC;CACrB;AAED;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,YAAY,EAAE,MAAM,CAAC;CACtB;AAED;;;GAGG;AACH,MAAM,WAAW,cAAe,SAAQ,WAAW,EAAE,YAAY;CAChE;AAED;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC7B;;;;OAIG;IACH,OAAO,CAAC,KAAK,EAAE,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC;CACzD"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { CompositeToken } from './tokenRefresher';
|
|
2
|
+
/**
|
|
3
|
+
* Token storage class for managing access and refresh tokens
|
|
4
|
+
*/
|
|
5
|
+
export declare class TokenStorage {
|
|
6
|
+
private readonly tokenKey;
|
|
7
|
+
private storage;
|
|
8
|
+
constructor(tokenKey?: string, storage?: Storage);
|
|
9
|
+
/**
|
|
10
|
+
* Get the current access token
|
|
11
|
+
*/
|
|
12
|
+
get(): CompositeToken | null;
|
|
13
|
+
/**
|
|
14
|
+
* Store a composite token
|
|
15
|
+
*/
|
|
16
|
+
set(token: CompositeToken): void;
|
|
17
|
+
/**
|
|
18
|
+
* Clear all tokens
|
|
19
|
+
*/
|
|
20
|
+
clear(): void;
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=tokenStorage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tokenStorage.d.ts","sourceRoot":"","sources":["../src/tokenStorage.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAIlD;;GAEG;AACH,qBAAa,YAAY;IACvB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,OAAO,CAAU;gBAGvB,QAAQ,GAAE,MAA6B,EACvC,OAAO,GAAE,OAAsB;IAMjC;;OAEG;IACH,GAAG,IAAI,cAAc,GAAG,IAAI;IAK5B;;OAEG;IACH,GAAG,CAAC,KAAK,EAAE,cAAc,GAAG,IAAI;IAKhC;;OAEG;IACH,KAAK,IAAI,IAAI;CAGd"}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { DeviceIdStorage } from './deviceIdStorage';
|
|
2
|
+
import { TokenStorage } from './tokenStorage';
|
|
3
|
+
import { TokenRefresher } from './tokenRefresher';
|
|
4
|
+
/**
|
|
5
|
+
* CoSec HTTP headers enumeration
|
|
6
|
+
*/
|
|
7
|
+
export declare enum CoSecHeaders {
|
|
8
|
+
DEVICE_ID = "CoSec-Device-Id",
|
|
9
|
+
APP_ID = "CoSec-App-Id",
|
|
10
|
+
AUTHORIZATION = "Authorization",
|
|
11
|
+
REQUEST_ID = "CoSec-Request-Id"
|
|
12
|
+
}
|
|
13
|
+
export declare enum ResponseCodes {
|
|
14
|
+
UNAUTHORIZED = 401
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* CoSec options interface
|
|
18
|
+
*/
|
|
19
|
+
export interface CoSecOptions {
|
|
20
|
+
/**
|
|
21
|
+
* Application ID to be sent in the CoSec-App-Id header
|
|
22
|
+
*/
|
|
23
|
+
appId: string;
|
|
24
|
+
/**
|
|
25
|
+
* Device ID storage instance
|
|
26
|
+
*/
|
|
27
|
+
deviceIdStorage: DeviceIdStorage;
|
|
28
|
+
/**
|
|
29
|
+
* Token storage instance
|
|
30
|
+
*/
|
|
31
|
+
tokenStorage: TokenStorage;
|
|
32
|
+
/**
|
|
33
|
+
* Token refresher function
|
|
34
|
+
* Takes a CompositeToken and returns a Promise that resolves to a new CompositeToken
|
|
35
|
+
*/
|
|
36
|
+
tokenRefresher: TokenRefresher;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Authorization result interface
|
|
40
|
+
*/
|
|
41
|
+
export interface AuthorizeResult {
|
|
42
|
+
authorized: boolean;
|
|
43
|
+
reason: string;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Authorization result constants
|
|
47
|
+
*/
|
|
48
|
+
export declare const AuthorizeResults: {
|
|
49
|
+
ALLOW: {
|
|
50
|
+
authorized: boolean;
|
|
51
|
+
reason: string;
|
|
52
|
+
};
|
|
53
|
+
EXPLICIT_DENY: {
|
|
54
|
+
authorized: boolean;
|
|
55
|
+
reason: string;
|
|
56
|
+
};
|
|
57
|
+
IMPLICIT_DENY: {
|
|
58
|
+
authorized: boolean;
|
|
59
|
+
reason: string;
|
|
60
|
+
};
|
|
61
|
+
TOKEN_EXPIRED: {
|
|
62
|
+
authorized: boolean;
|
|
63
|
+
reason: string;
|
|
64
|
+
};
|
|
65
|
+
TOO_MANY_REQUESTS: {
|
|
66
|
+
authorized: boolean;
|
|
67
|
+
reason: string;
|
|
68
|
+
};
|
|
69
|
+
};
|
|
70
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD;;GAEG;AACH,oBAAY,YAAY;IACtB,SAAS,oBAAoB;IAC7B,MAAM,iBAAiB;IACvB,aAAa,kBAAkB;IAC/B,UAAU,qBAAqB;CAChC;AAED,oBAAY,aAAa;IACvB,YAAY,MAAM;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,eAAe,EAAE,eAAe,CAAC;IAEjC;;OAEG;IACH,YAAY,EAAE,YAAY,CAAC;IAE3B;;;OAGG;IACH,cAAc,EAAE,cAAc,CAAC;CAChC;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,UAAU,EAAE,OAAO,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;GAEG;AACH,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;CAM5B,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@ahoo-wang/fetcher-cosec",
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Support for CoSec authentication in Fetcher",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"fetch",
|
|
7
|
+
"http",
|
|
8
|
+
"client",
|
|
9
|
+
"cosec",
|
|
10
|
+
"authentication"
|
|
11
|
+
],
|
|
12
|
+
"author": "Ahoo-Wang",
|
|
13
|
+
"license": "Apache-2.0",
|
|
14
|
+
"homepage": "https://github.com/Ahoo-Wang/fetcher/tree/master/packages/cosec",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "https://github.com/Ahoo-Wang/fetcher.git",
|
|
18
|
+
"directory": "packages/cosec"
|
|
19
|
+
},
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/Ahoo-Wang/fetcher/issues"
|
|
22
|
+
},
|
|
23
|
+
"main": "./dist/index.umd.js",
|
|
24
|
+
"module": "./dist/index.es.js",
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"import": "./dist/index.es.js",
|
|
30
|
+
"require": "./dist/index.umd.js"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"dist"
|
|
35
|
+
],
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"nanoid": "^5.1.5",
|
|
38
|
+
"@ahoo-wang/fetcher": "0.3.0"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"@vitest/coverage-v8": "^3.2.4",
|
|
42
|
+
"eslint": "^9.33.0",
|
|
43
|
+
"prettier": "^3.6.2",
|
|
44
|
+
"typescript": "^5.9.2",
|
|
45
|
+
"unplugin-dts": "1.0.0-beta.6",
|
|
46
|
+
"vite": "^7.1.3",
|
|
47
|
+
"vitest": "^3.2.4"
|
|
48
|
+
},
|
|
49
|
+
"scripts": {
|
|
50
|
+
"build": "vite build",
|
|
51
|
+
"test": "vitest run --coverage",
|
|
52
|
+
"lint": "tsc --noEmit",
|
|
53
|
+
"clean": "rm -rf dist"
|
|
54
|
+
}
|
|
55
|
+
}
|