Compare commits

..

22 Commits

Author SHA1 Message Date
Dave Horton
ab7c69c0e8 fix test case 2021-05-07 08:38:54 -04:00
Dave Horton
fc61d3d2fa add integration test 2021-05-07 08:33:13 -04:00
Dave Horton
081a83e121 add some columns to voip_carriers 2021-04-16 15:07:54 -04:00
Dave Horton
7e6261eec8 fixes for updating/deleting registration hook 2021-02-21 11:27:40 -05:00
Dave Horton
5f10ef585f REST createCall must use absolute url in call_hook and call_status_hook 2021-02-19 11:47:03 -05:00
Dave Horton
c9eeb41eb6 fix bug in retrieving phone number by sid 2021-02-19 09:23:29 -05:00
Dave Horton
843e1e4e80 account level users can only add phone numbers to their carriers 2021-02-19 08:53:45 -05:00
Dave Horton
fb86875576 update call now uses POST, plus bugfix #6 2021-02-19 08:52:27 -05:00
Dave Horton
e633de5d4a Merge pull request #5 from radicaldrew/master
Updated Dockerfile
2020-12-30 08:50:46 -05:00
Andrew
d8ac0a7aa2 Updated Dockerfile
Create multi stage build and tested with compose
2020-12-30 15:45:24 +02:00
Dave Horton
0da3bf94a6 Merge pull request #4 from jambonz/gh-actions
migrate to gh actions
2020-12-14 16:06:59 -05:00
Dave Horton
4e9b079f0d update ci badge 2020-12-14 16:04:05 -05:00
Dave Horton
7876b0efa6 migrate to gh actions 2020-12-14 16:01:16 -05:00
Dave Horton
dd53a62457 swagger updates 2020-12-11 10:47:52 -05:00
Dave Horton
09928597e0 include account_sid in createCall and createMessage sent to fs 2020-12-11 10:42:01 -05:00
Dave Horton
484fa7841a updated API with new properties for voip_carriers that require outbound registration 2020-12-11 10:34:34 -05:00
Dave Horton
c578757dd2 bugfix for REST outdial to teams 2020-11-24 10:07:35 -05:00
Dave Horton
6b01f7f07e swagger bugfix: createAccount and updateAccount changes 2020-11-11 15:41:03 -05:00
Dave Horton
93ddaf86d2 deps 2020-10-26 12:03:07 -04:00
Dave Horton
6e0fc76281 deps 2020-10-26 10:06:43 -04:00
Dave Horton
ea64fb1a58 add sms messaging support 2020-10-09 08:04:39 -04:00
Dave Horton
53763aae14 bugfix: createCall REST API to Teams endpoint was being blocked 2020-09-30 15:37:49 -04:00
31 changed files with 460 additions and 127 deletions

View File

