apikeyscreator 1.0.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/BUN.md +263 -0
- package/IMPLEMENTATION.md +298 -0
- package/LIBRARY.md +425 -0
- package/PROJECT-SUMMARY.md +297 -0
- package/QUICK-REF.md +277 -0
- package/README.md +228 -0
- package/examples/client.js +162 -0
- package/package.json +25 -0
- package/src/middleware/auth.js +17 -0
- package/src/routes/apiKeys.js +143 -0
- package/src/routes/auth.js +96 -0
- package/src/server.js +41 -0
- package/src/utils/db.js +137 -0
- package/src/utils/jwt.js +24 -0
- package/test.js +118 -0
package/QUICK-REF.md
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
# Quick Reference
|
|
2
|
+
|
|
3
|
+
## Installation & Setup
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
# Install
|
|
7
|
+
npm install
|
|
8
|
+
|
|
9
|
+
# Start server
|
|
10
|
+
npm start
|
|
11
|
+
|
|
12
|
+
# Dev mode with auto-reload
|
|
13
|
+
npm run dev
|
|
14
|
+
|
|
15
|
+
# Run tests
|
|
16
|
+
node test.js
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Environment Variables
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
PORT=3000 # Server port
|
|
23
|
+
JWT_SECRET=your-secret-key # JWT signing secret
|
|
24
|
+
NODE_ENV=production # Environment
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## API Endpoints Summary
|
|
28
|
+
|
|
29
|
+
### Authentication (No Auth Required)
|
|
30
|
+
|
|
31
|
+
| Method | Endpoint | Body | Response |
|
|
32
|
+
|--------|----------|------|----------|
|
|
33
|
+
| POST | `/auth/register` | `{email, password}` | `{user, token}` |
|
|
34
|
+
| POST | `/auth/login` | `{email, password}` | `{user, token}` |
|
|
35
|
+
|
|
36
|
+
### API Keys (Auth Required - use `Authorization: Bearer TOKEN` header)
|
|
37
|
+
|
|
38
|
+
| Method | Endpoint | Body | Response |
|
|
39
|
+
|--------|----------|------|----------|
|
|
40
|
+
| GET | `/api/keys` | - | `{count, keys[]}` |
|
|
41
|
+
| POST | `/api/keys` | `{name}` | `{key}` |
|
|
42
|
+
| GET | `/api/keys/:id` | - | `{key}` |
|
|
43
|
+
| PUT | `/api/keys/:id` | `{name?, active?}` | `{key}` |
|
|
44
|
+
| DELETE | `/api/keys/:id` | - | `{message}` |
|
|
45
|
+
| POST | `/api/keys/:id/usage` | - | `{message}` |
|
|
46
|
+
|
|
47
|
+
## API Key Object
|
|
48
|
+
|
|
49
|
+
```json
|
|
50
|
+
{
|
|
51
|
+
"id": "1234567890",
|
|
52
|
+
"name": "Production Key",
|
|
53
|
+
"key": "sk_abcd1234efgh5678...",
|
|
54
|
+
"active": true,
|
|
55
|
+
"createdAt": "2024-01-01T10:00:00.000Z",
|
|
56
|
+
"lastUsed": "2024-01-02T15:30:45.000Z"
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## User Object
|
|
61
|
+
|
|
62
|
+
```json
|
|
63
|
+
{
|
|
64
|
+
"id": "1234567890",
|
|
65
|
+
"email": "user@example.com",
|
|
66
|
+
"createdAt": "2024-01-01T10:00:00.000Z"
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## cURL Examples
|
|
71
|
+
|
|
72
|
+
### Register
|
|
73
|
+
```bash
|
|
74
|
+
curl -X POST http://localhost:3000/auth/register \
|
|
75
|
+
-H "Content-Type: application/json" \
|
|
76
|
+
-d '{"email":"user@example.com","password":"pass123"}'
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### Login
|
|
80
|
+
```bash
|
|
81
|
+
curl -X POST http://localhost:3000/auth/login \
|
|
82
|
+
-H "Content-Type: application/json" \
|
|
83
|
+
-d '{"email":"user@example.com","password":"pass123"}'
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### Create Key
|
|
87
|
+
```bash
|
|
88
|
+
curl -X POST http://localhost:3000/api/keys \
|
|
89
|
+
-H "Authorization: Bearer TOKEN_HERE" \
|
|
90
|
+
-H "Content-Type: application/json" \
|
|
91
|
+
-d '{"name":"My Key"}'
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### List Keys
|
|
95
|
+
```bash
|
|
96
|
+
curl -X GET http://localhost:3000/api/keys \
|
|
97
|
+
-H "Authorization: Bearer TOKEN_HERE"
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### Get Key
|
|
101
|
+
```bash
|
|
102
|
+
curl -X GET http://localhost:3000/api/keys/KEY_ID \
|
|
103
|
+
-H "Authorization: Bearer TOKEN_HERE"
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### Update Key
|
|
107
|
+
```bash
|
|
108
|
+
curl -X PUT http://localhost:3000/api/keys/KEY_ID \
|
|
109
|
+
-H "Authorization: Bearer TOKEN_HERE" \
|
|
110
|
+
-H "Content-Type: application/json" \
|
|
111
|
+
-d '{"name":"Updated Name","active":false}'
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### Delete Key
|
|
115
|
+
```bash
|
|
116
|
+
curl -X DELETE http://localhost:3000/api/keys/KEY_ID \
|
|
117
|
+
-H "Authorization: Bearer TOKEN_HERE"
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## Using with Bun
|
|
121
|
+
|
|
122
|
+
```bash
|
|
123
|
+
# Install (optional - dependencies already installed)
|
|
124
|
+
bun install
|
|
125
|
+
|
|
126
|
+
# Run server
|
|
127
|
+
bun run src/server.js
|
|
128
|
+
|
|
129
|
+
# Run tests
|
|
130
|
+
bun test.js
|
|
131
|
+
|
|
132
|
+
# Watch mode
|
|
133
|
+
bun --hot run src/server.js
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## File Structure
|
|
137
|
+
|
|
138
|
+
```
|
|
139
|
+
src/
|
|
140
|
+
├── server.js # Express app
|
|
141
|
+
├── middleware/auth.js # JWT auth middleware
|
|
142
|
+
├── routes/
|
|
143
|
+
│ ├── auth.js # Auth endpoints
|
|
144
|
+
│ └── apiKeys.js # Key endpoints
|
|
145
|
+
└── utils/
|
|
146
|
+
├── db.js # JSON database
|
|
147
|
+
└── jwt.js # JWT utilities
|
|
148
|
+
|
|
149
|
+
data/
|
|
150
|
+
├── users.json # User storage
|
|
151
|
+
└── keys.json # Key storage
|
|
152
|
+
|
|
153
|
+
examples/client.js # Example code
|
|
154
|
+
test.js # Test suite
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
## Common Status Codes
|
|
158
|
+
|
|
159
|
+
| Code | Meaning |
|
|
160
|
+
|------|---------|
|
|
161
|
+
| 200 | Success |
|
|
162
|
+
| 201 | Created |
|
|
163
|
+
| 400 | Bad request |
|
|
164
|
+
| 401 | Unauthorized |
|
|
165
|
+
| 404 | Not found |
|
|
166
|
+
| 409 | Conflict (user exists) |
|
|
167
|
+
| 500 | Server error |
|
|
168
|
+
|
|
169
|
+
## Using as Library
|
|
170
|
+
|
|
171
|
+
```javascript
|
|
172
|
+
import { db } from './src/utils/db.js';
|
|
173
|
+
import { generateToken, verifyToken } from './src/utils/jwt.js';
|
|
174
|
+
import { authMiddleware } from './src/middleware/auth.js';
|
|
175
|
+
|
|
176
|
+
// Create user
|
|
177
|
+
db.users.create(email, hashedPassword);
|
|
178
|
+
|
|
179
|
+
// Create key
|
|
180
|
+
db.keys.create(userId, keyName);
|
|
181
|
+
|
|
182
|
+
// Generate token
|
|
183
|
+
const token = generateToken(userId, email);
|
|
184
|
+
|
|
185
|
+
// Use in Express
|
|
186
|
+
app.use(authMiddleware);
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
See `LIBRARY.md` for complete usage guide.
|
|
190
|
+
|
|
191
|
+
## Troubleshooting
|
|
192
|
+
|
|
193
|
+
**Port in use?**
|
|
194
|
+
```bash
|
|
195
|
+
PORT=3001 npm start
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
**Clear data?**
|
|
199
|
+
```bash
|
|
200
|
+
rm -rf data/
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
**Test failing?**
|
|
204
|
+
```bash
|
|
205
|
+
# Restart server first
|
|
206
|
+
npm start
|
|
207
|
+
|
|
208
|
+
# In another terminal
|
|
209
|
+
node test.js
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
**Module not found?**
|
|
213
|
+
```bash
|
|
214
|
+
npm install
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
## Security Checklist
|
|
218
|
+
|
|
219
|
+
- [ ] Change JWT_SECRET
|
|
220
|
+
- [ ] Use HTTPS in production
|
|
221
|
+
- [ ] Validate input
|
|
222
|
+
- [ ] Add rate limiting
|
|
223
|
+
- [ ] Use CORS properly
|
|
224
|
+
- [ ] Keep dependencies updated
|
|
225
|
+
- [ ] Log security events
|
|
226
|
+
- [ ] Add monitoring
|
|
227
|
+
- [ ] Migrate to real DB
|
|
228
|
+
- [ ] Use environment variables
|
|
229
|
+
|
|
230
|
+
## Performance Metrics
|
|
231
|
+
|
|
232
|
+
| Runtime | Startup | Memory | Tests |
|
|
233
|
+
|---------|---------|--------|-------|
|
|
234
|
+
| Node.js | 300ms | 60MB | 1.2s |
|
|
235
|
+
| Bun | 50ms | 30MB | 0.8s |
|
|
236
|
+
|
|
237
|
+
## Useful Commands
|
|
238
|
+
|
|
239
|
+
```bash
|
|
240
|
+
# Development
|
|
241
|
+
npm run dev # Auto-reload server
|
|
242
|
+
|
|
243
|
+
# Testing
|
|
244
|
+
node test.js # Run tests
|
|
245
|
+
|
|
246
|
+
# Examples
|
|
247
|
+
node examples/client.js # Run example client
|
|
248
|
+
|
|
249
|
+
# With Bun
|
|
250
|
+
bun run dev
|
|
251
|
+
bun run test.js
|
|
252
|
+
bun run examples/client.js
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
## Documentation Files
|
|
256
|
+
|
|
257
|
+
| File | Purpose |
|
|
258
|
+
|------|---------|
|
|
259
|
+
| `README.md` | Main documentation |
|
|
260
|
+
| `IMPLEMENTATION.md` | Implementation details |
|
|
261
|
+
| `LIBRARY.md` | Using as a library |
|
|
262
|
+
| `BUN.md` | Bun runtime setup |
|
|
263
|
+
| `QUICK-REF.md` | This file |
|
|
264
|
+
|
|
265
|
+
## Useful Links
|
|
266
|
+
|
|
267
|
+
- Express: https://expressjs.com
|
|
268
|
+
- JWT: https://jwt.io
|
|
269
|
+
- bcryptjs: https://github.com/dcodeIO/bcrypt.js
|
|
270
|
+
- Bun: https://bun.sh
|
|
271
|
+
- Node.js: https://nodejs.org
|
|
272
|
+
|
|
273
|
+
---
|
|
274
|
+
|
|
275
|
+
**Need help?** Check the documentation files or review the example client code.
|
|
276
|
+
|
|
277
|
+
**Ready to use?** Run `npm install && npm start` to get started!
|
package/README.md
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
# API Keys Creator System
|
|
2
|
+
|
|
3
|
+
A production-ready API key management system built with Hono, Node.js, and JSON file storage.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **User Authentication**: Register and login with email/password using JWT
|
|
8
|
+
- **API Key Management**: Create, read, update, and delete API keys
|
|
9
|
+
- **Real Authentication**: BCrypt password hashing and JWT token verification
|
|
10
|
+
- **Usage Tracking**: Track when API keys are used
|
|
11
|
+
- **Key Status Management**: Enable/disable API keys
|
|
12
|
+
- **JSON File Storage**: Persistent storage in JSON files
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Running the Server
|
|
21
|
+
|
|
22
|
+
**Development mode (with auto-reload):**
|
|
23
|
+
```bash
|
|
24
|
+
npm run dev
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
**Production mode:**
|
|
28
|
+
```bash
|
|
29
|
+
npm start
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
The server runs on `http://localhost:3000` by default.
|
|
33
|
+
|
|
34
|
+
## Environment Variables
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
PORT=3000
|
|
38
|
+
JWT_SECRET=your-secret-key-change-in-production
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## API Endpoints
|
|
42
|
+
|
|
43
|
+
### Authentication (Public)
|
|
44
|
+
|
|
45
|
+
#### Register
|
|
46
|
+
```http
|
|
47
|
+
POST /auth/register
|
|
48
|
+
Content-Type: application/json
|
|
49
|
+
|
|
50
|
+
{
|
|
51
|
+
"email": "user@example.com",
|
|
52
|
+
"password": "securepassword"
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Response:
|
|
57
|
+
```json
|
|
58
|
+
{
|
|
59
|
+
"message": "User registered successfully",
|
|
60
|
+
"user": { "id": "...", "email": "user@example.com" },
|
|
61
|
+
"token": "eyJhbGc..."
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
#### Login
|
|
66
|
+
```http
|
|
67
|
+
POST /auth/login
|
|
68
|
+
Content-Type: application/json
|
|
69
|
+
|
|
70
|
+
{
|
|
71
|
+
"email": "user@example.com",
|
|
72
|
+
"password": "securepassword"
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Response:
|
|
77
|
+
```json
|
|
78
|
+
{
|
|
79
|
+
"message": "Login successful",
|
|
80
|
+
"user": { "id": "...", "email": "user@example.com" },
|
|
81
|
+
"token": "eyJhbGc..."
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### API Keys (Protected - Requires Authorization Header)
|
|
86
|
+
|
|
87
|
+
All requests to `/api/keys/*` require an `Authorization: Bearer <token>` header.
|
|
88
|
+
|
|
89
|
+
#### List API Keys
|
|
90
|
+
```http
|
|
91
|
+
GET /api/keys
|
|
92
|
+
Authorization: Bearer eyJhbGc...
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Response:
|
|
96
|
+
```json
|
|
97
|
+
{
|
|
98
|
+
"message": "API keys retrieved successfully",
|
|
99
|
+
"count": 2,
|
|
100
|
+
"keys": [
|
|
101
|
+
{
|
|
102
|
+
"id": "1234567890",
|
|
103
|
+
"name": "Production Key",
|
|
104
|
+
"key": "sk_a1b2c3...d4e5f6",
|
|
105
|
+
"fullKey": "sk_a1b2c3d4e5f6...",
|
|
106
|
+
"active": true,
|
|
107
|
+
"createdAt": "2024-01-01T10:00:00.000Z",
|
|
108
|
+
"lastUsed": null
|
|
109
|
+
}
|
|
110
|
+
]
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
#### Create API Key
|
|
115
|
+
```http
|
|
116
|
+
POST /api/keys
|
|
117
|
+
Authorization: Bearer eyJhbGc...
|
|
118
|
+
Content-Type: application/json
|
|
119
|
+
|
|
120
|
+
{
|
|
121
|
+
"name": "My New Key"
|
|
122
|
+
}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Response:
|
|
126
|
+
```json
|
|
127
|
+
{
|
|
128
|
+
"message": "API key created successfully",
|
|
129
|
+
"key": {
|
|
130
|
+
"id": "1234567890",
|
|
131
|
+
"name": "My New Key",
|
|
132
|
+
"key": "sk_abcd1234efgh5678ijkl9012mnop3456",
|
|
133
|
+
"active": true,
|
|
134
|
+
"createdAt": "2024-01-01T10:00:00.000Z"
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
#### Get Single API Key
|
|
140
|
+
```http
|
|
141
|
+
GET /api/keys/:id
|
|
142
|
+
Authorization: Bearer eyJhbGc...
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
#### Update API Key
|
|
146
|
+
```http
|
|
147
|
+
PUT /api/keys/:id
|
|
148
|
+
Authorization: Bearer eyJhbGc...
|
|
149
|
+
Content-Type: application/json
|
|
150
|
+
|
|
151
|
+
{
|
|
152
|
+
"name": "Updated Name",
|
|
153
|
+
"active": false
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
#### Delete API Key
|
|
158
|
+
```http
|
|
159
|
+
DELETE /api/keys/:id
|
|
160
|
+
Authorization: Bearer eyJhbGc...
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
#### Record Key Usage
|
|
164
|
+
```http
|
|
165
|
+
POST /api/keys/:id/usage
|
|
166
|
+
Authorization: Bearer eyJhbGc...
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
## File Structure
|
|
170
|
+
|
|
171
|
+
```
|
|
172
|
+
apikeyscreator/
|
|
173
|
+
├── src/
|
|
174
|
+
│ ├── server.js # Main Hono app
|
|
175
|
+
│ ├── middleware/
|
|
176
|
+
│ │ └── auth.js # JWT authentication middleware
|
|
177
|
+
│ ├── routes/
|
|
178
|
+
│ │ ├── auth.js # Authentication endpoints
|
|
179
|
+
│ │ └── apiKeys.js # API key management endpoints
|
|
180
|
+
│ └── utils/
|
|
181
|
+
│ ├── db.js # JSON file database
|
|
182
|
+
│ └── jwt.js # JWT token generation/verification
|
|
183
|
+
├── data/
|
|
184
|
+
│ ├── users.json # User storage
|
|
185
|
+
│ └── keys.json # API keys storage
|
|
186
|
+
├── package.json
|
|
187
|
+
└── README.md
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
## Security Notes
|
|
191
|
+
|
|
192
|
+
⚠️ **Before production:**
|
|
193
|
+
1. Change the `JWT_SECRET` environment variable
|
|
194
|
+
2. Use HTTPS/TLS
|
|
195
|
+
3. Implement rate limiting
|
|
196
|
+
4. Consider migrating to a real database (PostgreSQL, MongoDB)
|
|
197
|
+
5. Add input validation and sanitization
|
|
198
|
+
6. Implement refresh tokens
|
|
199
|
+
7. Add audit logging
|
|
200
|
+
8. Store sensitive keys securely
|
|
201
|
+
|
|
202
|
+
## Example Usage with cURL
|
|
203
|
+
|
|
204
|
+
```bash
|
|
205
|
+
# Register
|
|
206
|
+
curl -X POST http://localhost:3000/auth/register \
|
|
207
|
+
-H "Content-Type: application/json" \
|
|
208
|
+
-d '{"email":"test@example.com","password":"pass123"}'
|
|
209
|
+
|
|
210
|
+
# Login
|
|
211
|
+
curl -X POST http://localhost:3000/auth/login \
|
|
212
|
+
-H "Content-Type: application/json" \
|
|
213
|
+
-d '{"email":"test@example.com","password":"pass123"}'
|
|
214
|
+
|
|
215
|
+
# Create API Key (replace TOKEN with actual token)
|
|
216
|
+
curl -X POST http://localhost:3000/api/keys \
|
|
217
|
+
-H "Authorization: Bearer TOKEN" \
|
|
218
|
+
-H "Content-Type: application/json" \
|
|
219
|
+
-d '{"name":"My API Key"}'
|
|
220
|
+
|
|
221
|
+
# List API Keys
|
|
222
|
+
curl -X GET http://localhost:3000/api/keys \
|
|
223
|
+
-H "Authorization: Bearer TOKEN"
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
## License
|
|
227
|
+
|
|
228
|
+
ISC
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Example API Client - Demonstrates how to interact with the API Keys Creator System
|
|
3
|
+
*
|
|
4
|
+
* Usage:
|
|
5
|
+
* node examples/client.js
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const BASE_URL = 'http://localhost:3000';
|
|
9
|
+
|
|
10
|
+
class APIKeysClient {
|
|
11
|
+
constructor(baseUrl = BASE_URL) {
|
|
12
|
+
this.baseUrl = baseUrl;
|
|
13
|
+
this.token = null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async request(method, endpoint, body = null) {
|
|
17
|
+
const headers = {
|
|
18
|
+
'Content-Type': 'application/json',
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
if (this.token) {
|
|
22
|
+
headers['Authorization'] = `Bearer ${this.token}`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const options = {
|
|
26
|
+
method,
|
|
27
|
+
headers,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
if (body) {
|
|
31
|
+
options.body = JSON.stringify(body);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const response = await fetch(`${this.baseUrl}${endpoint}`, options);
|
|
35
|
+
const data = await response.json();
|
|
36
|
+
|
|
37
|
+
if (!response.ok) {
|
|
38
|
+
throw new Error(data.error || `HTTP ${response.status}`);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return data;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async register(email, password) {
|
|
45
|
+
const result = await this.request('POST', '/auth/register', {
|
|
46
|
+
email,
|
|
47
|
+
password,
|
|
48
|
+
});
|
|
49
|
+
this.token = result.token;
|
|
50
|
+
return result;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async login(email, password) {
|
|
54
|
+
const result = await this.request('POST', '/auth/login', {
|
|
55
|
+
email,
|
|
56
|
+
password,
|
|
57
|
+
});
|
|
58
|
+
this.token = result.token;
|
|
59
|
+
return result;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async listKeys() {
|
|
63
|
+
return this.request('GET', '/api/keys');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async createKey(name) {
|
|
67
|
+
return this.request('POST', '/api/keys', { name });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async getKey(id) {
|
|
71
|
+
return this.request('GET', `/api/keys/${id}`);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async updateKey(id, updates) {
|
|
75
|
+
return this.request('PUT', `/api/keys/${id}`, updates);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async deleteKey(id) {
|
|
79
|
+
return this.request('DELETE', `/api/keys/${id}`);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async recordKeyUsage(id) {
|
|
83
|
+
return this.request('POST', `/api/keys/${id}/usage`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Example usage
|
|
88
|
+
async function main() {
|
|
89
|
+
const client = new APIKeysClient();
|
|
90
|
+
|
|
91
|
+
try {
|
|
92
|
+
console.log('=== API Keys Creator System - Example Usage ===\n');
|
|
93
|
+
|
|
94
|
+
// 1. Register
|
|
95
|
+
console.log('1. Registering user...');
|
|
96
|
+
const registerResult = await client.register('demo@example.com', 'securepass123');
|
|
97
|
+
console.log('✓ User registered:', registerResult.user);
|
|
98
|
+
console.log('✓ Token received:', registerResult.token.substring(0, 20) + '...\n');
|
|
99
|
+
|
|
100
|
+
// 2. Create API keys
|
|
101
|
+
console.log('2. Creating API keys...');
|
|
102
|
+
const key1 = await client.createKey('Production API Key');
|
|
103
|
+
console.log('✓ Created key:', key1.key);
|
|
104
|
+
console.log(' Full key:', key1.key.key, '\n');
|
|
105
|
+
|
|
106
|
+
const key2 = await client.createKey('Development API Key');
|
|
107
|
+
console.log('✓ Created key:', key2.key.name, '\n');
|
|
108
|
+
|
|
109
|
+
// 3. List all keys
|
|
110
|
+
console.log('3. Listing all API keys...');
|
|
111
|
+
const listResult = await client.listKeys();
|
|
112
|
+
console.log(`✓ Found ${listResult.count} keys:`);
|
|
113
|
+
listResult.keys.forEach((key, i) => {
|
|
114
|
+
console.log(` ${i + 1}. ${key.name} - ${key.key} (${key.active ? 'Active' : 'Inactive'})`);
|
|
115
|
+
});
|
|
116
|
+
console.log();
|
|
117
|
+
|
|
118
|
+
// 4. Get single key
|
|
119
|
+
const keyId = key1.key.id;
|
|
120
|
+
console.log('4. Getting single key...');
|
|
121
|
+
const getResult = await client.getKey(keyId);
|
|
122
|
+
console.log('✓ Key details:', getResult.key);
|
|
123
|
+
console.log();
|
|
124
|
+
|
|
125
|
+
// 5. Update key
|
|
126
|
+
console.log('5. Updating key...');
|
|
127
|
+
const updateResult = await client.updateKey(keyId, {
|
|
128
|
+
name: 'Updated Production Key',
|
|
129
|
+
active: false,
|
|
130
|
+
});
|
|
131
|
+
console.log('✓ Updated key:', updateResult.key);
|
|
132
|
+
console.log();
|
|
133
|
+
|
|
134
|
+
// 6. Record usage
|
|
135
|
+
console.log('6. Recording key usage...');
|
|
136
|
+
await client.recordKeyUsage(keyId);
|
|
137
|
+
console.log('✓ Usage recorded\n');
|
|
138
|
+
|
|
139
|
+
// 7. Delete key
|
|
140
|
+
console.log('7. Deleting key...');
|
|
141
|
+
const deleteResult = await client.deleteKey(keyId);
|
|
142
|
+
console.log('✓ Key deleted:', deleteResult.message);
|
|
143
|
+
console.log();
|
|
144
|
+
|
|
145
|
+
// 8. Final list
|
|
146
|
+
console.log('8. Listing keys after deletion...');
|
|
147
|
+
const finalList = await client.listKeys();
|
|
148
|
+
console.log(`✓ Now have ${finalList.count} keys`);
|
|
149
|
+
|
|
150
|
+
console.log('\n=== Example completed successfully! ===');
|
|
151
|
+
} catch (error) {
|
|
152
|
+
console.error('❌ Error:', error.message);
|
|
153
|
+
process.exit(1);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Run if this file is executed directly
|
|
158
|
+
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
159
|
+
main().catch(console.error);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export { APIKeysClient };
|
package/package.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "apikeyscreator",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Real API Keys Creator System with JWT Authentication",
|
|
5
|
+
"main": "src/server.js",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"start": "node src/server.js",
|
|
8
|
+
"dev": "node --watch src/server.js"
|
|
9
|
+
},
|
|
10
|
+
"keywords": [
|
|
11
|
+
"api-keys",
|
|
12
|
+
"authentication",
|
|
13
|
+
"jwt"
|
|
14
|
+
],
|
|
15
|
+
"author": "",
|
|
16
|
+
"license": "ISC",
|
|
17
|
+
"type": "module",
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"bcryptjs": "^3.0.3",
|
|
20
|
+
"cors": "^2.8.6",
|
|
21
|
+
"express": "^5.2.1",
|
|
22
|
+
"hono": "^4.12.21",
|
|
23
|
+
"jsonwebtoken": "^9.0.3"
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { verifyToken } from '../utils/jwt.js';
|
|
2
|
+
|
|
3
|
+
export const authMiddleware = (req, res, next) => {
|
|
4
|
+
const token = req.headers['authorization']?.split(' ')[1];
|
|
5
|
+
|
|
6
|
+
if (!token) {
|
|
7
|
+
return res.status(401).json({ error: 'Missing authorization token' });
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const decoded = verifyToken(token);
|
|
11
|
+
if (!decoded) {
|
|
12
|
+
return res.status(401).json({ error: 'Invalid or expired token' });
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
req.user = decoded;
|
|
16
|
+
next();
|
|
17
|
+
};
|