Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,12 @@ Copy `.env.example` to `.env` and fill in the required values. The backend valid
| `AUDIT_LOG_PATH` | no | `./audit.log` | Path to append-only NDJSON audit log |
| `ANALYTICS_PORT` | no | `8001` | Python analytics service port |
| `BACKEND_URL` | no | `http://backend:4000` | Analytics service → backend base URL |
| `ANOMALY_THRESHOLD` | no | `50` | Mint count above which an issuer is flagged |
| `ANOMALY_SCHEDULE_MINUTES` | no | `15` | How often (minutes) the anomaly check runs |
| `ALERT_WEBHOOK_URL` | no | — | Webhook URL to POST alerts to (Slack/PagerDuty/email) |
| `ALERT_WEBHOOK_TYPE` | no | `slack` | Webhook payload format: `slack`, `pagerduty`, or `email` |
| `PAGERDUTY_ROUTING_KEY` | no | — | PagerDuty Events API v2 routing key (required when `ALERT_WEBHOOK_TYPE=pagerduty`) |
| `ALERT_EMAIL_TO` | no | — | Recipient address (required when `ALERT_WEBHOOK_TYPE=email`) |

For full descriptions, format rules, and examples see [docs/configuration.md](docs/configuration.md).

Expand Down
1,321 changes: 1,318 additions & 3 deletions backend/package-lock.json

Large diffs are not rendered by default.

6 changes: 5 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,11 @@
"jest": {
"setupFiles": [
"./tests/setup.js"
]
],
"moduleNameMapper": {
"^../secrets$": "<rootDir>/tests/__mocks__/secrets.js",
"^./secrets$": "<rootDir>/tests/__mocks__/secrets.js"
}
},
"devDependencies": {
"@faker-js/faker": "^8.4.1",
Expand Down
28 changes: 14 additions & 14 deletions backend/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,25 +19,25 @@ const eventsRoutes = require('./routes/events');
const apiVersion = require('./middleware/apiVersion');
const { getRpcServer } = require('./stellar/soroban');

const app = express();
const requestId = require('./middleware/requestId');

const app = express();

app.use(cors());
app.use(express.json({ limit: config.BODY_LIMIT }));
app.use(requestId);

/**
* Request logging middleware.
*
* Logs all incoming HTTP requests with method and path.
*
* @param {Object} req - Express request object
* @param {Object} res - Express response object
* @param {Function} next - Express next middleware function
*
* @side-effects Logs request information
*/
app.use((req, _res, next) => {
logger.info('request', { method: req.method, path: req.path });
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
logger.info('request', {
requestId: req.requestId,
method: req.method,
route: req.path,
statusCode: res.statusCode,
durationMs: Date.now() - start,
});
});
next();
});

Expand Down
4 changes: 3 additions & 1 deletion backend/src/logger.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
const { createLogger, format, transports } = require('winston');

const isProd = process.env.NODE_ENV === 'production';

const logger = createLogger({
level: process.env.LOG_LEVEL || 'info',
format: format.combine(
format.timestamp(),
format.errors({ stack: true }),
format.errors({ stack: !isProd }),
format.json()
),
defaultMeta: { service: 'backend' },
Expand Down
8 changes: 8 additions & 0 deletions backend/src/middleware/requestId.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const { randomUUID } = require('crypto');

module.exports = function requestId(req, res, next) {
const id = req.headers['x-request-id'] || randomUUID();
req.requestId = id;
res.setHeader('X-Request-ID', id);
next();
};
32 changes: 27 additions & 5 deletions backend/src/routes/vaccination.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ const issueSchema = z.object({
date_administered: z.string().refine((val) => !isNaN(Date.parse(val)), {
message: 'Invalid date format',
}),
dose_number: z.number().int().min(1).optional(),
dose_series: z.number().int().min(1).optional(),
});

const revokeSchema = z.object({
Expand Down Expand Up @@ -94,14 +96,20 @@ router.post(
issuerMiddleware,
validate(issueSchema),
async (req, res) => {
const { patient_address, vaccine_name, date_administered } = req.body;
const { patient_address, vaccine_name, date_administered, dose_number, dose_series } = req.body;

try {
const toOptU32 = (v) => v != null
? StellarSdk.xdr.ScVal.scvVec([StellarSdk.xdr.ScVal.scvU32(v)])
: StellarSdk.xdr.ScVal.scvVoid();

const args = [
StellarSdk.Address.fromString(patient_address).toScVal(),
StellarSdk.xdr.ScVal.scvString(vaccine_name),
StellarSdk.xdr.ScVal.scvString(date_administered),
StellarSdk.Address.fromString(req.user.publicKey).toScVal(),
toOptU32(dose_number),
toOptU32(dose_series),
];

const result = await invokeContract(process.env.ISSUER_SECRET_KEY, 'mint_vaccination', args);
Expand All @@ -113,7 +121,7 @@ router.post(
action: 'vaccination.issue',
target: patient_address,
result: 'success',
meta: { token_id: tokenId, vaccine_name, date_administered },
meta: { token_id: tokenId, vaccine_name, date_administered, dose_number, dose_series },
});

res.json({
Expand Down Expand Up @@ -259,16 +267,30 @@ router.post(
* schema:
* $ref: '#/components/schemas/Error'
*/
// GET /vaccination/:wallet — fetch all records for a wallet
// GET /vaccination/:wallet — fetch paginated records for a wallet
router.get('/:wallet', authMiddleware, validateStellarPublicKey('params', 'wallet', 'wallet'), async (req, res) => {
const { wallet } = req.params;

const rawPage = req.query.page !== undefined ? Number(req.query.page) : 1;
const rawLimit = req.query.limit !== undefined ? Number(req.query.limit) : 20;

if (!Number.isInteger(rawPage) || rawPage < 1) {
return res.status(400).json({ error: 'page must be a positive integer' });
}
if (!Number.isInteger(rawLimit) || rawLimit < 1 || rawLimit > 100) {
return res.status(400).json({ error: 'limit must be an integer between 1 and 100' });
}

try {
const args = [StellarSdk.Address.fromString(wallet).toScVal()];
const result = await simulateContract('verify_vaccination', args);
const [vaccinated, records] = StellarSdk.scValToNative(result);
const [vaccinated, allRecords] = StellarSdk.scValToNative(result);

const total = allRecords.length;
const start = (rawPage - 1) * rawLimit;
const data = allRecords.slice(start, start + rawLimit);

res.json({ wallet, vaccinated, records });
res.json({ data, total, page: rawPage, limit: rawLimit });
} catch (err) {
res.status(500).json({ error: err.message });
}
Expand Down
4 changes: 4 additions & 0 deletions backend/tests/__mocks__/secrets.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
initializeSecrets: jest.fn().mockResolvedValue(undefined),
loadSecretsFromAWS: jest.fn().mockResolvedValue({}),
};
Loading