@@ -8,7 +8,7 @@
"jsx": false,
"modules": false
},
"ecmaVersion": 2017
"ecmaVersion": 2018
},
"plugins": ["promise"],
"rules": {

19
.github/workflows/npm-publish.yml vendored Normal file
View File

@@ -0,0 +1,19 @@
name: CI
on:
push:
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: 12
- run: npm install
- run: npm run jslint
- run: npm test

View File

@@ -1,8 +0,0 @@
dist: bionic
language: node_js
node_js:
- "lts/*"
services:
- mysql
script:
- npm test

View File

@@ -1,13 +1,16 @@
FROM node:lts-alpine
FROM node:alpine as builder
RUN apk update && apk add --no-cache python make g++
WORKDIR /opt/app/
COPY package.json ./
RUN npm install
RUN npm prune
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
FROM node:alpine as app
WORKDIR /opt/app
COPY . /opt/app
COPY --from=builder /opt/app/node_modules ./node_modules
ARG NODE_ENV
ENV NODE_ENV $NODE_ENV
COPY package.json /usr/src/app/
RUN npm install
COPY . /usr/src/app
CMD [ "npm", "start" ]

View File

@@ -1,4 +1,4 @@
# jambones-api-server [![Build Status](https://secure.travis-ci.org/jambonz/jambones-api-server.png)](http://travis-ci.org/jambonz/jambones-api-server)
# jambonz-api-server ![Build Status](https://github.com/jambonz/jambonz-api-server/workflows/CI/badge.svg)
Jambones REST API server.

1
app.js
View File

@@ -38,6 +38,7 @@ const {
} = require('@jambonz/db-helpers')({
host: process.env.JAMBONES_MYSQL_HOST,
user: process.env.JAMBONES_MYSQL_USER,
port: process.env.JAMBONES_MYSQL_PORT || 3306,
password: process.env.JAMBONES_MYSQL_PASSWORD,
database: process.env.JAMBONES_MYSQL_DATABASE,
connectionLimit: process.env.JAMBONES_MYSQL_CONNECTION_LIMIT || 10

View File

@@ -1,3 +1,3 @@
create database jambones_test;
create user jambones_test@localhost IDENTIFIED WITH mysql_native_password by 'jambones_test';
grant all on jambones_test.* to jambones_test@localhost;
create user jambones_test@'%' IDENTIFIED WITH mysql_native_password by 'jambones_test';
grant all on jambones_test.* to jambones_test@'%';

View File

@@ -38,7 +38,7 @@ account_sid CHAR(36) NOT NULL,
regex VARCHAR(255) NOT NULL,
application_sid CHAR(36) NOT NULL,
PRIMARY KEY (call_route_sid)
) ENGINE=InnoDB COMMENT='a regex-based pattern match for call routing';
) COMMENT='a regex-based pattern match for call routing';
CREATE TABLE lcr_routes
(
@@ -55,11 +55,11 @@ api_key_sid CHAR(36) NOT NULL UNIQUE ,
token CHAR(36) NOT NULL UNIQUE ,
account_sid CHAR(36),
service_provider_sid CHAR(36),
expires_at TIMESTAMP NULL,
last_used TIMESTAMP NULL,
expires_at TIMESTAMP NULL DEFAULT NULL,
last_used TIMESTAMP NULL DEFAULT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (api_key_sid)
) ENGINE=InnoDB COMMENT='An authorization token that is used to access the REST api';
) COMMENT='An authorization token that is used to access the REST api';
CREATE TABLE ms_teams_tenants
(
@@ -98,8 +98,15 @@ description VARCHAR(255),
account_sid CHAR(36) COMMENT 'if provided, indicates this entity represents a customer PBX that is associated with a specific account',
application_sid CHAR(36) COMMENT 'If provided, all incoming calls from this source will be routed to the associated application',
e164_leading_plus BOOLEAN NOT NULL DEFAULT false,
requires_register BOOLEAN NOT NULL DEFAULT false,
register_username VARCHAR(64),
register_sip_realm VARCHAR(64),
register_password VARCHAR(64),
tech_prefix VARCHAR(16),
diversion VARCHAR(32),
is_active BOOLEAN NOT NULL DEFAULT true,
PRIMARY KEY (voip_carrier_sid)
) ENGINE=InnoDB COMMENT='A Carrier or customer PBX that can send or receive calls';
) COMMENT='A Carrier or customer PBX that can send or receive calls';
CREATE TABLE phone_numbers
(
@@ -157,7 +164,7 @@ speech_synthesis_voice VARCHAR(64),
speech_recognizer_vendor VARCHAR(64) NOT NULL DEFAULT 'google',
speech_recognizer_language VARCHAR(64) NOT NULL DEFAULT 'en-US',
PRIMARY KEY (application_sid)
) ENGINE=InnoDB COMMENT='A defined set of behaviors to be applied to phone calls ';
) COMMENT='A defined set of behaviors to be applied to phone calls ';
CREATE TABLE service_providers
(
@@ -168,7 +175,7 @@ root_domain VARCHAR(128) UNIQUE ,
registration_hook_sid CHAR(36),
ms_teams_fqdn VARCHAR(255),
PRIMARY KEY (service_provider_sid)
) ENGINE=InnoDB COMMENT='A partition of the platform used by one service provider';
) COMMENT='A partition of the platform used by one service provider';
CREATE TABLE accounts
(
@@ -179,8 +186,10 @@ service_provider_sid CHAR(36) NOT NULL COMMENT 'service provider that owns the c
registration_hook_sid CHAR(36) COMMENT 'webhook to call when devices underr this account attempt to register',
device_calling_application_sid CHAR(36) COMMENT 'application to use for outbound calling from an account',
is_active BOOLEAN NOT NULL DEFAULT true,
webhook_secret VARCHAR(36),
disable_cdrs BOOLEAN NOT NULL DEFAULT 0,
PRIMARY KEY (account_sid)
) ENGINE=InnoDB COMMENT='An enterprise that uses the platform for comm services';
) COMMENT='An enterprise that uses the platform for comm services';
CREATE INDEX call_route_sid_idx ON call_routes (call_route_sid);
ALTER TABLE call_routes ADD FOREIGN KEY account_sid_idxfk (account_sid) REFERENCES accounts (account_sid);

View File

