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 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 (SuperAdmin only)
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` | SuperAdmin | Admin dashboard |
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` | SuperAdmin | List files (JSON) |
232
- | `POST /mbkbucket/api/upload` | SuperAdmin | Upload file(s) |
233
- | `POST /mbkbucket/api/delete` | SuperAdmin | Delete file(s) |
234
- | `POST /mbkbucket/api/delete-folder` | SuperAdmin | Delete folder |
235
- | `POST /mbkbucket/api/create-folder` | SuperAdmin | Create folder marker |
236
- | `POST /mbkbucket/api/rename` | SuperAdmin | Rename/move a file |
237
- | `GET /mbkbucket/api/download/:key(*)` | SuperAdmin | Download a file |
238
- | `GET /mbkbucket/api/metadata/:key(*)` | SuperAdmin | Get file metadata |
239
- | `POST /mbkbucket/api/multipart/init` | SuperAdmin | Init multipart upload |
240
- | `POST /mbkbucket/api/multipart/part` | SuperAdmin | Upload multipart chunk |
241
- | `POST /mbkbucket/api/multipart/complete` | SuperAdmin | Complete multipart |
242
- | `POST /mbkbucket/api/multipart/abort` | SuperAdmin | Abort multipart |
243
- | `GET /mbkbucket/api/multipart/list` | SuperAdmin | List incomplete uploads |
244
- | `POST /mbkbucket/api/multipart/cleanup` | SuperAdmin | Clean up stale uploads |
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 serverUrl = findFlag('server') || storedCfg.serverUrl;
136
+ let server_url = findFlag('server') || storedCfg.server_url;
137
137
 
138
- if (!serverUrl || typeof serverUrl !== '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 serverUrl https://your-server.com\n Then just run: mbkbucket login');
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 profileKey = findFlag('profile-key') || storedCfg.profileKey;
144
- updateConfig({ serverUrl });
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
- serverUrl,
149
- profileKey: typeof profileKey === 'string' ? profileKey : undefined,
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
- tokenPrefix: result.tokenPrefix,
154
+ token_prefix: result.token_prefix,
155
155
  username: result.username,
156
- serverUrl,
156
+ server_url,
157
157
  profile: result.profile || null,
158
- loggedInAt: nowIso(),
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('profileKey') || msg.includes('profileId')) {
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 "${serverUrl}". Verify it is running and CLI_AUTH_ENABLED=true.`);
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.serverUrl}`);
186
- console.log(` Token: ${cfg.tokenPrefix}...`);
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.loggedInAt)}`);
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
- tokenPrefix: 'mbk_demo',
465
+ token_prefix: 'mbk_demo',
466
466
  username: 'demo-user',
467
- serverUrl: 'https://your-app.example.com',
468
- profile: { name: 'Default CLI Profile', scope: 'read-write', allowedApps: ['mbkbucket'] },
469
- loggedInAt: nowIso(),
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', 'tokenPrefix', 'username', 'serverUrl', 'profile', 'profileKey', 'loggedInAt'];
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, serverUrl } = readConfig();
56
- return Boolean(token && serverUrl);
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().serverUrl || null;
64
+ return readConfig().server_url || null;
65
65
  }
66
66
 
67
- export async function deviceFlowLogin({ serverUrl, profileKey }) {
68
- const baseUrl = String(serverUrl).replace(/\/+$/, '');
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
- clientName: `mbkbucket-cli-${os.hostname()}`,
78
- ...(profileKey && { profileKey }),
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 { verificationUrl, userCode, deviceCode, expiresIn, interval, profile } = deviceResp;
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(`│ ${verificationUrl.padEnd(53)}│`);
100
+ console.log(`│ ${(verification_url || '').padEnd(53)}│`);
96
101
  console.log('│ │');
97
- console.log(`│ 🔢 Or enter this code: ${userCode.padEnd(30)}│`);
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(expiresIn / 60)} minutes)...\n`);
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({ deviceCode }),
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: ${pollBody.tokenPrefix}...`);
129
+ console.log(` Token prefix: ${token_prefix}...`);
124
130
  return {
125
131
  token: pollBody.token,
126
- tokenPrefix: pollBody.tokenPrefix,
132
+ token_prefix: token_prefix,
127
133
  username: pollBody.username,
128
134
  profile: profile || null,
129
135
  };
@@ -102,7 +102,4 @@ export function validateAllConfiguration() {
102
102
 
103
103
  export const mbkbucketVar = validateConfiguration();
104
104
 
105
- export {
106
- packageJson,
107
- appVersion
108
- };
105
+ export { packageJson, appVersion };
@@ -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, _req, res, _next) {
18
- console.error(`[mbkbucket] ${err.stack}`);
19
- return res.status(500).render("Error/dError.handlebars", {
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: 500,
22
- error: "Internal app Error",
23
- message: "An unexpected error occurred on the app.",
24
- details: err.message,
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
  }
@@ -21,7 +21,7 @@ const uploadChunkMiddleware = (req, res, next) => {
21
21
  });
22
22
  };
23
23
 
24
- const adminAuth = sessRole('SuperAdmin');
24
+ const adminAuth = sessRole('superadmin');
25
25
 
26
26
  router.use(requireBucketApi);
27
27
 
@@ -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('SuperAdmin'), renderBucketDashboard);
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('SuperAdmin');
10
+ const adminAuth = sessRole('superadmin');
11
11
 
12
12
  router.use(requireBucketView);
13
13
  router.get('/player/*key', adminAuth, playerPage);
@@ -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({ success: false, code, error: message });
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.2",
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": "node --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.3.6",
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
+ }