structure
This commit is contained in:
parent
3236b348c5
commit
9d44572c0c
9
.editorconfig
Normal file
9
.editorconfig
Normal file
@ -0,0 +1,9 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
44
.gitignore
vendored
44
.gitignore
vendored
@ -1,47 +1,15 @@
|
||||
# Node modules
|
||||
node_modules/
|
||||
|
||||
# Environment variables
|
||||
.env
|
||||
.env.*.local
|
||||
|
||||
# Logs
|
||||
logs
|
||||
.env.*
|
||||
logs/
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# Debug
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# OS & Editor settings
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
.vscode/
|
||||
.idea/
|
||||
*.sublime-project
|
||||
*.sublime-workspace
|
||||
|
||||
# Build output
|
||||
dist/
|
||||
build/
|
||||
tmp/
|
||||
temp/
|
||||
|
||||
# Database files (if local DB is used)
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
|
||||
# Coverage / testing
|
||||
coverage/
|
||||
.nyc_output/
|
||||
jest-*
|
||||
|
||||
# Misc
|
||||
*.local
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.DS_Store
|
||||
.idea/
|
||||
.vscode/
|
||||
public/uploads/
|
||||
|
||||
47
CODE_OF_CONDUCT.md
Normal file
47
CODE_OF_CONDUCT.md
Normal file
@ -0,0 +1,47 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our community include:
|
||||
|
||||
- Demonstrating empathy and kindness toward other people
|
||||
- Being respectful of differing opinions, viewpoints, and experiences
|
||||
- Giving and gracefully accepting constructive feedback
|
||||
- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
|
||||
- Focusing on what is best not just for us as individuals, but for the overall community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
- The use of sexualized language or imagery, and sexual attention or advances of any kind
|
||||
- Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
- Public or private harassment
|
||||
- Publishing others’ private information, such as a physical or email address, without their explicit permission
|
||||
- Other conduct which could reasonably be considered inappropriate in a professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT EMAIL ADDRESS].
|
||||
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at https://www.contributor-covenant.org/version/2/1/code_of_conduct.html.
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
27
CONTRIBUTING.md
Normal file
27
CONTRIBUTING.md
Normal file
@ -0,0 +1,27 @@
|
||||
# Contributing to Guardian AI Backend
|
||||
|
||||
Thank you for considering contributing! Please follow these guidelines:
|
||||
|
||||
## Getting Started
|
||||
- Fork the repo and clone locally.
|
||||
- Create a new branch for your feature or bugfix.
|
||||
- Install dependencies with `npm install`.
|
||||
|
||||
## Code Style
|
||||
- Use Prettier and EditorConfig for formatting.
|
||||
- Write clear, modular code and add comments where helpful.
|
||||
- Use environment variables for all secrets/config.
|
||||
|
||||
## Commits & PRs
|
||||
- Write descriptive commit messages.
|
||||
- Reference issues in your PRs if applicable.
|
||||
- Ensure all tests pass before submitting a PR.
|
||||
|
||||
## Issues
|
||||
- Use GitHub Issues for bugs and feature requests.
|
||||
- Provide as much detail as possible.
|
||||
|
||||
## Code of Conduct
|
||||
- Be respectful and inclusive.
|
||||
|
||||
Thank you for helping make Guardian AI better!
|
||||
21
LICENSE
Normal file
21
LICENSE
Normal file
@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Guardian AI
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
100
README.md
Normal file
100
README.md
Normal file
@ -0,0 +1,100 @@
|
||||
# Guardian AI Backend
|
||||
|
||||
A scalable, production-ready Node.js backend using Express, MySQL, and Sequelize, following a modular MVC architecture. Features include JWT authentication, role-based access, Stripe payments, real-time alerts, and more.
|
||||
|
||||
---
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
├── public/ # Static files
|
||||
├── src/
|
||||
│ ├── config/ # App and DB config
|
||||
│ ├── controllers/ # Route controllers
|
||||
│ ├── middlewares/ # Express middlewares (auth, validation, etc.)
|
||||
│ ├── migrations/ # Sequelize migrations
|
||||
│ ├── models/ # Sequelize models
|
||||
│ ├── routes/ # Express route definitions
|
||||
│ ├── services/ # Business logic/services (Stripe, email, etc.)
|
||||
│ ├── sockets/ # Socket.IO logic
|
||||
│ ├── utils/ # Utility/helper functions
|
||||
│ └── seeders/ # Sequelize seed scripts
|
||||
├── .env.example # Example environment variables
|
||||
├── package.json # Project dependencies and scripts
|
||||
├── server.js # Main server entry point
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Getting Started
|
||||
|
||||
1. **Clone the repo:**
|
||||
```bash
|
||||
git clone <repo-url>
|
||||
cd guardian-ai
|
||||
```
|
||||
2. **Install dependencies:**
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
3. **Configure environment:**
|
||||
- Copy `.env.example` to `.env` and fill in your values.
|
||||
4. **Run migrations & seeders:**
|
||||
```bash
|
||||
npx sequelize-cli db:migrate
|
||||
npx sequelize-cli db:seed:all
|
||||
```
|
||||
5. **Start the server:**
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
6. **API Docs:**
|
||||
- Visit [http://localhost:3000/api/v1/docs](http://localhost:3000/api/v1/docs) for Swagger API documentation.
|
||||
|
||||
---
|
||||
|
||||
## Authentication & Authorization
|
||||
- Uses JWT for authentication.
|
||||
- Role-based access: `admin`, `caregiver`, `patient`.
|
||||
- Middleware in `src/middlewares/auth.js` protects routes and checks roles.
|
||||
|
||||
---
|
||||
|
||||
## Payments (Stripe)
|
||||
- Stripe integration for subscriptions, invoices, and webhooks.
|
||||
- All logic in `src/services/stripeService.js` and related controllers/routes.
|
||||
|
||||
---
|
||||
|
||||
## Real-Time & Notifications
|
||||
- Uses Socket.IO for real-time caregiver alerts (`src/sockets/`).
|
||||
- Weekly summary emails sent via Nodemailer (`src/services/weeklySummaryService.js`).
|
||||
|
||||
---
|
||||
|
||||
## Retell API Encryption
|
||||
- All Retell API access is protected by an encrypted key.
|
||||
- Use `src/utils/retellEncryption.js` to generate and verify keys (AES-256).
|
||||
- Generate a key with:
|
||||
```bash
|
||||
node src/scripts/generateRetellKey.js '{"userId":123}'
|
||||
```
|
||||
- Add `RETELL_ENCRYPTION_KEY` (32 bytes) to your `.env`.
|
||||
|
||||
---
|
||||
|
||||
## Scripts
|
||||
- `npm run dev` — Start in dev mode
|
||||
- `npx sequelize-cli db:migrate` — Run migrations
|
||||
- `npx sequelize-cli db:seed:all` — Seed test data
|
||||
|
||||
---
|
||||
|
||||
## Contributing
|
||||
- See `CONTRIBUTING.md` and `CODE_OF_CONDUCT.md` for guidelines.
|
||||
- Use Prettier and EditorConfig for code style.
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
MIT — see `LICENSE` file.
|
||||
3338
package-lock.json
generated
Normal file
3338
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
@ -22,7 +22,9 @@
|
||||
"nodemailer": "^6.9.8",
|
||||
"sequelize": "^6.37.1",
|
||||
"socket.io": "^4.7.5",
|
||||
"stripe": "^14.23.0"
|
||||
"stripe": "^14.23.0",
|
||||
"swagger-jsdoc": "^6.2.8",
|
||||
"swagger-ui-express": "^5.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"nodemon": "^3.0.3",
|
||||
@ -30,4 +32,4 @@
|
||||
},
|
||||
"author": "Guardian AI Team",
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
|
||||
8
prettier.config.js
Normal file
8
prettier.config.js
Normal file
@ -0,0 +1,8 @@
|
||||
module.exports = {
|
||||
semi: true,
|
||||
singleQuote: true,
|
||||
trailingComma: 'all',
|
||||
printWidth: 100,
|
||||
tabWidth: 2,
|
||||
endOfLine: 'lf',
|
||||
};
|
||||
34
src/models/tier.js
Normal file
34
src/models/tier.js
Normal file
@ -0,0 +1,34 @@
|
||||
module.exports = (sequelize, DataTypes) => {
|
||||
const Tier = sequelize.define('Tier', {
|
||||
id: {
|
||||
type: DataTypes.INTEGER,
|
||||
autoIncrement: true,
|
||||
primaryKey: true,
|
||||
},
|
||||
name: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: false,
|
||||
},
|
||||
contactsLimit: {
|
||||
type: DataTypes.INTEGER,
|
||||
allowNull: false,
|
||||
},
|
||||
price: {
|
||||
type: DataTypes.DECIMAL(10,2),
|
||||
allowNull: false,
|
||||
},
|
||||
description: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: true,
|
||||
},
|
||||
}, {
|
||||
tableName: 'tiers',
|
||||
timestamps: true,
|
||||
});
|
||||
|
||||
Tier.associate = (models) => {
|
||||
Tier.hasMany(models.User, { foreignKey: 'tierId', as: 'caregivers' });
|
||||
};
|
||||
|
||||
return Tier;
|
||||
};
|
||||
49
src/models/user.js
Normal file
49
src/models/user.js
Normal file
@ -0,0 +1,49 @@
|
||||
module.exports = (sequelize, DataTypes) => {
|
||||
const User = sequelize.define('User', {
|
||||
id: {
|
||||
type: DataTypes.INTEGER,
|
||||
autoIncrement: true,
|
||||
primaryKey: true,
|
||||
},
|
||||
name: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: false,
|
||||
},
|
||||
email: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: false,
|
||||
unique: true,
|
||||
validate: { isEmail: true },
|
||||
},
|
||||
password: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: false,
|
||||
},
|
||||
role: {
|
||||
type: DataTypes.ENUM('admin', 'caregiver', 'patient'),
|
||||
allowNull: false,
|
||||
defaultValue: 'caregiver',
|
||||
},
|
||||
notificationOptIn: {
|
||||
type: DataTypes.BOOLEAN,
|
||||
defaultValue: true,
|
||||
},
|
||||
tierId: {
|
||||
type: DataTypes.INTEGER,
|
||||
allowNull: true,
|
||||
},
|
||||
}, {
|
||||
tableName: 'users',
|
||||
timestamps: true,
|
||||
});
|
||||
|
||||
User.associate = (models) => {
|
||||
User.hasMany(models.CaregiverPatient, { foreignKey: 'caregiverId', as: 'patients' });
|
||||
User.hasMany(models.CaregiverPatient, { foreignKey: 'patientId', as: 'caregivers' });
|
||||
User.hasMany(models.Call, { foreignKey: 'caregiverId', as: 'calls' });
|
||||
User.hasMany(models.Call, { foreignKey: 'patientId', as: 'patientCalls' });
|
||||
User.belongsTo(models.Tier, { foreignKey: 'tierId', as: 'tier' });
|
||||
};
|
||||
|
||||
return User;
|
||||
};
|
||||
@ -1 +1,8 @@
|
||||
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const swaggerUi = require('swagger-ui-express');
|
||||
const swaggerSpec = require('../config/swagger');
|
||||
|
||||
router.use('/', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
|
||||
|
||||
module.exports = router;
|
||||
@ -1 +1,14 @@
|
||||
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const stripeController = require('../controllers/stripeController');
|
||||
const { authenticateJWT, authorizeRoles } = require('../middlewares/auth');
|
||||
|
||||
router.use(authenticateJWT, authorizeRoles('caregiver'));
|
||||
|
||||
router.post('/subscribe', stripeController.subscribe);
|
||||
router.get('/invoices', stripeController.invoices);
|
||||
|
||||
// Webhook (no auth)
|
||||
router.post('/webhook', express.raw({ type: 'application/json' }), stripeController.webhook);
|
||||
|
||||
module.exports = router;
|
||||
18
src/scripts/generateRetellKey.js
Normal file
18
src/scripts/generateRetellKey.js
Normal file
@ -0,0 +1,18 @@
|
||||
const { generateEncryptedKey } = require('../utils/retellEncryption');
|
||||
|
||||
const input = process.argv[2];
|
||||
if (!input) {
|
||||
console.error('Usage: node src/scripts/generateRetellKey.js "{\"userId\":123}"');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let payload;
|
||||
try {
|
||||
payload = JSON.parse(input);
|
||||
} catch (e) {
|
||||
console.error('Invalid JSON payload');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const encryptedKey = generateEncryptedKey(payload);
|
||||
console.log('Encrypted Key:', encryptedKey);
|
||||
@ -1 +1,6 @@
|
||||
|
||||
module.exports = (io) => {
|
||||
io.on('connection', (socket) => {
|
||||
// Example: socket.join(`caregiver_${userId}`) after authentication
|
||||
socket.on('disconnect', () => {});
|
||||
});
|
||||
};
|
||||
23
src/utils/retellEncryption.js
Normal file
23
src/utils/retellEncryption.js
Normal file
@ -0,0 +1,23 @@
|
||||
const crypto = require('crypto');
|
||||
const ENCRYPTION_KEY = process.env.RETELL_ENCRYPTION_KEY || 'default_secret_key_32byteslong!'; // 32 bytes for AES-256
|
||||
const IV_LENGTH = 16; // AES block size
|
||||
|
||||
// Generate an encrypted key (e.g., for a user/session)
|
||||
exports.generateEncryptedKey = (payload) => {
|
||||
const iv = crypto.randomBytes(IV_LENGTH);
|
||||
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(ENCRYPTION_KEY), iv);
|
||||
let encrypted = cipher.update(JSON.stringify(payload));
|
||||
encrypted = Buffer.concat([encrypted, cipher.final()]);
|
||||
return iv.toString('hex') + ':' + encrypted.toString('hex');
|
||||
};
|
||||
|
||||
// Decrypt and verify the encrypted key
|
||||
exports.verifyEncryptedKey = (encryptedKey) => {
|
||||
const [ivHex, encryptedHex] = encryptedKey.split(':');
|
||||
const iv = Buffer.from(ivHex, 'hex');
|
||||
const encryptedText = Buffer.from(encryptedHex, 'hex');
|
||||
const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(ENCRYPTION_KEY), iv);
|
||||
let decrypted = decipher.update(encryptedText);
|
||||
decrypted = Buffer.concat([decrypted, decipher.final()]);
|
||||
return JSON.parse(decrypted.toString());
|
||||
};
|
||||
Loading…
Reference in New Issue
Block a user