@@ -56,14 +56,13 @@
<name><![CDATA[voip_carriers]]></name>
<schema><![CDATA[]]></schema>
<comment><![CDATA[A Carrier or customer PBX that can send or receive calls]]></comment>
<tableType><![CDATA[InnoDB]]></tableType>
<location>
<x>417.00</x>
<y>263.00</y>
</location>
<size>
<width>266.00</width>
<height>140.00</height>
<height>280.00</height>
</size>
<zorder>6</zorder>
<SQLField>
@@ -126,6 +125,45 @@
<notNull><![CDATA[1]]></notNull>
<uid><![CDATA[123EA4AC-627B-42A1-8779-D72494E8D47F]]></uid>
</SQLField>
<SQLField>
<name><![CDATA[requires_register]]></name>
<type><![CDATA[BOOLEAN]]></type>
<defaultValue><![CDATA[false]]></defaultValue>
<notNull><![CDATA[1]]></notNull>
<uid><![CDATA[B694DA3E-F58D-44C5-980F-E0CFBE6DFA02]]></uid>
</SQLField>
<SQLField>
<name><![CDATA[register_username]]></name>
<type><![CDATA[VARCHAR(64)]]></type>
<uid><![CDATA[7EA13180-1746-44F5-8699-6099D5D29018]]></uid>
</SQLField>
<SQLField>
<name><![CDATA[register_sip_realm]]></name>
<type><![CDATA[VARCHAR(64)]]></type>
<uid><![CDATA[163F2E47-6536-4A30-BD0A-4BBAA5AB4214]]></uid>
</SQLField>
<SQLField>
<name><![CDATA[register_password]]></name>
<type><![CDATA[VARCHAR(64)]]></type>
<uid><![CDATA[3699DD5F-20F9-4650-86EB-A08A90894C59]]></uid>
</SQLField>
<SQLField>
<name><![CDATA[tech_prefix]]></name>
<type><![CDATA[VARCHAR(16)]]></type>
<uid><![CDATA[58305E16-A895-4E7B-866F-F2A7BAD8B609]]></uid>
</SQLField>
<SQLField>
<name><![CDATA[diversion]]></name>
<type><![CDATA[VARCHAR(32)]]></type>
<uid><![CDATA[33E3BA51-A9A6-40D2-BAF8-F8E67CC9DD13]]></uid>
</SQLField>
<SQLField>
<name><![CDATA[is_active]]></name>
<type><![CDATA[BOOLEAN]]></type>
<defaultValue><![CDATA[true]]></defaultValue>
<notNull><![CDATA[1]]></notNull>
<uid><![CDATA[8A6DFB34-1620-4DA6-AB6A-FFA79F71D110]]></uid>
</SQLField>
<labelWindowIndex><![CDATA[8]]></labelWindowIndex>
<objectComment><![CDATA[A Carrier or customer PBX that can send or receive calls]]></objectComment>
<ui.treeExpanded><![CDATA[1]]></ui.treeExpanded>
@@ -135,7 +173,6 @@
<name><![CDATA[api_keys]]></name>
<schema><![CDATA[]]></schema>
<comment><![CDATA[An authorization token that is used to access the REST api]]></comment>
<tableType><![CDATA[InnoDB]]></tableType>
<location>
<x>1319.00</x>
<y>38.00</y>
@@ -269,10 +306,9 @@
<name><![CDATA[call_routes]]></name>
<schema><![CDATA[]]></schema>
<comment><![CDATA[a regex-based pattern match for call routing]]></comment>
<tableType><![CDATA[InnoDB]]></tableType>
<location>
<x>424.00</x>
<y>461.00</y>
<x>407.00</x>
<y>584.00</y>
</location>
<size>
<width>254.00</width>
@@ -487,14 +523,13 @@
<name><![CDATA[accounts]]></name>
<schema><![CDATA[]]></schema>
<comment><![CDATA[An enterprise that uses the platform for comm services]]></comment>
<tableType><![CDATA[InnoDB]]></tableType>
<location>
<x>825.00</x>
<y>321.00</y>
</location>
<size>
<width>380.00</width>
<height>160.00</height>
<height>200.00</height>
</size>
<zorder>4</zorder>
<SQLField>
@@ -576,6 +611,19 @@
<notNull><![CDATA[1]]></notNull>
<uid><![CDATA[C7130A90-DBB4-424D-A9A9-CB203C32350C]]></uid>
</SQLField>
<SQLField>
<name><![CDATA[webhook_secret]]></name>
<type><![CDATA[VARCHAR(36)]]></type>
<notNull><![CDATA[0]]></notNull>
<uid><![CDATA[CF25660D-AACA-4783-8A13-C7393D3B3D95]]></uid>
</SQLField>
<SQLField>
<name><![CDATA[disable_cdrs]]></name>
<type><![CDATA[BOOLEAN]]></type>
<defaultValue><![CDATA[0]]></defaultValue>
<notNull><![CDATA[1]]></notNull>
<uid><![CDATA[341B2A8D-AE85-4FCA-8EA8-D6E6149511F4]]></uid>
</SQLField>
<labelWindowIndex><![CDATA[11]]></labelWindowIndex>
<objectComment><![CDATA[An enterprise that uses the platform for comm services]]></objectComment>
<ui.treeExpanded><![CDATA[1]]></ui.treeExpanded>
@@ -587,8 +635,8 @@
<comment><![CDATA[A phone number that has been assigned to an account]]></comment>
<tableType><![CDATA[InnoDB]]></tableType>
<location>
<x>385.00</x>
<y>625.00</y>
<x>360.00</x>
<y>753.00</y>
</location>
<size>
<width>331.00</width>
@@ -759,7 +807,6 @@
<name><![CDATA[applications]]></name>
<schema><![CDATA[]]></schema>
<comment><![CDATA[A defined set of behaviors to be applied to phone calls ]]></comment>
<tableType><![CDATA[InnoDB]]></tableType>
<location>
<x>829.00</x>
<y>568.00</y>
@@ -1021,7 +1068,6 @@
<name><![CDATA[service_providers]]></name>
<schema><![CDATA[]]></schema>
<comment><![CDATA[A partition of the platform used by one service provider]]></comment>
<tableType><![CDATA[InnoDB]]></tableType>
<location>
<x>838.00</x>
<y>96.00</y>
@@ -1099,17 +1145,17 @@
<overviewPanelHidden><![CDATA[0]]></overviewPanelHidden>
<pageBoundariesVisible><![CDATA[0]]></pageBoundariesVisible>
<PageGridVisible><![CDATA[0]]></PageGridVisible>
<RightSidebarWidth><![CDATA[1924.000000]]></RightSidebarWidth>
<RightSidebarWidth><![CDATA[1213.000000]]></RightSidebarWidth>
<sidebarIndex><![CDATA[2]]></sidebarIndex>
<snapToGrid><![CDATA[0]]></snapToGrid>
<SourceSidebarWidth><![CDATA[0.000000]]></SourceSidebarWidth>
<SQLEditorFileFormatVersion><![CDATA[4]]></SQLEditorFileFormatVersion>
<uid><![CDATA[58C99A00-06C9-478C-A667-C63842E088F3]]></uid>
<windowHeight><![CDATA[1013.000000]]></windowHeight>
<windowLocationX><![CDATA[2716.000000]]></windowLocationX>
<windowLocationY><![CDATA[1913.000000]]></windowLocationY>
<windowScrollOrigin><![CDATA[{0, 5}]]></windowScrollOrigin>
<windowWidth><![CDATA[2201.000000]]></windowWidth>
<windowHeight><![CDATA[977.000000]]></windowHeight>
<windowLocationX><![CDATA[2718.000000]]></windowLocationX>
<windowLocationY><![CDATA[1891.000000]]></windowLocationY>
<windowScrollOrigin><![CDATA[{369.5, 4}]]></windowScrollOrigin>
<windowWidth><![CDATA[1490.000000]]></windowWidth>
</SQLDocumentInfo>
<AllowsIndexRenamingOnInsert><![CDATA[1]]></AllowsIndexRenamingOnInsert>
<defaultLabelExpanded><![CDATA[1]]></defaultLabelExpanded>

