streamby-core 0.24.2 โ†’ 0.24.4

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
@@ -1,242 +1,242 @@
1
- # @streamby/core
2
-
3
- Middleware framework for building storage-agnostic media APIs.
4
- Part of the [StreamBy](https://streamby.nhexa.cl) ecosystem by TerminalCore Labs.
5
-
6
- ---
7
-
8
- ## ๐Ÿš€ What is it?
9
-
10
- `@streamby/core` is a plug-and-play middleware for Express (or compatible frameworks) that enables file uploads, listings and **multi-project access** over services like:
11
-
12
- - โœ… AWS S3
13
- - โœ… Google Cloud Storage (soon)
14
- - โœ… Cloudflare R2 (soon)
15
- - โœ… Local/Personal servers (soon)
16
-
17
- It's designed to be installed inside your existing API as a library โ€” **no need to run a separate backend**.
18
-
19
- ---
20
-
21
- ## ๐Ÿ“ฆ Installation
22
-
23
- ```bash
24
- npm install @streamby/core
25
- ```
26
-
27
- ---
28
-
29
- ## ๐Ÿงฑ Basic usage
30
-
31
- ---
32
-
33
- ## ๐Ÿ—„๏ธ Database Schema Setup
34
-
35
- `@streamby/core` requires a pre-configured database schema for its internal operations. It does not manage database connections directly; instead, it expects the host application to provide initialized connection instances. This ensures full control and flexibility for the host environment.
36
-
37
- The library will only interact with the specified schema and will not touch other schemas in your database. The `reset` option is opt-in and will only drop and recreate the specified `streamby` schema if explicitly set to `true`.
38
-
39
- ### PostgreSQL Example
40
-
41
- ```ts
42
- import { Pool } from "pg";
43
- import { setupStreambyPg } from "@streamby/core/pg/setup"; // Adjust path as per your package structure
44
-
45
- const pool = new Pool({ connectionString: process.env.DATABASE_URL });
46
-
47
- // Call setupStreambyPg to ensure the schema and tables are created
48
- // reset: false (default) ensures idempotency and no data loss
49
- await setupStreambyPg({ pool, schema: "streamby", reset: false });
50
- ```
51
-
52
- ### MongoDB Example
53
-
54
- ```ts
55
- import { MongoClient } from "mongodb";
56
- import { setupStreambyMongo } from "@streamby/core/mongo/setup"; // Adjust path as per your package structure
57
-
58
- const client = new MongoClient(process.env.MONGO_URL!);
59
-
60
- // Connect the MongoDB client
61
- await client.connect();
62
-
63
- // Call setupStreambyMongo to ensure collections and indexes are created
64
- await setupStreambyMongo({ client, dbName: "streamby" });
65
- ```
66
-
67
- ```ts
68
- import express from 'express';
69
- import { createStreamByRouter } from '@streamby/core';
70
-
71
- const app = express();
72
-
73
- app.use('/streamby', createStreamByRouter({
74
- storageProvider: {
75
- type: 's3',
76
- config: {
77
- bucket: 'your-bucket-name',
78
- region: 'your-region',
79
- accessKeyId: 'YOUR_AWS_KEY',
80
- secretAccessKey: 'YOUR_AWS_SECRET'
81
- }
82
- },
83
- authProvider: async (req) => {
84
- // extract token/cookie and validate
85
- return {
86
- userId: 'demo',
87
- projects: ['demo-project'],
88
- role: 'admin',
89
- };
90
- },
91
- projectProvider: async (projectId) => {
92
- // fetch project from your DB
93
- return {
94
- id: projectId,
95
- name: 'Demo Project',
96
- description: 'Demo for StreamBy integration',
97
- rootFolders: [],
98
- settings: { allowUpload: true }
99
- };
100
- }
101
- }));
102
-
103
- app.listen(3000);
104
- ```
105
-
106
- ---
107
-
108
- ## ๐Ÿงช Testing
109
-
110
- ```bash
111
- npm run test
112
- ```
113
-
114
- Unit tests use [Vitest](https://vitest.dev) and [Supertest](https://www.npmjs.com/package/supertest).
115
-
116
- ---
117
-
118
- ## ๐Ÿ“ Features
119
-
120
- - ๐Ÿ“‚ Multi-project access control
121
- - ๐Ÿ” Project-aware file uploads & listings
122
- - ๐Ÿงน Modular adapters per storage provider
123
- - ๐Ÿงฐ Built-in testability with mock auth & storage
124
- - โœจ Simple to extend for custom business logic
125
-
126
- ---
127
-
128
- ## ๐Ÿ—บ๏ธ API Endpoints
129
-
130
- Here's a summary of the key API endpoints provided by `@streamby/core`:
131
-
132
- ### `GET /streamby/projects`
133
-
134
- Lists all projects accessible by the authenticated user.
135
-
136
- **Query Parameters:**
137
- - `archived`: (Optional) Filter projects by their archived status.
138
- - `true`: Returns only archived projects.
139
- - `false`: Returns only unarchived projects.
140
- - (Omitted): Returns all projects (both archived and unarchived).
141
-
142
- **Example Response:**
143
- ```json
144
- {
145
- "projects": [
146
- {
147
- "id": "project1_id",
148
- "dbType": "nosql",
149
- "name": "My NoSQL Project",
150
- "image": "url_to_image",
151
- "archived": false
152
- },
153
- {
154
- "id": "project2_id",
155
- "dbType": "sql",
156
- "name": "My SQL Project",
157
- "image": "url_to_image",
158
- "archived": true
159
- }
160
- ]
161
- }
162
- ```
163
-
164
- ### `PATCH /streamby/projects/:id/archive`
165
-
166
- Archives a specific project. After archiving, it returns the complete list of projects for the user, including the updated project.
167
-
168
- **Example Response:**
169
- ```json
170
- {
171
- "success": true,
172
- "projects": [
173
- {
174
- "id": "project1_id",
175
- "dbType": "nosql",
176
- "name": "My NoSQL Project",
177
- "image": "url_to_image",
178
- "archived": true
179
- },
180
- {
181
- "id": "project2_id",
182
- "dbType": "sql",
183
- "name": "My SQL Project",
184
- "image": "url_to_image",
185
- "archived": false
186
- }
187
- ]
188
- }
189
- ```
190
-
191
- ### `PATCH /streamby/projects/:id/unarchive`
192
-
193
- Unarchives a specific project. After unarchiving, it returns the complete list of projects for the user, including the updated project.
194
-
195
- **Example Response:**
196
- ```json
197
- {
198
- "success": true,
199
- "projects": [
200
- {
201
- "id": "project1_id",
202
- "dbType": "nosql",
203
- "name": "My NoSQL Project",
204
- "image": "url_to_image",
205
- "archived": false
206
- },
207
- {
208
- "id": "project2_id",
209
- "dbType": "sql",
210
- "name": "My SQL Project",
211
- "image": "url_to_image",
212
- "archived": false
213
- }
214
- ]
215
- }
216
- ```
217
-
218
- ---
219
-
220
- ## ๐Ÿšฃ Roadmap
221
-
222
- - [ ] Support for Google Cloud Storage
223
- - [ ] CLI tool for uploading files
224
- - [ ] Role-based access control middleware
225
- - [ ] Plugin system for extended routes
226
- - [ ] Streaming support (HLS, audio, etc.)
227
-
228
- ---
229
-
230
- ## ๐Ÿง‘โ€๐Ÿ’ป Maintained by
231
-
232
- **TerminalCore Labs** โ€“ part of [Nhexa Entertainment](https://nhexa.cl)
233
- Developed as open-source infrastructure for creative and media-oriented apps.
234
-
235
- Visit us [here](https://terminalcore.cl)
236
-
237
- ---
238
-
239
- ## ๐Ÿ“Ÿ License
240
-
241
- [MIT](./LICENSE)
242
-
1
+ # @streamby/core
2
+
3
+ Middleware framework for building storage-agnostic media APIs.
4
+ Part of the [StreamBy](https://streamby.nhexa.cl) ecosystem by TerminalCore Labs.
5
+
6
+ ---
7
+
8
+ ## ๐Ÿš€ What is it?
9
+
10
+ `@streamby/core` is a plug-and-play middleware for Express (or compatible frameworks) that enables file uploads, listings and **multi-project access** over services like:
11
+
12
+ - โœ… AWS S3
13
+ - โœ… Google Cloud Storage (soon)
14
+ - โœ… Cloudflare R2 (soon)
15
+ - โœ… Local/Personal servers (soon)
16
+
17
+ It's designed to be installed inside your existing API as a library โ€” **no need to run a separate backend**.
18
+
19
+ ---
20
+
21
+ ## ๐Ÿ“ฆ Installation
22
+
23
+ ```bash
24
+ npm install @streamby/core
25
+ ```
26
+
27
+ ---
28
+
29
+ ## ๐Ÿงฑ Basic usage
30
+
31
+ ---
32
+
33
+ ## ๐Ÿ—„๏ธ Database Schema Setup
34
+
35
+ `@streamby/core` requires a pre-configured database schema for its internal operations. It does not manage database connections directly; instead, it expects the host application to provide initialized connection instances. This ensures full control and flexibility for the host environment.
36
+
37
+ The library will only interact with the specified schema and will not touch other schemas in your database. The `reset` option is opt-in and will only drop and recreate the specified `streamby` schema if explicitly set to `true`.
38
+
39
+ ### PostgreSQL Example
40
+
41
+ ```ts
42
+ import { Pool } from "pg";
43
+ import { setupStreambyPg } from "@streamby/core/pg/setup"; // Adjust path as per your package structure
44
+
45
+ const pool = new Pool({ connectionString: process.env.DATABASE_URL });
46
+
47
+ // Call setupStreambyPg to ensure the schema and tables are created
48
+ // reset: false (default) ensures idempotency and no data loss
49
+ await setupStreambyPg({ pool, schema: "streamby", reset: false });
50
+ ```
51
+
52
+ ### MongoDB Example
53
+
54
+ ```ts
55
+ import { MongoClient } from "mongodb";
56
+ import { setupStreambyMongo } from "@streamby/core/mongo/setup"; // Adjust path as per your package structure
57
+
58
+ const client = new MongoClient(process.env.MONGO_URL!);
59
+
60
+ // Connect the MongoDB client
61
+ await client.connect();
62
+
63
+ // Call setupStreambyMongo to ensure collections and indexes are created
64
+ await setupStreambyMongo({ client, dbName: "streamby" });
65
+ ```
66
+
67
+ ```ts
68
+ import express from 'express';
69
+ import { createStreamByRouter } from '@streamby/core';
70
+
71
+ const app = express();
72
+
73
+ app.use('/streamby', createStreamByRouter({
74
+ storageProvider: {
75
+ type: 's3',
76
+ config: {
77
+ bucket: 'your-bucket-name',
78
+ region: 'your-region',
79
+ accessKeyId: 'YOUR_AWS_KEY',
80
+ secretAccessKey: 'YOUR_AWS_SECRET'
81
+ }
82
+ },
83
+ authProvider: async (req) => {
84
+ // extract token/cookie and validate
85
+ return {
86
+ userId: 'demo',
87
+ projects: ['demo-project'],
88
+ role: 'admin',
89
+ };
90
+ },
91
+ projectProvider: async (projectId) => {
92
+ // fetch project from your DB
93
+ return {
94
+ id: projectId,
95
+ name: 'Demo Project',
96
+ description: 'Demo for StreamBy integration',
97
+ rootFolders: [],
98
+ settings: { allowUpload: true }
99
+ };
100
+ }
101
+ }));
102
+
103
+ app.listen(3000);
104
+ ```
105
+
106
+ ---
107
+
108
+ ## ๐Ÿงช Testing
109
+
110
+ ```bash
111
+ npm run test
112
+ ```
113
+
114
+ Unit tests use [Vitest](https://vitest.dev) and [Supertest](https://www.npmjs.com/package/supertest).
115
+
116
+ ---
117
+
118
+ ## ๐Ÿ“ Features
119
+
120
+ - ๐Ÿ“‚ Multi-project access control
121
+ - ๐Ÿ” Project-aware file uploads & listings
122
+ - ๐Ÿงน Modular adapters per storage provider
123
+ - ๐Ÿงฐ Built-in testability with mock auth & storage
124
+ - โœจ Simple to extend for custom business logic
125
+
126
+ ---
127
+
128
+ ## ๐Ÿ—บ๏ธ API Endpoints
129
+
130
+ Here's a summary of the key API endpoints provided by `@streamby/core`:
131
+
132
+ ### `GET /streamby/projects`
133
+
134
+ Lists all projects accessible by the authenticated user.
135
+
136
+ **Query Parameters:**
137
+ - `archived`: (Optional) Filter projects by their archived status.
138
+ - `true`: Returns only archived projects.
139
+ - `false`: Returns only unarchived projects.
140
+ - (Omitted): Returns all projects (both archived and unarchived).
141
+
142
+ **Example Response:**
143
+ ```json
144
+ {
145
+ "projects": [
146
+ {
147
+ "id": "project1_id",
148
+ "dbType": "nosql",
149
+ "name": "My NoSQL Project",
150
+ "image": "url_to_image",
151
+ "archived": false
152
+ },
153
+ {
154
+ "id": "project2_id",
155
+ "dbType": "sql",
156
+ "name": "My SQL Project",
157
+ "image": "url_to_image",
158
+ "archived": true
159
+ }
160
+ ]
161
+ }
162
+ ```
163
+
164
+ ### `PATCH /streamby/projects/:id/archive`
165
+
166
+ Archives a specific project. After archiving, it returns the complete list of projects for the user, including the updated project.
167
+
168
+ **Example Response:**
169
+ ```json
170
+ {
171
+ "success": true,
172
+ "projects": [
173
+ {
174
+ "id": "project1_id",
175
+ "dbType": "nosql",
176
+ "name": "My NoSQL Project",
177
+ "image": "url_to_image",
178
+ "archived": true
179
+ },
180
+ {
181
+ "id": "project2_id",
182
+ "dbType": "sql",
183
+ "name": "My SQL Project",
184
+ "image": "url_to_image",
185
+ "archived": false
186
+ }
187
+ ]
188
+ }
189
+ ```
190
+
191
+ ### `PATCH /streamby/projects/:id/unarchive`
192
+
193
+ Unarchives a specific project. After unarchiving, it returns the complete list of projects for the user, including the updated project.
194
+
195
+ **Example Response:**
196
+ ```json
197
+ {
198
+ "success": true,
199
+ "projects": [
200
+ {
201
+ "id": "project1_id",
202
+ "dbType": "nosql",
203
+ "name": "My NoSQL Project",
204
+ "image": "url_to_image",
205
+ "archived": false
206
+ },
207
+ {
208
+ "id": "project2_id",
209
+ "dbType": "sql",
210
+ "name": "My SQL Project",
211
+ "image": "url_to_image",
212
+ "archived": false
213
+ }
214
+ ]
215
+ }
216
+ ```
217
+
218
+ ---
219
+
220
+ ## ๐Ÿšฃ Roadmap
221
+
222
+ - [ ] Support for Google Cloud Storage
223
+ - [ ] CLI tool for uploading files
224
+ - [ ] Role-based access control middleware
225
+ - [ ] Plugin system for extended routes
226
+ - [ ] Streaming support (HLS, audio, etc.)
227
+
228
+ ---
229
+
230
+ ## ๐Ÿง‘โ€๐Ÿ’ป Maintained by
231
+
232
+ **TerminalCore Labs** โ€“ part of [Nhexa Entertainment](https://nhexa.cl)
233
+ Developed as open-source infrastructure for creative and media-oriented apps.
234
+
235
+ Visit us [here](https://terminalcore.cl)
236
+
237
+ ---
238
+
239
+ ## ๐Ÿ“Ÿ License
240
+
241
+ [MIT](./LICENSE)
242
+
@@ -43,56 +43,56 @@ const getConnection = (id) => {
43
43
  exports.getConnection = getConnection;
44
44
  const ensureTablesExist = async (pool) => {
45
45
  try {
46
- await pool.query(`
47
- CREATE SCHEMA IF NOT EXISTS streamby;
48
- CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
49
- CREATE TABLE IF NOT EXISTS streamby.projects (
50
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
51
- name VARCHAR(255) NOT NULL,
52
- description TEXT,
53
- image TEXT,
54
- "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
55
- "updatedAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW()
56
- );
46
+ await pool.query(`
47
+ CREATE SCHEMA IF NOT EXISTS streamby;
48
+ CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
49
+ CREATE TABLE IF NOT EXISTS streamby.projects (
50
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
51
+ name VARCHAR(255) NOT NULL,
52
+ description TEXT,
53
+ image TEXT,
54
+ "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
55
+ "updatedAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW()
56
+ );
57
57
  `);
58
58
  console.log('โœ… "projects" table ensured to exist.');
59
59
  // Ensure dbType column exists and is correctly configured
60
- await pool.query(`
61
- ALTER TABLE streamby.projects ADD COLUMN IF NOT EXISTS "dbType" VARCHAR(50);
60
+ await pool.query(`
61
+ ALTER TABLE streamby.projects ADD COLUMN IF NOT EXISTS "dbType" VARCHAR(50);
62
62
  `);
63
- await pool.query(`
64
- UPDATE streamby.projects SET "dbType" = 'nosql' WHERE "dbType" IS NULL;
63
+ await pool.query(`
64
+ UPDATE streamby.projects SET "dbType" = 'nosql' WHERE "dbType" IS NULL;
65
65
  `);
66
- await pool.query(`
67
- ALTER TABLE streamby.projects ALTER COLUMN "dbType" SET NOT NULL;
66
+ await pool.query(`
67
+ ALTER TABLE streamby.projects ALTER COLUMN "dbType" SET NOT NULL;
68
68
  `);
69
- await pool.query(`
70
- ALTER TABLE streamby.projects ALTER COLUMN "dbType" SET DEFAULT 'nosql';
69
+ await pool.query(`
70
+ ALTER TABLE streamby.projects ALTER COLUMN "dbType" SET DEFAULT 'nosql';
71
71
  `);
72
- await pool.query(`
73
- CREATE TABLE IF NOT EXISTS streamby.exports (
74
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
75
- "projectId" UUID NOT NULL REFERENCES streamby.projects(id) ON DELETE CASCADE,
76
- status VARCHAR(50) NOT NULL DEFAULT 'pending',
77
- "filePath" TEXT,
78
- "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
79
- "updatedAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW()
80
- );
72
+ await pool.query(`
73
+ CREATE TABLE IF NOT EXISTS streamby.exports (
74
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
75
+ "projectId" UUID NOT NULL REFERENCES streamby.projects(id) ON DELETE CASCADE,
76
+ status VARCHAR(50) NOT NULL DEFAULT 'pending',
77
+ "filePath" TEXT,
78
+ "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
79
+ "updatedAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW()
80
+ );
81
81
  `);
82
82
  console.log('โœ… "exports" table ensured to exist.');
83
- await pool.query(`
84
- CREATE TABLE IF NOT EXISTS streamby.project_members (
85
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
86
- "projectId" UUID NOT NULL REFERENCES streamby.projects(id) ON DELETE CASCADE,
87
- "userId" VARCHAR(255) NOT NULL,
88
- role VARCHAR(255) NOT NULL DEFAULT 'member',
89
- archived BOOLEAN NOT NULL DEFAULT FALSE,
90
- "archivedBy" VARCHAR(255),
91
- "archivedAt" TIMESTAMP WITH TIME ZONE,
92
- "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
93
- "updatedAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
94
- UNIQUE ("projectId", "userId")
95
- );
83
+ await pool.query(`
84
+ CREATE TABLE IF NOT EXISTS streamby.project_members (
85
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
86
+ "projectId" UUID NOT NULL REFERENCES streamby.projects(id) ON DELETE CASCADE,
87
+ "userId" VARCHAR(255) NOT NULL,
88
+ role VARCHAR(255) NOT NULL DEFAULT 'member',
89
+ archived BOOLEAN NOT NULL DEFAULT FALSE,
90
+ "archivedBy" VARCHAR(255),
91
+ "archivedAt" TIMESTAMP WITH TIME ZONE,
92
+ "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
93
+ "updatedAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
94
+ UNIQUE ("projectId", "userId")
95
+ );
96
96
  `);
97
97
  console.log('โœ… "project_members" table ensured to exist.');
98
98
  }
@@ -5,13 +5,13 @@ const createSQLExportTable = async (connection, projectId, exportName, fields) =
5
5
  const slug = exportName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
6
6
  const tableName = `export_${projectId}_${slug}`;
7
7
  const columns = fields.map(field => `"${field.name}" ${field.type}`).join(',');
8
- const createTableQuery = `
9
- CREATE TABLE IF NOT EXISTS "${tableName}" (
10
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
11
- "projectId" UUID NOT NULL,
12
- __metadata JSONB NOT NULL,
13
- ${columns ? `, ${columns}` : ''}
14
- );
8
+ const createTableQuery = `
9
+ CREATE TABLE IF NOT EXISTS "${tableName}" (
10
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
11
+ "projectId" UUID NOT NULL,
12
+ __metadata JSONB NOT NULL,
13
+ ${columns ? `, ${columns}` : ''}
14
+ );
15
15
  `;
16
16
  await connection.query(createTableQuery);
17
17
  console.log(`โœ… Table '${tableName}' created with metadata.`);
@@ -29,11 +29,11 @@ exports.createSQLExportTable = createSQLExportTable;
29
29
  const createSQLRawExportTable = async (connection, projectId, exportName, jsonData) => {
30
30
  const slug = exportName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
31
31
  const tableName = `raw_export_${projectId}_${slug}`;
32
- const createTableQuery = `
33
- CREATE TABLE IF NOT EXISTS "${tableName}" (
34
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
35
- data JSONB NOT NULL
36
- );
32
+ const createTableQuery = `
33
+ CREATE TABLE IF NOT EXISTS "${tableName}" (
34
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
35
+ data JSONB NOT NULL
36
+ );
37
37
  `;
38
38
  await connection.query(createTableQuery);
39
39
  console.log(`โœ… Raw table '${tableName}' created.`);
@@ -0,0 +1,2 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+ export declare const projectOriginMiddleware: (req: Request, res: Response, next: NextFunction) => Promise<void | Response<any, Record<string, any>>>;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.projectOriginMiddleware = void 0;
4
+ const manager_1 = require("../models/manager");
5
+ const projectOriginMiddleware = async (req, res, next) => {
6
+ const projectId = req.params.projectId;
7
+ const origin = req.headers.origin;
8
+ if (!projectId) {
9
+ return next();
10
+ }
11
+ if (!origin) {
12
+ return res.status(403).json({ message: 'Origin header is required' });
13
+ }
14
+ try {
15
+ const Project = (0, manager_1.getModel)('projects');
16
+ const project = await Project.findOne({ id: projectId });
17
+ if (!project) {
18
+ return res.status(404).json({ message: 'Project not found' });
19
+ }
20
+ if (project.allowedOrigin && project.allowedOrigin.length > 0) {
21
+ if (project.allowedOrigin.includes(origin)) {
22
+ res.header('Access-Control-Allow-Origin', origin);
23
+ res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
24
+ res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
25
+ next();
26
+ }
27
+ else {
28
+ return res.status(403).json({ message: 'Origin not allowed' });
29
+ }
30
+ }
31
+ else {
32
+ // If no origins are configured, allow the request
33
+ next();
34
+ }
35
+ }
36
+ catch (error) {
37
+ console.error('Error in projectOriginMiddleware:', error);
38
+ return res.status(500).json({ message: 'Internal server error' });
39
+ }
40
+ };
41
+ exports.projectOriginMiddleware = projectOriginMiddleware;
@@ -26,7 +26,7 @@ function createStreamByRouter(config) {
26
26
  (0, manager_1.registerModel)('exports', allDbIds, 'exports', streambySchema);
27
27
  const mainDb = config.databases.find(db => db.main);
28
28
  if (mainDb) {
29
- (0, manager_1.registerModel)('users', [mainDb.id], 'users', streambySchema);
29
+ (0, manager_1.registerModel)('users', [mainDb.id], 'users', 'accounts');
30
30
  }
31
31
  }
32
32
  router.use((0, auth_2.authenticate)(config));
@@ -1,2 +1,2 @@
1
1
  import { Request, Response, NextFunction } from 'express';
2
- export declare function publicRoute(req: Request, res: Response, next: NextFunction): void;
2
+ export declare function getExportRoute(req: Request, res: Response, next: NextFunction): void;
@@ -1,8 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.publicRoute = publicRoute;
4
- function publicRoute(req, res, next) {
5
- if (req.path.includes('/public-export/')) {
3
+ exports.getExportRoute = getExportRoute;
4
+ function getExportRoute(req, res, next) {
5
+ if (req.path.includes('/get-export/')) {
6
6
  return next();
7
7
  }
8
8
  return next();
@@ -53,7 +53,25 @@ function exportRouter(config) {
53
53
  if (!data) {
54
54
  return res.status(404).json({ message: 'Export data not found' });
55
55
  }
56
- res.json({ data, message: 'Export data fetched successfully' });
56
+ let responseData;
57
+ if (Array.isArray(data)) {
58
+ responseData = {
59
+ content: data,
60
+ allowedOrigin: exportMetadata.allowedOrigin,
61
+ private: exportMetadata.private,
62
+ };
63
+ }
64
+ else {
65
+ responseData = {
66
+ ...data,
67
+ allowedOrigin: exportMetadata.allowedOrigin,
68
+ private: exportMetadata.private,
69
+ };
70
+ }
71
+ res.json({
72
+ data: responseData,
73
+ message: 'Export data fetched successfully',
74
+ });
57
75
  }
58
76
  catch (err) {
59
77
  res.status(500).json({ message: 'Failed to fetch export data', details: err.message });
@@ -68,7 +86,7 @@ function exportRouter(config) {
68
86
  return res.status(401).json({ message: 'Unauthorized' });
69
87
  }
70
88
  const projectId = req.params.id;
71
- const { name, description, collectionName, jsonData } = req.body;
89
+ const { name, description, collectionName, jsonData, isPrivate, allowedOrigin } = req.body;
72
90
  if (!name || !collectionName || !jsonData) {
73
91
  return res.status(400).json({ message: 'Missing export name, collectionName, or jsonData' });
74
92
  }
@@ -76,7 +94,7 @@ function exportRouter(config) {
76
94
  if (!project || !(0, auth_1.isProjectMember)(project, auth.userId)) {
77
95
  return res.status(403).json({ message: 'Unauthorized project access' });
78
96
  }
79
- const result = await (0, export_1.createExport)(config, projectId, name, collectionName, jsonData, project.dbType);
97
+ const result = await (0, export_1.createExport)(config, projectId, name, collectionName, jsonData, project.dbType, isPrivate, allowedOrigin);
80
98
  res.status(201).json({ data: result, message: result.message });
81
99
  }
82
100
  catch (err) {
@@ -90,7 +108,7 @@ function exportRouter(config) {
90
108
  return res.status(401).json({ message: 'Unauthorized' });
91
109
  }
92
110
  const { id: projectId, export_id: exportId } = req.params;
93
- const { name, collectionName, description, jsonData } = req.body;
111
+ const { name, collectionName, description, jsonData, isPrivate, allowedOrigin } = req.body;
94
112
  if (!name || !collectionName || !jsonData) {
95
113
  return res.status(400).json({ message: 'Missing name, collectionName, or jsonData' });
96
114
  }
@@ -98,7 +116,7 @@ function exportRouter(config) {
98
116
  if (!project || !(0, auth_1.isProjectMember)(project, auth.userId)) {
99
117
  return res.status(403).json({ message: 'Unauthorized project access' });
100
118
  }
101
- const result = await (0, export_1.updateExport)(config, projectId, exportId, name, collectionName, jsonData, project.dbType);
119
+ const result = await (0, export_1.updateExport)(config, projectId, exportId, name, collectionName, jsonData, project.dbType, isPrivate, allowedOrigin);
102
120
  res.status(200).json({ data: result, message: result.message });
103
121
  }
104
122
  catch (err) {
@@ -127,7 +145,7 @@ function exportRouter(config) {
127
145
  res.status(500).json({ message: 'Failed to delete export', details: err.message });
128
146
  }
129
147
  });
130
- router.get('/:projectId/public-export/:exportName', async (req, res) => {
148
+ router.get('/:projectId/get-export/:exportName', async (req, res) => {
131
149
  try {
132
150
  const { projectId, exportName } = req.params;
133
151
  const project = await Project.findOne({ _id: projectId });
@@ -138,85 +156,10 @@ function exportRouter(config) {
138
156
  if (!exportMetadata) {
139
157
  return res.status(404).json({ message: 'Export not found in this project' });
140
158
  }
141
- const targetDb = config.databases?.find(db => db.type === project.dbType);
142
- if (!targetDb) {
143
- return res.status(500).json({ message: `Database connection not found for type ${project.dbType}` });
144
- }
145
- const connection = (0, connectionManager_1.getConnection)(targetDb.id);
146
- let data;
147
- if (project.dbType === 'nosql') {
148
- const db = connection.client.db();
149
- if (exportMetadata.type === 'raw') {
150
- const rawData = await db.collection(exportMetadata.collectionName).findOne({ _id: new mongodb_1.ObjectId(exportMetadata.id) });
151
- data = rawData ? rawData.json : null;
152
- }
153
- else {
154
- data = await db.collection(exportMetadata.collectionName).find({ __metadata: { $exists: false } }).toArray();
155
- }
156
- }
157
- else if (project.dbType === 'sql') {
158
- // SQL implementation for public exports will go here
159
- return res.status(501).json({ message: 'SQL public exports not yet implemented' });
160
- }
161
- if (!data) {
162
- return res.status(404).json({ message: 'Export data not found' });
163
- }
164
- res.json(data); // Return the raw data directly
165
- }
166
- catch (err) {
167
- res.status(500).json({ message: 'Failed to fetch public export data', details: err.message });
168
- }
169
- });
170
- router.get('/:projectId/public-export/:exportName', async (req, res) => {
171
- try {
172
- const { projectId, exportName } = req.params;
173
- const project = await Project.findOne({ _id: projectId });
174
- if (!project) {
175
- return res.status(404).json({ message: 'Project not found' });
176
- }
177
- const exportMetadata = project.exports.find((e) => e.name === exportName);
178
- if (!exportMetadata) {
179
- return res.status(404).json({ message: 'Export not found in this project' });
180
- }
181
- const targetDb = config.databases?.find(db => db.type === project.dbType);
182
- if (!targetDb) {
183
- return res.status(500).json({ message: `Database connection not found for type ${project.dbType}` });
184
- }
185
- const connection = (0, connectionManager_1.getConnection)(targetDb.id);
186
- let data;
187
- if (project.dbType === 'nosql') {
188
- const db = connection.client.db();
189
- if (exportMetadata.type === 'raw') {
190
- const rawData = await db.collection(exportMetadata.collectionName).findOne({ _id: new mongodb_1.ObjectId(exportMetadata.id) });
191
- data = rawData ? rawData.json : null;
192
- }
193
- else {
194
- data = await db.collection(exportMetadata.collectionName).find({ __metadata: { $exists: false } }).toArray();
195
- }
196
- }
197
- else if (project.dbType === 'sql') {
198
- // SQL implementation for public exports will go here
199
- return res.status(501).json({ message: 'SQL public exports not yet implemented' });
200
- }
201
- if (!data) {
202
- return res.status(404).json({ message: 'Export data not found' });
203
- }
204
- res.json(data); // Return the raw data directly
205
- }
206
- catch (err) {
207
- res.status(500).json({ message: 'Failed to fetch public export data', details: err.message });
208
- }
209
- });
210
- router.get('/:projectId/public-export/:exportName', async (req, res) => {
211
- try {
212
- const { projectId, exportName } = req.params;
213
- const project = await Project.findOne({ _id: projectId });
214
- if (!project) {
215
- return res.status(404).json({ message: 'Project not found' });
216
- }
217
- const exportMetadata = project.exports.find((e) => e.name === exportName);
218
- if (!exportMetadata) {
219
- return res.status(404).json({ message: 'Export not found in this project' });
159
+ const origin = req.headers.origin;
160
+ const allowedOrigins = exportMetadata.allowedOrigin || project.allowedOrigin;
161
+ if (!allowedOrigins.includes(origin)) {
162
+ return res.status(403).json({ message: 'Unauthorized' });
220
163
  }
221
164
  const targetDb = config.databases?.find(db => db.type === project.dbType);
222
165
  if (!targetDb) {
@@ -52,7 +52,7 @@ function projectRouter(config) {
52
52
  if (auth.role !== 'admin' && auth.role !== 'editor') {
53
53
  return res.status(403).json({ message: 'Permission denied' });
54
54
  }
55
- const { name, description, dbType, image } = req.body;
55
+ const { name, description, dbType, image, allowedOrigin } = req.body;
56
56
  const mainDb = config.databases?.find(db => db.main);
57
57
  if (!mainDb) {
58
58
  return res.status(500).json({ message: 'Main database not configured' });
@@ -68,6 +68,7 @@ function projectRouter(config) {
68
68
  name,
69
69
  description: description || '',
70
70
  image: image || '',
71
+ allowedOrigin: allowedOrigin || [],
71
72
  members: [{ userId: auth.userId, username: user.username, role: "admin", archived: false }]
72
73
  });
73
74
  const allProjects = await Project.find({});
@@ -293,5 +294,30 @@ function projectRouter(config) {
293
294
  res.status(500).json({ message: 'Failed to update project image', details: err.message });
294
295
  }
295
296
  });
297
+ router.patch('/projects/:id/origins', async (req, res) => {
298
+ try {
299
+ const auth = req.auth;
300
+ if (auth.role !== 'admin' && auth.role !== 'editor') {
301
+ return res.status(403).json({ message: 'Permission denied' });
302
+ }
303
+ const projectId = req.params.id;
304
+ const { origins } = req.body;
305
+ const project = await Project.findOne({ _id: projectId });
306
+ if (!project) {
307
+ return res.status(404).json({ message: 'Project not found' });
308
+ }
309
+ if (!(0, auth_1.isProjectMember)(project, auth.userId)) {
310
+ return res.status(403).json({ message: 'Unauthorized project access' });
311
+ }
312
+ const updated = await Project.update({ _id: projectId }, { allowedOrigin: origins });
313
+ if (!updated) {
314
+ return res.status(404).json({ message: 'Project not found or not updated' });
315
+ }
316
+ res.status(200).json({ success: true, project: updated, message: 'Project origins updated successfully' });
317
+ }
318
+ catch (err) {
319
+ res.status(500).json({ message: 'Failed to update project origins', details: err.message });
320
+ }
321
+ });
296
322
  return router;
297
323
  }
@@ -23,7 +23,7 @@ class Model {
23
23
  const connection = (0, connectionManager_1.getConnection)(id);
24
24
  return connection.type === dbType;
25
25
  });
26
- return new Model(filteredConnectionIds, this.tableName);
26
+ return new Model(filteredConnectionIds, this.tableName, this.schema);
27
27
  }
28
28
  async find(filter) {
29
29
  const allResults = [];
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.authenticate = void 0;
4
4
  exports.checkRole = checkRole;
5
5
  const authenticate = (config) => async (req, res, next) => {
6
- if (req.path.includes('/public-export/')) {
6
+ if (req.path.includes('/get-export/')) {
7
7
  return next();
8
8
  }
9
9
  try {
@@ -5,8 +5,8 @@ interface CreateExportResult {
5
5
  message: string;
6
6
  }
7
7
  import { StreamByConfig } from '../types';
8
- export declare function createExport(config: StreamByConfig, projectId: string, exportName: string, collectionName: string, jsonData: any, dbType: DatabaseType): Promise<CreateExportResult>;
9
- export declare function updateExport(config: StreamByConfig, projectId: string, exportId: string, exportName: string, collectionName: string, jsonData: any, dbType: DatabaseType): Promise<CreateExportResult>;
8
+ export declare function createExport(config: StreamByConfig, projectId: string, exportName: string, collectionName: string, jsonData: any, dbType: DatabaseType, isPrivate?: boolean, allowedOrigin?: string[]): Promise<CreateExportResult>;
9
+ export declare function updateExport(config: StreamByConfig, projectId: string, exportId: string, exportName: string, collectionName: string, jsonData: any, dbType: DatabaseType, isPrivate?: boolean, allowedOrigin?: string[]): Promise<CreateExportResult>;
10
10
  export declare function deleteExport(config: StreamByConfig, projectId: string, exportId: string, dbType: DatabaseType, collectionName: string): Promise<{
11
11
  message: string;
12
12
  }>;
@@ -8,7 +8,7 @@ const mongodb_1 = require("mongodb");
8
8
  const connectionManager_1 = require("../adapters/database/connectionManager");
9
9
  const nosql_1 = require("../adapters/database/nosql");
10
10
  const sql_1 = require("../adapters/database/sql");
11
- async function createExport(config, projectId, exportName, collectionName, jsonData, dbType) {
11
+ async function createExport(config, projectId, exportName, collectionName, jsonData, dbType, isPrivate, allowedOrigin) {
12
12
  const targetDb = config.databases?.find(db => db.type === dbType && db.main) ||
13
13
  config.databases?.find(db => db.type === dbType);
14
14
  if (!targetDb) {
@@ -28,10 +28,10 @@ async function createExport(config, projectId, exportName, collectionName, jsonD
28
28
  // Update the project with the new export reference
29
29
  // Assuming project metadata is always in NoSQL (MongoDB)
30
30
  const NoSQLProject = (0, manager_1.getModel)('projects', 'nosql');
31
- await NoSQLProject.update({ _id: projectId }, { $push: { exports: { id: dbType === 'nosql' ? new mongodb_1.ObjectId(result.exportId) : result.exportId, name: exportName, collectionName: result.collectionName, type: 'raw', method: 'GET' } } });
31
+ await NoSQLProject.update({ _id: projectId }, { $push: { exports: { id: dbType === 'nosql' ? new mongodb_1.ObjectId(result.exportId) : result.exportId, name: exportName, collectionName: result.collectionName, type: 'raw', method: 'GET', private: isPrivate, allowedOrigin: allowedOrigin } } });
32
32
  return { ...result, message: 'Raw export created successfully' };
33
33
  }
34
- async function updateExport(config, projectId, exportId, exportName, collectionName, jsonData, dbType) {
34
+ async function updateExport(config, projectId, exportId, exportName, collectionName, jsonData, dbType, isPrivate, allowedOrigin) {
35
35
  const targetDb = config.databases?.find(db => db.type === dbType && db.main) ||
36
36
  config.databases?.find(db => db.type === dbType);
37
37
  if (!targetDb) {
@@ -56,8 +56,7 @@ async function updateExport(config, projectId, exportId, exportName, collectionN
56
56
  await NoSQLProject.update({
57
57
  _id: new mongodb_1.ObjectId(projectId),
58
58
  'exports.id': { $in: [new mongodb_1.ObjectId(exportId), exportId] }
59
- }, { $set: { 'exports.$.name': exportName, 'exports.$.collectionName': collectionName } });
60
- console.log(result);
59
+ }, { $set: { 'exports.$.name': exportName, 'exports.$.collectionName': collectionName, 'exports.$.private': isPrivate, 'exports.$.allowedOrigin': allowedOrigin } });
61
60
  return { ...result, message: 'Raw export updated successfully' };
62
61
  }
63
62
  async function deleteExport(config, projectId, exportId, dbType, collectionName) {
@@ -83,4 +83,6 @@ export interface Export {
83
83
  type: 'structured' | 'raw';
84
84
  fields?: FieldDefinition[];
85
85
  jsonData?: any;
86
+ private?: boolean;
87
+ allowedOrigin?: string[];
86
88
  }
package/package.json CHANGED
@@ -1,60 +1,60 @@
1
- {
2
- "name": "streamby-core",
3
- "version": "0.24.2",
4
- "description": "StreamBy middleware framework for media storage management",
5
- "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
7
- "files": [
8
- "dist"
9
- ],
10
- "scripts": {
11
- "build": "tsc",
12
- "test": "vitest",
13
- "dev": "ts-node-dev --respawn --clear dev.ts",
14
- "prepublishOnly": "npm run build"
15
- },
16
- "repository": {
17
- "type": "git",
18
- "url": "https://github.com/GwerhDev/StreamBy-Package.git"
19
- },
20
- "keywords": [
21
- "streamby",
22
- "middleware",
23
- "upload",
24
- "storage",
25
- "s3",
26
- "express",
27
- "typescript"
28
- ],
29
- "author": "TerminalCore Labs",
30
- "license": "MIT",
31
- "dependencies": {
32
- "@aws-sdk/client-s3": "^3.528.0",
33
- "@aws-sdk/s3-request-presigner": "^3.787.0",
34
- "@prisma/client": "^6.12.0",
35
- "bcrypt": "^5.1.1",
36
- "dotenv": "^16.5.0",
37
- "express": "^4.0.0",
38
- "mongodb": "^6.17.0",
39
- "mongoose": "^8.13.2",
40
- "pg": "^8.16.3",
41
- "prisma": "^6.12.0"
42
- },
43
- "devDependencies": {
44
- "@types/bcrypt": "^5.0.2",
45
- "@types/cors": "^2.8.18",
46
- "@types/express": "^4.17.17",
47
- "@types/mongodb": "^4.0.7",
48
- "@types/node": "^22.15.21",
49
- "@types/pg": "^8.15.4",
50
- "@types/supertest": "^6.0.3",
51
- "cors": "^2.8.5",
52
- "supertest": "^7.1.4",
53
- "ts-node-dev": "^2.0.0",
54
- "typescript": "^5.8.3",
55
- "vitest": "^3.1.1"
56
- },
57
- "peerDependencies": {
58
- "express": "^4.0.0"
59
- }
60
- }
1
+ {
2
+ "name": "streamby-core",
3
+ "version": "0.24.4",
4
+ "description": "StreamBy middleware framework for media storage management",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "scripts": {
11
+ "build": "tsc",
12
+ "test": "vitest",
13
+ "dev": "ts-node-dev --respawn --clear dev.ts",
14
+ "prepublishOnly": "npm run build"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://github.com/GwerhDev/StreamBy-Package.git"
19
+ },
20
+ "keywords": [
21
+ "streamby",
22
+ "middleware",
23
+ "upload",
24
+ "storage",
25
+ "s3",
26
+ "express",
27
+ "typescript"
28
+ ],
29
+ "author": "TerminalCore Labs",
30
+ "license": "MIT",
31
+ "dependencies": {
32
+ "@aws-sdk/client-s3": "^3.528.0",
33
+ "@aws-sdk/s3-request-presigner": "^3.787.0",
34
+ "@prisma/client": "^6.12.0",
35
+ "bcrypt": "^5.1.1",
36
+ "dotenv": "^16.5.0",
37
+ "express": "^4.0.0",
38
+ "mongodb": "^6.17.0",
39
+ "mongoose": "^8.13.2",
40
+ "pg": "^8.16.3",
41
+ "prisma": "^6.12.0"
42
+ },
43
+ "devDependencies": {
44
+ "@types/bcrypt": "^5.0.2",
45
+ "@types/cors": "^2.8.18",
46
+ "@types/express": "^4.17.17",
47
+ "@types/mongodb": "^4.0.7",
48
+ "@types/node": "^22.15.21",
49
+ "@types/pg": "^8.15.4",
50
+ "@types/supertest": "^6.0.3",
51
+ "cors": "^2.8.5",
52
+ "supertest": "^7.1.4",
53
+ "ts-node-dev": "^2.0.0",
54
+ "typescript": "^5.8.3",
55
+ "vitest": "^3.1.1"
56
+ },
57
+ "peerDependencies": {
58
+ "express": "^4.0.0"
59
+ }
60
+ }