mbkbucket 3.3.2 → 3.4.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/README.md +17 -24
- package/lib/cli.js +20 -20
- package/lib/src/cli/auth-helper.js +20 -14
- package/lib/src/config/index.js +1 -4
- package/lib/src/middleware/error-handler.js +36 -8
- package/lib/src/routes/api.routes.js +1 -1
- package/lib/src/routes/index.js +1 -1
- package/lib/src/routes/view.routes.js +1 -1
- package/lib/src/utils/errors.js +10 -1
- package/package.json +8 -5
package/README.md
CHANGED
|
@@ -37,14 +37,7 @@ npm install mbkbucket
|
|
|
37
37
|
### As a Library
|
|
38
38
|
|
|
39
39
|
```js
|
|
40
|
-
import {
|
|
41
|
-
uploadFile,
|
|
42
|
-
downloadFile,
|
|
43
|
-
listfiles,
|
|
44
|
-
deleteFile,
|
|
45
|
-
deleteFolder,
|
|
46
|
-
getFileMetadata,
|
|
47
|
-
generateSignedUrl,
|
|
40
|
+
import { uploadFile, downloadFile, listfiles, deleteFile, deleteFolder, getFileMetadata, generateSignedUrl,
|
|
48
41
|
bucket, // Express router
|
|
49
42
|
packageJson // Package metadata
|
|
50
43
|
} from 'mbkbucket';
|
|
@@ -82,7 +75,7 @@ mbkbucket.listen(3004, () => {
|
|
|
82
75
|
```
|
|
83
76
|
|
|
84
77
|
The Express app includes:
|
|
85
|
-
- **`/mbkbucket`** — Admin dashboard (
|
|
78
|
+
- **`/mbkbucket`** — Admin dashboard (superadmin only)
|
|
86
79
|
- **`/mbkbucket/api/*`** — REST API for file operations
|
|
87
80
|
- **`/mbkbucket/p_view/:key(*)`** — Public file view
|
|
88
81
|
- **`/mbkbucket/info`** — Health & config info
|
|
@@ -225,23 +218,23 @@ All functions are exported from the package root. Full TypeScript declarations i
|
|
|
225
218
|
|
|
226
219
|
| Route | Auth | Description |
|
|
227
220
|
|---|---|---|
|
|
228
|
-
| `GET /mbkbucket` |
|
|
221
|
+
| `GET /mbkbucket` | superadmin | Admin dashboard |
|
|
229
222
|
| `GET /mbkbucket/info` | Any | Health check & config info |
|
|
230
223
|
| `GET /mbkbucket/p_view/:key(*)` | Public | Public file viewer |
|
|
231
|
-
| `POST /mbkbucket/api/list` |
|
|
232
|
-
| `POST /mbkbucket/api/upload` |
|
|
233
|
-
| `POST /mbkbucket/api/delete` |
|
|
234
|
-
| `POST /mbkbucket/api/delete-folder` |
|
|
235
|
-
| `POST /mbkbucket/api/create-folder` |
|
|
236
|
-
| `POST /mbkbucket/api/rename` |
|
|
237
|
-
| `GET /mbkbucket/api/download/:key(*)` |
|
|
238
|
-
| `GET /mbkbucket/api/metadata/:key(*)` |
|
|
239
|
-
| `POST /mbkbucket/api/multipart/init` |
|
|
240
|
-
| `POST /mbkbucket/api/multipart/part` |
|
|
241
|
-
| `POST /mbkbucket/api/multipart/complete` |
|
|
242
|
-
| `POST /mbkbucket/api/multipart/abort` |
|
|
243
|
-
| `GET /mbkbucket/api/multipart/list` |
|
|
244
|
-
| `POST /mbkbucket/api/multipart/cleanup` |
|
|
224
|
+
| `POST /mbkbucket/api/list` | superadmin | List files (JSON) |
|
|
225
|
+
| `POST /mbkbucket/api/upload` | superadmin | Upload file(s) |
|
|
226
|
+
| `POST /mbkbucket/api/delete` | superadmin | Delete file(s) |
|
|
227
|
+
| `POST /mbkbucket/api/delete-folder` | superadmin | Delete folder |
|
|
228
|
+
| `POST /mbkbucket/api/create-folder` | superadmin | Create folder marker |
|
|
229
|
+
| `POST /mbkbucket/api/rename` | superadmin | Rename/move a file |
|
|
230
|
+
| `GET /mbkbucket/api/download/:key(*)` | superadmin | Download a file |
|
|
231
|
+
| `GET /mbkbucket/api/metadata/:key(*)` | superadmin | Get file metadata |
|
|
232
|
+
| `POST /mbkbucket/api/multipart/init` | superadmin | Init multipart upload |
|
|
233
|
+
| `POST /mbkbucket/api/multipart/part` | superadmin | Upload multipart chunk |
|
|
234
|
+
| `POST /mbkbucket/api/multipart/complete` | superadmin | Complete multipart |
|
|
235
|
+
| `POST /mbkbucket/api/multipart/abort` | superadmin | Abort multipart |
|
|
236
|
+
| `GET /mbkbucket/api/multipart/list` | superadmin | List incomplete uploads |
|
|
237
|
+
| `POST /mbkbucket/api/multipart/cleanup` | superadmin | Clean up stale uploads |
|
|
245
238
|
|
|
246
239
|
### Views
|
|
247
240
|
|
package/lib/cli.js
CHANGED
|
@@ -133,39 +133,39 @@ function promptLine() {
|
|
|
133
133
|
|
|
134
134
|
async function cmdLogin() {
|
|
135
135
|
const storedCfg = readConfig();
|
|
136
|
-
let
|
|
136
|
+
let server_url = findFlag('server') || storedCfg.server_url;
|
|
137
137
|
|
|
138
|
-
if (!
|
|
139
|
-
console.error('❌ --server <url> is required for login.\n Example: mbkbucket login --server https://myapp.example.com\n\n💡 Tip: Set it once with:\n mbkbucket config set
|
|
138
|
+
if (!server_url || typeof server_url !== 'string') {
|
|
139
|
+
console.error('❌ --server <url> is required for login.\n Example: mbkbucket login --server https://myapp.example.com\n\n💡 Tip: Set it once with:\n mbkbucket config set server_url https://your-server.com\n Then just run: mbkbucket login');
|
|
140
140
|
process.exit(1);
|
|
141
141
|
}
|
|
142
142
|
|
|
143
|
-
const
|
|
144
|
-
updateConfig({
|
|
143
|
+
const profile_key = findFlag('profile-key') || storedCfg.profile_key;
|
|
144
|
+
updateConfig({ server_url });
|
|
145
145
|
|
|
146
146
|
try {
|
|
147
147
|
const result = await deviceFlowLogin({
|
|
148
|
-
|
|
149
|
-
|
|
148
|
+
server_url,
|
|
149
|
+
profile_key: typeof profile_key === 'string' ? profile_key : undefined,
|
|
150
150
|
});
|
|
151
151
|
|
|
152
152
|
updateConfig({
|
|
153
153
|
token: result.token,
|
|
154
|
-
|
|
154
|
+
token_prefix: result.token_prefix,
|
|
155
155
|
username: result.username,
|
|
156
|
-
|
|
156
|
+
server_url,
|
|
157
157
|
profile: result.profile || null,
|
|
158
|
-
|
|
158
|
+
logged_in_at: nowIso(),
|
|
159
159
|
});
|
|
160
160
|
|
|
161
161
|
console.log('\n✅ Credentials saved. You are now logged in.\n Run "mbkbucket whoami" to verify.');
|
|
162
162
|
} catch (err) {
|
|
163
163
|
const msg = err.message || '';
|
|
164
164
|
console.error(`❌ Login failed: ${msg}`);
|
|
165
|
-
if (msg.includes('
|
|
165
|
+
if (msg.includes('profile_key') || msg.includes('profile_id')) {
|
|
166
166
|
console.error('\n💡 An API token profile is required. Create one in mbkauthe admin panel and pass --profile-key.');
|
|
167
167
|
} else if (msg.includes('fetch') || msg.includes('ECONNREFUSED') || msg.includes('ENOTFOUND')) {
|
|
168
|
-
console.error(`\n💡 Could not reach server "${
|
|
168
|
+
console.error(`\n💡 Could not reach server "${server_url}". Verify it is running and CLI_AUTH_ENABLED=true.`);
|
|
169
169
|
}
|
|
170
170
|
process.exit(1);
|
|
171
171
|
}
|
|
@@ -182,10 +182,10 @@ function cmdWhoami() {
|
|
|
182
182
|
if (!isLoggedIn()) return console.log('ℹ️ Not logged in. Run "mbkbucket login --server <url>" to authenticate.');
|
|
183
183
|
const cfg = readConfig();
|
|
184
184
|
console.log(`✅ Logged in as: ${cfg.username}`);
|
|
185
|
-
console.log(` Server: ${cfg.
|
|
186
|
-
console.log(` Token: ${cfg.
|
|
185
|
+
console.log(` Server: ${cfg.server_url}`);
|
|
186
|
+
console.log(` Token: ${cfg.token_prefix}...`);
|
|
187
187
|
if (cfg.profile) console.log(` Profile: ${cfg.profile.name} (scope: ${cfg.profile.scope || 'full'})`);
|
|
188
|
-
console.log(` Since: ${formatDate(cfg.
|
|
188
|
+
console.log(` Since: ${formatDate(cfg.logged_in_at)}`);
|
|
189
189
|
}
|
|
190
190
|
|
|
191
191
|
async function cmdList() {
|
|
@@ -462,14 +462,14 @@ async function cmdSignedUrl() {
|
|
|
462
462
|
// ---------------------------------------------------------------------------
|
|
463
463
|
const DEMO_CONFIG = {
|
|
464
464
|
token: 'mbk_demo_token_replace_with_real_one_from_login',
|
|
465
|
-
|
|
465
|
+
token_prefix: 'mbk_demo',
|
|
466
466
|
username: 'demo-user',
|
|
467
|
-
|
|
468
|
-
profile: { name: 'Default CLI Profile', scope: 'read-write',
|
|
469
|
-
|
|
467
|
+
server_url: 'https://your-app.example.com',
|
|
468
|
+
profile: { name: 'Default CLI Profile', scope: 'read-write', allowed_apps: ['mbkbucket'] },
|
|
469
|
+
logged_in_at: nowIso(),
|
|
470
470
|
};
|
|
471
471
|
|
|
472
|
-
const VALID_CONFIG_KEYS = ['token', '
|
|
472
|
+
const VALID_CONFIG_KEYS = ['token', 'token_prefix', 'username', 'server_url', 'profile', 'profile_key', 'logged_in_at'];
|
|
473
473
|
|
|
474
474
|
async function cmdConfig() {
|
|
475
475
|
const [sub, key, value] = cmdArgs;
|
|
@@ -52,8 +52,8 @@ export function updateConfig(partial) {
|
|
|
52
52
|
}
|
|
53
53
|
|
|
54
54
|
export function isLoggedIn() {
|
|
55
|
-
const { token,
|
|
56
|
-
return Boolean(token &&
|
|
55
|
+
const { token, server_url } = readConfig();
|
|
56
|
+
return Boolean(token && server_url);
|
|
57
57
|
}
|
|
58
58
|
|
|
59
59
|
export function getStoredToken() {
|
|
@@ -61,11 +61,11 @@ export function getStoredToken() {
|
|
|
61
61
|
}
|
|
62
62
|
|
|
63
63
|
export function getStoredServerUrl() {
|
|
64
|
-
return readConfig().
|
|
64
|
+
return readConfig().server_url || null;
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
-
export async function deviceFlowLogin({
|
|
68
|
-
const baseUrl = String(
|
|
67
|
+
export async function deviceFlowLogin({ server_url, profile_key }) {
|
|
68
|
+
const baseUrl = String(server_url).replace(/\/+$/, '');
|
|
69
69
|
console.log(`🔑 Requesting device login from ${baseUrl} ...`);
|
|
70
70
|
|
|
71
71
|
let deviceResp;
|
|
@@ -74,8 +74,8 @@ export async function deviceFlowLogin({ serverUrl, profileKey }) {
|
|
|
74
74
|
method: 'POST',
|
|
75
75
|
headers: { 'Content-Type': 'application/json' },
|
|
76
76
|
body: JSON.stringify({
|
|
77
|
-
|
|
78
|
-
...(
|
|
77
|
+
client_name: `mbkbucket-cli-${os.hostname()}`,
|
|
78
|
+
...(profile_key && { profile_key }),
|
|
79
79
|
}),
|
|
80
80
|
});
|
|
81
81
|
deviceResp = await res.json();
|
|
@@ -87,19 +87,24 @@ export async function deviceFlowLogin({ serverUrl, profileKey }) {
|
|
|
87
87
|
throw err;
|
|
88
88
|
}
|
|
89
89
|
|
|
90
|
-
const
|
|
90
|
+
const verification_url = deviceResp.verification_url;
|
|
91
|
+
const user_code = deviceResp.user_code;
|
|
92
|
+
const device_code = deviceResp.device_code;
|
|
93
|
+
const expires_in = deviceResp.expires_in;
|
|
94
|
+
const interval = deviceResp.interval;
|
|
95
|
+
const profile = deviceResp.profile;
|
|
91
96
|
|
|
92
97
|
console.log('\n┌─────────────────────────────────────────────────────────┐');
|
|
93
98
|
console.log('│ │');
|
|
94
99
|
console.log('│ 🌐 Open this URL in your browser to approve: │');
|
|
95
|
-
console.log(`│ ${
|
|
100
|
+
console.log(`│ ${(verification_url || '').padEnd(53)}│`);
|
|
96
101
|
console.log('│ │');
|
|
97
|
-
console.log(`│ 🔢 Or enter this code: ${
|
|
102
|
+
console.log(`│ 🔢 Or enter this code: ${(user_code || '').padEnd(30)}│`);
|
|
98
103
|
console.log('│ │');
|
|
99
104
|
console.log('└─────────────────────────────────────────────────────────┘\n');
|
|
100
105
|
|
|
101
106
|
if (profile) console.log(` Profile: ${profile.name} (scope: ${profile.scope || 'full'})`);
|
|
102
|
-
console.log(` Waiting for approval (expires in ${Math.floor(
|
|
107
|
+
console.log(` Waiting for approval (expires in ${Math.floor((expires_in || 900) / 60)} minutes)...\n`);
|
|
103
108
|
|
|
104
109
|
const pollInterval = (interval || 5) * 1000;
|
|
105
110
|
const deadline = Date.now() + MAX_POLL_TIME_MS;
|
|
@@ -113,17 +118,18 @@ export async function deviceFlowLogin({ serverUrl, profileKey }) {
|
|
|
113
118
|
const pollRes = await fetch(`${baseUrl}/api/cli/device/token`, {
|
|
114
119
|
method: 'POST',
|
|
115
120
|
headers: { 'Content-Type': 'application/json' },
|
|
116
|
-
body: JSON.stringify({
|
|
121
|
+
body: JSON.stringify({ device_code }),
|
|
117
122
|
});
|
|
118
123
|
|
|
119
124
|
const pollBody = await pollRes.json();
|
|
120
125
|
|
|
121
126
|
if (pollBody.status === 'approved' && pollBody.success) {
|
|
127
|
+
const token_prefix = pollBody.token_prefix || '';
|
|
122
128
|
console.log(`✅ Login approved! Welcome, ${pollBody.username}.`);
|
|
123
|
-
console.log(` Token prefix: ${
|
|
129
|
+
console.log(` Token prefix: ${token_prefix}...`);
|
|
124
130
|
return {
|
|
125
131
|
token: pollBody.token,
|
|
126
|
-
|
|
132
|
+
token_prefix: token_prefix,
|
|
127
133
|
username: pollBody.username,
|
|
128
134
|
profile: profile || null,
|
|
129
135
|
};
|
package/lib/src/config/index.js
CHANGED
|
@@ -1,11 +1,26 @@
|
|
|
1
1
|
import { createLogger } from "#logger";
|
|
2
|
+
import { isJsonRequest, sendError, sanitizeErrorDetails } from "mbkauthe";
|
|
2
3
|
|
|
3
4
|
const debugServer = createLogger('server');
|
|
4
5
|
|
|
5
6
|
const BASE_ERROR_DATA = { layout: false, pagename: "Home", page: "/" };
|
|
6
7
|
|
|
7
|
-
export function notFoundHandler(req, res) {
|
|
8
|
+
export function notFoundHandler(req, res, next) {
|
|
9
|
+
const url = req.originalUrl || req.url || '';
|
|
10
|
+
if (!url.startsWith('/mbkbucket') && typeof next === 'function') {
|
|
11
|
+
return next();
|
|
12
|
+
}
|
|
13
|
+
|
|
8
14
|
debugServer("Path not found: %s %s", req.method, req.url);
|
|
15
|
+
|
|
16
|
+
if (isJsonRequest(req)) {
|
|
17
|
+
return sendError(res, "The requested API route was not found.", {
|
|
18
|
+
statusCode: 404,
|
|
19
|
+
code: "ROUTE_NOT_FOUND",
|
|
20
|
+
req,
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
9
24
|
return res.status(404).render("Error/dError.handlebars", {
|
|
10
25
|
...BASE_ERROR_DATA,
|
|
11
26
|
code: 404,
|
|
@@ -14,13 +29,26 @@ export function notFoundHandler(req, res) {
|
|
|
14
29
|
});
|
|
15
30
|
}
|
|
16
31
|
|
|
17
|
-
export function globalErrorHandler(err,
|
|
18
|
-
console.error(`[mbkbucket] ${err.stack}`);
|
|
19
|
-
|
|
32
|
+
export function globalErrorHandler(err, req, res, _next) {
|
|
33
|
+
console.error(`[mbkbucket] ${err.stack || err}`);
|
|
34
|
+
|
|
35
|
+
const statusCode = Number(err.status || err.statusCode || 500);
|
|
36
|
+
|
|
37
|
+
if (isJsonRequest(req)) {
|
|
38
|
+
return sendError(res, err, {
|
|
39
|
+
statusCode,
|
|
40
|
+
req,
|
|
41
|
+
details: process.env.NODE_ENV !== 'production' ? err.stack : undefined,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const sanitizedDetails = err.message ? sanitizeErrorDetails(err.message) : undefined;
|
|
46
|
+
|
|
47
|
+
return res.status(statusCode).render("Error/dError.handlebars", {
|
|
20
48
|
...BASE_ERROR_DATA,
|
|
21
|
-
code:
|
|
22
|
-
error: "Internal app Error",
|
|
23
|
-
message: "An unexpected error occurred on the app.",
|
|
24
|
-
details:
|
|
49
|
+
code: statusCode,
|
|
50
|
+
error: statusCode >= 500 ? "Internal app Error" : (err.name || "Client Error"),
|
|
51
|
+
message: err.message || "An unexpected error occurred on the app.",
|
|
52
|
+
...(sanitizedDetails ? { details: sanitizedDetails } : {}),
|
|
25
53
|
});
|
|
26
54
|
}
|
package/lib/src/routes/index.js
CHANGED
|
@@ -8,7 +8,7 @@ import apiRoutes from "./api.routes.js";
|
|
|
8
8
|
|
|
9
9
|
const router = express.Router();
|
|
10
10
|
|
|
11
|
-
router.get('/mbkbucket', sessRole('
|
|
11
|
+
router.get('/mbkbucket', sessRole('superadmin'), renderBucketDashboard);
|
|
12
12
|
router.use('/mbkbucket', bucketResolver, infoRoutes, viewRoutes, apiRoutes);
|
|
13
13
|
|
|
14
14
|
export default router;
|
|
@@ -7,7 +7,7 @@ import { pviewSecurity } from "../middleware/security.js";
|
|
|
7
7
|
import { viewFile, playerPage, publicView } from "../controllers/view.controller.js";
|
|
8
8
|
|
|
9
9
|
const router = express.Router();
|
|
10
|
-
const adminAuth = sessRole('
|
|
10
|
+
const adminAuth = sessRole('superadmin');
|
|
11
11
|
|
|
12
12
|
router.use(requireBucketView);
|
|
13
13
|
router.get('/player/*key', adminAuth, playerPage);
|
package/lib/src/utils/errors.js
CHANGED
|
@@ -36,7 +36,16 @@ export function classifyViewError(error, fallbackMessage = 'Request failed') {
|
|
|
36
36
|
|
|
37
37
|
export function sendApiError(res, error, fallbackMessage = 'Request failed') {
|
|
38
38
|
const { status, code, message } = classifyApiError(error, fallbackMessage);
|
|
39
|
-
return res.status(status).json({
|
|
39
|
+
return res.status(status).json({
|
|
40
|
+
success: false,
|
|
41
|
+
code,
|
|
42
|
+
error: {
|
|
43
|
+
code,
|
|
44
|
+
message,
|
|
45
|
+
},
|
|
46
|
+
message,
|
|
47
|
+
timestamp: new Date().toISOString(),
|
|
48
|
+
});
|
|
40
49
|
}
|
|
41
50
|
|
|
42
51
|
export function sendViewError(res, error, fallbackMessage = 'Request failed') {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mbkbucket",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.4.0",
|
|
4
4
|
"description": "Flexible S3/R2 bucket management — library, Express router, and CLI for mbktech.org applications. Provides upload, download, listing, multipart utilities, signed URLs, and a command-line interface with built-in configuration validation and health checks",
|
|
5
5
|
"author": "Muhammad Bin Khalid",
|
|
6
6
|
"homepage": "https://github.com/MIbnEKhalid/mbkbucket#readme",
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
},
|
|
14
14
|
"scripts": {
|
|
15
15
|
"dev": "cross-env NODE_ENV=dev nodemon index.js",
|
|
16
|
-
"test": "
|
|
16
|
+
"test": "vitest run"
|
|
17
17
|
},
|
|
18
18
|
"imports": {
|
|
19
19
|
"#helpers": "./lib/src/utils/helpers.js",
|
|
@@ -28,13 +28,16 @@
|
|
|
28
28
|
"express": "^5.1.0",
|
|
29
29
|
"express-handlebars": "^8.0.3",
|
|
30
30
|
"express-rate-limit": "^7.5.0",
|
|
31
|
-
"mbkauthe": "^5.
|
|
31
|
+
"mbkauthe": "^5.7.0",
|
|
32
32
|
"multer": "^2.0.2",
|
|
33
33
|
"pg": "^8.16.3"
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
|
+
"@types/supertest": "^7.2.1",
|
|
36
37
|
"cross-env": "^7.0.3",
|
|
37
|
-
"nodemon": "^3.1.14"
|
|
38
|
+
"nodemon": "^3.1.14",
|
|
39
|
+
"supertest": "^7.2.2",
|
|
40
|
+
"vitest": "^4.1.11"
|
|
38
41
|
},
|
|
39
42
|
"overrides": {
|
|
40
43
|
"csurf": {
|
|
@@ -77,4 +80,4 @@
|
|
|
77
80
|
"file-upload",
|
|
78
81
|
"file-download"
|
|
79
82
|
]
|
|
80
|
-
}
|
|
83
|
+
}
|