View File

@@ -2,6 +2,7 @@ const mysql = require('mysql2');
const pool = mysql.createPool({
host: process.env.JAMBONES_MYSQL_HOST,
user: process.env.JAMBONES_MYSQL_USER,
port: process.env.JAMBONES_MYSQL_PORT || 3306,
password: process.env.JAMBONES_MYSQL_PASSWORD,
database: process.env.JAMBONES_MYSQL_DATABASE,
connectionLimit: process.env.JAMBONES_MYSQL_CONNECTION_LIMIT || 10

View File

@@ -33,6 +33,22 @@ VoipCarrier.fields = [
{
name: 'e164_leading_plus',
type: 'number'
},
{
name: 'requires_register',
type: 'number'
},
{
name: 'register_username',
type: 'string'
},
{
name: 'register_sip_realm',
type: 'string'
},
{
name: 'register_password',
type: 'string'
}
];

View File

@@ -43,6 +43,7 @@ function validateUpdateCall(opts) {
const hasWhisper = opts.whisper;
const count = [
'call_hook',
'child_call_hook',
'call_status',
'listen_status',
'mute_status']
@@ -56,11 +57,13 @@ function validateUpdateCall(opts) {
case 1:
// good
break;
case 2:
if (opts.call_hook && opts.child_call_hook) break;
// eslint-disable-next-line no-fallthrough
default:
throw new DbErrorBadRequest('multiple options are not allowed in updateCall');
}
if (opts.call_hook && !opts.call_hook.url) throw new DbErrorBadRequest('missing call_hook.url');
if (opts.call_status && !['completed', 'no-answer'].includes(opts.call_status)) {
throw new DbErrorBadRequest('invalid call_status');
}
@@ -131,8 +134,34 @@ async function validateCreateCall(logger, sid, req) {
});
}
if (!obj.call_hook || (obj.call_hook && !obj.call_hook.url)) {
throw new DbErrorBadRequest('either url or application_sid required');
if (!obj.call_hook && !obj.application_sid) {
throw new DbErrorBadRequest('either call_hook or application_sid required');
}
if (typeof obj.call_hook === 'string') {
const url = obj.call_hook;
obj.call_hook = {
url,
method: 'POST'
};
}
if (typeof obj.call_status_hook === 'string') {
const url = obj.call_status_hook;
obj.call_status_hook = {
url,
method: 'POST'
};
}
if (typeof obj.call_hook === 'object' && typeof obj.call_hook.url != 'string') {
throw new DbErrorBadRequest('call_hook must be string or an object containing a url property');
}
if (typeof obj.call_status_hook === 'object' && typeof obj.call_status_hook.url != 'string') {
throw new DbErrorBadRequest('call_status_hook must be string or an object containing a url property');
}
if (obj.call_hook && !/^https?:/.test(obj.call_hook.url)) {
throw new DbErrorBadRequest('call_hook url be an absolute url');
}
if (obj.call_status_hook && !/^https?:/.test(obj.call_status_hook.url)) {
throw new DbErrorBadRequest('call_status_hook url be an absolute url');
}
}
@@ -263,31 +292,49 @@ router.put('/:sid', async(req, res) => {
const sid = req.params.sid;
const logger = req.app.locals.logger;
try {
// create webhooks if provided
const obj = Object.assign({}, req.body);
for (const prop of ['registration_hook']) {
if (prop in obj && Object.keys(obj[prop]).length) {
if ('webhook_sid' in obj[prop]) {
const sid = obj[prop]['webhook_sid'];
delete obj[prop]['webhook_sid'];
await Webhook.update(sid, obj[prop]);
if (null !== obj.registration_hook) {
for (const prop of ['registration_hook']) {
if (prop in obj && Object.keys(obj[prop]).length) {
if ('webhook_sid' in obj[prop]) {
const sid = obj[prop]['webhook_sid'];
delete obj[prop]['webhook_sid'];
await Webhook.update(sid, obj[prop]);
}
else {
const sid = await Webhook.make(obj[prop]);
obj[`${prop}_sid`] = sid;
}
}
else {
const sid = await Webhook.make(obj[prop]);
obj[`${prop}_sid`] = sid;
obj[`${prop}_sid`] = null;
}
delete obj[prop];
}
else {
obj[`${prop}_sid`] = null;
}
delete obj[prop];
}
await validateUpdate(req, sid);
const rowsAffected = await Account.update(sid, obj);
if (rowsAffected === 0) {
return res.status(404).end();
if (Object.keys(obj).length) {
let orphanedHook;
if (null === obj.registration_hook) {
const results = await Account.retrieve(sid);
if (results.length && results[0].registration_hook_sid) orphanedHook = results[0].registration_hook_sid;
obj.registration_hook_sid = null;
delete obj.registration_hook;
}
logger.info({obj}, `about to update Account ${sid}`);
const rowsAffected = await Account.update(sid, obj);
if (rowsAffected === 0) {
return res.status(404).end();
}
if (orphanedHook) {
await Webhook.remove(orphanedHook);
}
}
res.status(204).end();
updateLastUsed(logger, sid, req).catch((err) => {});
} catch (err) {
@@ -332,7 +379,7 @@ router.post('/:sid/Calls', async(req, res) => {
url: serviceUrl,
method: 'POST',
json: true,
body: req.body
body: Object.assign(req.body, {account_sid: sid})
}, (err, response, body) => {
if (err) {
logger.error(err, `Error sending createCall POST to ${ip}`);
@@ -417,7 +464,7 @@ router.delete('/:sid/Calls/:callSid', async(req, res) => {
/**
* update a call
*/
router.post('/:sid/Calls/:callSid', async(req, res) => {
const updateCall = async(req, res) => {
const accountSid = req.params.sid;
const callSid = req.params.callSid;
const {logger, retrieveCall} = req.app.locals;
@@ -443,6 +490,14 @@ router.post('/:sid/Calls/:callSid', async(req, res) => {
} catch (err) {
sysError(logger, res, err);
}
};
/** leaving for legacy purposes, this should have been (and now is) a PUT */
router.post('/:sid/Calls/:callSid', async(req, res) => {
await updateCall(req, res);
});
router.put('/:sid/Calls/:callSid', async(req, res) => {
await updateCall(req, res);
});
/**
@@ -464,7 +519,7 @@ router.post('/:sid/Messages', async(req, res) => {
const serviceUrl = `http://${ip}:3000/v1/createMessage/${sid}`;
await validateCreateMessage(logger, sid, req);
const payload = Object.assign({messageSid: uuidv4()}, req.body);
const payload = Object.assign({messageSid: uuidv4(), account_sid: sid}, req.body);
logger.debug({payload}, `sending createMessage API request to to ${ip}`);
updateLastUsed(logger, sid, req).catch((err) => {});
request({

View File

@@ -9,10 +9,16 @@ const preconditions = {
'delete': checkInUse,
'update': validateUpdate
};
const sysError = require('./error');
/* check for required fields when adding */
async function validateAdd(req) {
try {
/* account level user can only act on carriers associated to his/her account */
if (req.user.hasAccountAuth) {
req.body.account_sid = req.user.account_sid;
}
if (!req.body.voip_carrier_sid) throw new DbErrorBadRequest('voip_carrier_sid is required');
if (!req.body.number) throw new DbErrorBadRequest('number is required');
validateNumber(req.body.number);
@@ -30,24 +36,55 @@ async function validateAdd(req) {
/* can not delete a phone number if it in use */
async function checkInUse(req, sid) {
const phoneNumber = await PhoneNumber.retrieve(sid);
if (phoneNumber.account_sid) {
if (req.user.hasAccountAuth) {
if (phoneNumber.account_sid !== req.user.account_sid) {
throw new DbErrorUnprocessableRequest('cannot delete a phone number that belongs to another account');
}
}
if (!req.user.hasAccountAuth && phoneNumber.account_sid) {
throw new DbErrorUnprocessableRequest('cannot delete phone number that is assigned to an account');
}
}
/* can not change number or voip carrier */
async function validateUpdate(req, sid) {
//const result = await PhoneNumber.retrieve(sid);
if (req.body.voip_carrier_sid) throw new DbErrorBadRequest('voip_carrier_sid may not be modified');
if (req.body.number) throw new DbErrorBadRequest('number may not be modified');
// TODO: if we are assigning to an account, verify it exists
// TODO: if we are assigning to an application, verify it is associated to the same account
// TODO: if we are removing from an account, verify we are also removing from application.
const phoneNumber = await PhoneNumber.retrieve(sid);
if (req.user.hasAccountAuth) {
if (phoneNumber.account_sid !== req.user.account_sid) {
throw new DbErrorUnprocessableRequest('cannot delete a phone number that belongs to another account');
}
}
}
decorate(router, PhoneNumber, ['*'], preconditions);
decorate(router, PhoneNumber, ['add', 'update', 'delete'], preconditions);
/* list */
router.get('/', async(req, res) => {
const logger = req.app.locals.logger;
try {
const results = await PhoneNumber.retrieveAll(req.user.hasAccountAuth ? req.user.account_sid : null);
res.status(200).json(results);
} catch (err) {
sysError(logger, res, err);
}
});
/* retrieve */
router.get('/:sid', async(req, res) => {
const logger = req.app.locals.logger;
try {
const account_sid = req.user.hasAccountAuth ? req.user.account_sid : null;
const results = await PhoneNumber.retrieve(req.params.sid, account_sid);
if (results.length === 0) return res.status(404).end();
return res.status(200).json(results[0]);
}
catch (err) {
sysError(logger, res, err);
}
});
module.exports = router;

View File

@@ -177,7 +177,8 @@ paths:
description: login succeeded
content:
application/json:
schema: '#/components/schemas/Login'
schema:
$ref: '#/components/schemas/Login'
403:
description: login failed
content:
@@ -249,10 +250,29 @@ paths:
name:
type: string
description: voip carrier name
example: fastco
description:
type: string
example: my US sip trunking provider
e164_leading_plus:
type: boolean
description: whether a leading + is required on INVITEs to this provider
example: true
requires_register:
type: boolean
description: wehther this provider requires us to send a REGISTER to them in order to receive calls
register_username:
type: string
description: sip username to authenticate with, if registration is required
example: foo
register_sip_realm:
type: string
description: sip realm to authenticate with, if registration is required
example: sip.fastco.com
register_password:
type: string
description: sip password to authenticate with, if registration is required
example: bar
required:
- name
responses:
@@ -961,12 +981,6 @@ paths:
registration_hook:
$ref: '#/components/schemas/Webhook'
description: authentication webhook for registration
device_calling_hook:
$ref: '#/components/schemas/Webhook'
description: webhook for inbound call from registered devices
error_hook:
$ref: '#/components/schemas/Webhook'
description: webhook for reporting errors from malformed applications
service_provider_sid:
type: string
format: uuid
@@ -1682,6 +1696,14 @@ components:
type: string
e164_leading_plus:
type: boolean
requires_register:
type: boolean
register_username:
type: string
register_sip_realm:
type: string
register_password:
type: string
required:
- voip_carrier_sid
- name
@@ -1722,19 +1744,16 @@ components:
registration_hook:
$ref: '#/components/schemas/Webhook'
description: authentication webhook for registration
device_calling_hook:
$ref: '#/components/schemas/Webhook'
description: webhook for inbound call from registered devices
error_hook:
$ref: '#/components/schemas/Webhook'
description: webhook for reporting errors from malformed applications
device_calling_application_sid:
type: string
format: uuid
service_provider_sid:
type: string
format: uuid
required:
- account_sid
- name
- service_provider
- service_provider_sid
Application:
type: object
properties:

View File

@@ -1,11 +1,12 @@
{
"name": "jambonz-api-server",
"version": "1.2.0",
"version": "1.2.1",
"description": "",
"main": "app.js",
"scripts": {
"start": "node app.js",
"test": "NODE_ENV=test JAMBONES_MYSQL_HOST=localhost JAMBONES_MYSQL_USER=jambones_test JAMBONES_MYSQL_PASSWORD=jambones_test JAMBONES_MYSQL_DATABASE=jambones_test JAMBONES_REDIS_HOST=localhost JAMBONES_LOGLEVEL=error JAMBONES_CREATE_CALL_URL=http://localhost/v1/createCall node test/ | ./node_modules/.bin/tap-spec",
"test": "NODE_ENV=test JAMBONES_MYSQL_HOST=127.0.0.1 JAMBONES_MYSQL_USER=jambones_test JAMBONES_MYSQL_PASSWORD=jambones_test JAMBONES_MYSQL_DATABASE=jambones_test JAMBONES_MYSQL_PORT=3360 JAMBONES_REDIS_HOST=localhost JAMBONES_LOGLEVEL=error JAMBONES_CREATE_CALL_URL=http://localhost/v1/createCall node test/ | ./node_modules/.bin/tap-spec",
"integration-test": "NODE_ENV=test JAMBONES_TIME_SERIES_HOST=127.0.0.1 AWS_REGION='us-east-1' JAMBONES_CURRENCY=USD JWT_SECRET=foobarbazzle JAMBONES_MYSQL_HOST=127.0.0.1 JAMBONES_MYSQL_PORT=3360 JAMBONES_MYSQL_USER=jambones_test JAMBONES_MYSQL_PASSWORD=jambones_test JAMBONES_MYSQL_DATABASE=jambones_test JAMBONES_REDIS_HOST=localhost JAMBONES_REDIS_PORT=16379 JAMBONES_LOGLEVEL=debug JAMBONES_CREATE_CALL_URL=http://localhost/v1/createCall node test/serve-integration.js",
"coverage": "./node_modules/.bin/nyc --reporter html --report-dir ./coverage npm run test",
"jslint": "eslint app.js lib"
},
@@ -15,31 +16,29 @@
"url": "https://github.com/jambonz/jambonz-api-server.git"
},
"dependencies": {
"@jambonz/db-helpers": "^0.5.1",
"@jambonz/db-helpers": "^0.5.5",
"@jambonz/messaging-382com": "0.0.2",
"@jambonz/messaging-peerless": "0.0.9",
"@jambonz/messaging-simwood": "0.0.4",
"@jambonz/realtimedb-helpers": "0.2.17",
"@jambonz/realtimedb-helpers": "0.2.19",
"cors": "^2.8.5",
"express": "^4.17.1",
"mysql2": "^2.1.0",
"mysql2": "^2.2.5",
"passport": "^0.4.1",
"passport-http-bearer": "^1.0.1",
"pino": "^5.17.0",
"request": "^2.88.2",
"request-debug": "^0.2.0",
"swagger-ui-dist": "^3.35.0",
"swagger-ui-express": "^4.1.4",
"swagger-ui-express": "^4.1.5",
"uuid": "^3.4.0",
"yamljs": "^0.3.0"
},
"devDependencies": {
"eslint": "^7.10.0",
"blue-tape": "^1.0.0",
"eslint": "^7.15.0",
"eslint-plugin-promise": "^4.2.1",
"nyc": "^15.1.0",
"request-promise-native": "^1.0.9",
"tap-dot": "^2.0.0",
"tap-spec": "^5.0.0",
"tape": "^5.0.1"
"tap-spec": "^5.0.0"
}
}

View File

@@ -1,4 +1,4 @@
const test = require('tape').test ;
const test = require('blue-tape').test ;
const ADMIN_TOKEN = '38700987-c7a4-4685-a5bb-af378f9734de';
const authAdmin = {bearer: ADMIN_TOKEN};
const request = require('request-promise-native').defaults({
@@ -138,7 +138,7 @@ test('account tests', async(t) => {
await deleteObjectBySid(request, '/VoipCarriers', voip_carrier_sid);
await deleteObjectBySid(request, '/ServiceProviders', service_provider_sid);
t.end();
//t.end();
}
catch (err) {
console.error(err);

View File

@@ -1,4 +1,4 @@
const test = require('tape').test ;
const test = require('blue-tape').test ;
const ADMIN_TOKEN = '38700987-c7a4-4685-a5bb-af378f9734de';
const authAdmin = {bearer: ADMIN_TOKEN};
const request = require('request-promise-native').defaults({
@@ -121,7 +121,7 @@ test('application tests', async(t) => {
await deleteObjectBySid(request, '/VoipCarriers', voip_carrier_sid);
await deleteObjectBySid(request, '/ServiceProviders', service_provider_sid);
t.end();
//t.end();
}
catch (err) {
//console.error(err);

View File

@@ -1,4 +1,4 @@
const test = require('tape').test ;
const test = require('blue-tape').test ;
const ADMIN_TOKEN = '38700987-c7a4-4685-a5bb-af378f9734de';
const authAdmin = {bearer: ADMIN_TOKEN};
const request = require('request-promise-native').defaults({
@@ -461,7 +461,7 @@ test('authentication tests', async(t) => {
await deleteObjectBySid(request, '/ServiceProviders', spA_sid);
await deleteObjectBySid(request, '/ServiceProviders', spB_sid);
t.end();
//t.end();
}
catch (err) {
console.error(err);

View File

@@ -1,9 +1,8 @@
const test = require('tape').test ;
const test = require('blue-tape').test ;
const exec = require('child_process').exec ;
const pwd = process.env.TRAVIS ? '' : '-p$MYSQL_ROOT_PASSWORD';
test('creating jambones_test database', (t) => {
exec(`mysql -h localhost -u root ${pwd} < ${__dirname}/../db/create_test_db.sql`, (err, stdout, stderr) => {
exec(`mysql -h 127.0.0.1 -u root --protocol=tcp --port=3360 < ${__dirname}/../db/create_test_db.sql`, (err, stdout, stderr) => {
if (err) return t.end(err);
t.pass('database successfully created');
t.end();
@@ -11,7 +10,7 @@ test('creating jambones_test database', (t) => {
});
test('creating schema', (t) => {
exec(`mysql -h localhost -u root ${pwd} -D jambones_test < ${__dirname}/../db/jambones-sql.sql`, (err, stdout, stderr) => {
exec(`mysql -h 127.0.0.1 -u root --protocol=tcp --port=3360 -D jambones_test < ${__dirname}/../db/jambones-sql.sql`, (err, stdout, stderr) => {
if (err) return t.end(err);
t.pass('schema successfully created');
t.end();
@@ -19,7 +18,7 @@ test('creating schema', (t) => {
});
test('creating auth token', (t) => {
exec(`mysql -h localhost -u root ${pwd} -D jambones_test < ${__dirname}/../db/create-admin-token.sql`, (err, stdout, stderr) => {
exec(`mysql -h 127.0.0.1 -u root --protocol=tcp --port=3360 -D jambones_test < ${__dirname}/../db/create-admin-token.sql`, (err, stdout, stderr) => {
if (err) return t.end(err);
t.pass('auth token successfully created');
t.end();

View File

@@ -0,0 +1,25 @@
version: '3'
services:
mysql:
image: mysql:5.7
ports:
- "3360:3306"
environment:
MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
healthcheck:
test: ["CMD", "mysqladmin" ,"ping", "-h", "127.0.0.1", "--protocol", "tcp"]
timeout: 5s
retries: 10
redis:
image: redis:5-alpine
ports:
- "16379:6379/tcp"
depends_on:
mysql:
condition: service_healthy
influxdb:
image: influxdb:1.8-alpine
ports:
- "8086:8086"

12
test/docker_start.js Normal file
View File

@@ -0,0 +1,12 @@
const test = require('blue-tape');
//const test = require('tape').test ;
const exec = require('child_process').exec ;
test('starting docker network..', (t) => {
exec(`docker-compose -f ${__dirname}/docker-compose-testbed.yaml up -d`, (err, stdout, stderr) => {
setTimeout(() => {
t.pass('docker started');
t.end(err);
}, 15000);
});
});

12
test/docker_stop.js Normal file
View File

@@ -0,0 +1,12 @@
const test = require('blue-tape');
const exec = require('child_process').exec ;
test('stopping docker network..', (t) => {
t.timeoutAfter(10000);
exec(`docker-compose -f ${__dirname}/docker-compose-testbed.yaml down`, (err, stdout, stderr) => {
//console.log(`stderr: ${stderr}`);
process.exit(0);
});
t.end() ;
});

View File

@@ -1,3 +1,4 @@
require('./docker_start');
require('./create-test-db');
require('./sip-gateways');
require('./service-providers');
@@ -8,4 +9,4 @@ require('./applications');
require('./auth');
require('./sbcs');
require('./ms-teams');
require('./remove-test-db');
require('./docker_stop');

View File

@@ -1,4 +1,4 @@
const test = require('tape').test ;
const test = require('blue-tape').test ;
const ADMIN_TOKEN = '38700987-c7a4-4685-a5bb-af378f9734de';
const authAdmin = {bearer: ADMIN_TOKEN};
const request = require('request-promise-native').defaults({
@@ -10,7 +10,7 @@ process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
});
test('sbc_addresses tests', async(t) => {
test('ms teams tests', async(t) => {
const app = require('../app');
let sid;
try {
@@ -79,7 +79,7 @@ test('sbc_addresses tests', async(t) => {
await deleteObjectBySid(request, '/Accounts', account_sid2);
await deleteObjectBySid(request, '/ServiceProviders', service_provider_sid);
t.end();
//t.end();
}
catch (err) {
console.error(err);

View File

@@ -1,4 +1,4 @@
const test = require('tape').test ;
const test = require('blue-tape').test ;
const ADMIN_TOKEN = '38700987-c7a4-4685-a5bb-af378f9734de';
const authAdmin = {bearer: ADMIN_TOKEN};
const request = require('request-promise-native').defaults({
@@ -111,7 +111,7 @@ test('phone number tests', async(t) => {
await deleteObjectBySid(request, '/VoipCarriers', voip_carrier_sid);
t.end();
//t.end();
}
catch (err) {
console.error(err);

View File

@@ -1,9 +1,9 @@
const test = require('tape').test ;
const exec = require('child_process').exec ;
const pwd = process.env.TRAVIS ? '' : '-p$MYSQL_ROOT_PASSWORD';
const pwd = process.env.CI ? '' : '-p$MYSQL_ROOT_PASSWORD';
test('dropping jambones_test database', (t) => {
exec(`mysql -h localhost -u root ${pwd} < ${__dirname}/../db/remove_test_db.sql`, (err, stdout, stderr) => {
exec(`mysql -h 127.0.0.1 -u root ${pwd} --protocol=tcp < ${__dirname}/../db/remove_test_db.sql`, (err, stdout, stderr) => {
if (err) return t.end(err);
t.pass('database successfully dropped');
t.end();

View File

@@ -1,4 +1,4 @@
const test = require('tape').test ;
const test = require('blue-tape').test ;
const ADMIN_TOKEN = '38700987-c7a4-4685-a5bb-af378f9734de';
const authAdmin = {bearer: ADMIN_TOKEN};
const request = require('request-promise-native').defaults({
@@ -60,7 +60,7 @@ test('sbc_addresses tests', async(t) => {
await deleteObjectBySid(request, '/Sbcs', sid2);
await deleteObjectBySid(request, '/ServiceProviders', service_provider_sid);
t.end();
//t.end();
}
catch (err) {
console.error(err);

83
test/serve-integration.js Normal file
View File

@@ -0,0 +1,83 @@
const exec = require('child_process').exec ;
let stopping = false;
process.on('SIGINT', async() => {
if (stopping) return;
stopping = true;
console.log('shutting down');
await stopDocker();
process.exit(0);
});
const startDocker = () => {
return new Promise((resolve, reject) => {
console.log('starting dockerized mysql and redis..')
exec(`docker-compose -f ${__dirname}/docker-compose-testbed.yaml up -d`, (err) => {
if (err) return reject(err);
setTimeout(() => {
console.log('mysql is running');
resolve();
}, 10000);
});
});
};
const createDb = () => {
return new Promise((resolve, reject) => {
console.log('creating database..')
exec(`mysql -h 127.0.0.1 -u root --protocol=tcp --port=3360 < ${__dirname}/../db/create_test_db.sql`, (err) => {
if (err) return reject(err);
resolve();
});
});
};
const createSchema = () => {
return new Promise((resolve, reject) => {
console.log('creating schema..')
exec(`mysql -h 127.0.0.1 -u root --protocol=tcp --port=3360 -D jambones_test < ${__dirname}/../db/jambones-sql.sql`, (err, stdout, stderr) => {
if (err) return reject(err);
resolve();
});
});
};
const seedDb = () => {
return new Promise((resolve, reject) => {
console.log('seeding database..')
exec(`mysql -h 127.0.0.1 -u root --protocol=tcp --port=3360 -D jambones_test < ${__dirname}/../db/create-default-service-provider-and-account.sql`, (err) => {
if (err) return reject(err);
exec(`mysql -h 127.0.0.1 -u root --protocol=tcp --port=3360 -D jambones_test < ${__dirname}/../db/create-admin-token.sql`, (err) => {
if (err) return reject(err);
exec(`node ${__dirname}/../db/reset_admin_password.js`, (err) => {
if (err) return reject(err);
resolve();
});
});
});
});
};
const stopDocker = () => {
return new Promise((resolve, reject) => {
console.log('stopping docker network..')
exec(`docker-compose -f ${__dirname}/docker-compose-testbed.yaml down`, (err) => {
if (err) return reject(err);
resolve();
});
})
};
startDocker()
.then(createDb)
.then(createSchema)
.then(seedDb)
.then(() => {
console.log('ready for testing!');
require('..');
})
.catch(async(err) => {
console.error({err}, 'Error running integration test');
await stopDocker();
process.exit(-1);
});

View File

@@ -1,4 +1,4 @@
const test = require('tape').test ;
const test = require('blue-tape').test ;
const ADMIN_TOKEN = '38700987-c7a4-4685-a5bb-af378f9734de';
const authAdmin = {bearer: ADMIN_TOKEN};
const request = require('request-promise-native').defaults({
@@ -117,7 +117,7 @@ test('service provider tests', async(t) => {
resolveWithFullResponse: true,
});
t.ok(result.statusCode === 204, 'successfully deleted service provider 2');
t.end();
//t.end();
}
catch (err) {
console.error(err);

View File

@@ -1,4 +1,4 @@
const test = require('tape').test ;
const test = require('blue-tape').test ;
const ADMIN_TOKEN = '38700987-c7a4-4685-a5bb-af378f9734de';
const authAdmin = {bearer: ADMIN_TOKEN};
const request = require('request-promise-native').defaults({
@@ -72,7 +72,7 @@ test('sip gateway tests', async(t) => {
await deleteObjectBySid(request, '/VoipCarriers', voip_carrier_sid);
t.end();
//t.end();
}
catch (err) {
console.error(err);

View File

@@ -1,4 +1,4 @@
const test = require('tape').test ;
const test = require('blue-tape').test ;
const ADMIN_TOKEN = '38700987-c7a4-4685-a5bb-af378f9734de';
const authAdmin = {bearer: ADMIN_TOKEN};
const request = require('request-promise-native').defaults({
@@ -50,7 +50,11 @@ test('voip carrier tests', async(t) => {
json: true,
resolveWithFullResponse: true,
body: {
name: 'robb'
name: 'robb',
requires_register: true,
register_username: 'foo',
register_sip_realm: 'bar',
register_password: 'baz'
}
});
t.ok(result.statusCode === 204, 'successfully updated voip carrier');
@@ -190,7 +194,7 @@ test('voip carrier tests', async(t) => {
await deleteObjectBySid(request, '/Accounts', account_sid2);
await deleteObjectBySid(request, '/ServiceProviders', service_provider_sid);
t.end();
//t.end();
}
catch (err) {
console.error(err);