feat: full multi-tenant auth - JWT login, clinic registration, super admin CRUD
Build Curio HMS / build-and-deploy (push) Successful in 50s Details

This commit is contained in:
Deep Koluguri 2026-05-25 21:43:30 -04:00
parent 70b1da8190
commit 231a84182e
299 changed files with 27738 additions and 350 deletions

58
backend/authMiddleware.js Normal file
View File

@ -0,0 +1,58 @@
/**
* authMiddleware.js JWT sign/verify helpers + Express middleware for Curio HMS.
*/
const jwt = require('jsonwebtoken');
const JWT_SECRET = process.env.JWT_SECRET || 'curio_dev_secret_change_in_production';
const JWT_EXPIRY = '7d';
/**
* Sign a JWT with the given payload.
* @param {{ userId, email, role, tenantId }} payload
* @returns {string} signed JWT
*/
function signToken(payload) {
return jwt.sign(payload, JWT_SECRET, { expiresIn: JWT_EXPIRY });
}
/**
* Express middleware: verifies JWT and enforces role access.
* @param {...string} roles - allowed roles; empty = any authenticated user
*/
function requireAuth(...roles) {
return (req, res, next) => {
const header = req.headers['authorization'] || req.headers['x-auth-token'];
if (!header) return res.status(401).json({ error: 'Authentication required' });
const token = header.startsWith('Bearer ') ? header.slice(7) : header;
try {
const decoded = jwt.verify(token, JWT_SECRET);
req.user = decoded;
if (roles.length > 0 && !roles.includes(decoded.role)) {
return res.status(403).json({ error: 'Insufficient permissions' });
}
next();
} catch (err) {
return res.status(401).json({ error: 'Invalid or expired token' });
}
};
}
/**
* Middleware: verifies JWT but does NOT reject unauthenticated requests.
* Attaches req.user if valid token present.
*/
function optionalAuth(req, res, next) {
const header = req.headers['authorization'] || req.headers['x-auth-token'];
if (header) {
const token = header.startsWith('Bearer ') ? header.slice(7) : header;
try {
req.user = jwt.verify(token, JWT_SECRET);
} catch (_) { /* ignore */ }
}
next();
}
module.exports = { signToken, requireAuth, optionalAuth };

View File

@ -1,64 +1,40 @@
/**
* ConfigManager: Central configuration for multi-tenant hospital settings and white-labeling.
* configManager.js In-memory fallback config for multi-tenant hospital settings.
* The server.js DB layer takes priority; this is the fallback for legacy/dev use.
*/
class ConfigManager {
constructor() {
this.tenants = {
'default': {
name: "Curio Clinic",
logo: "C",
primaryColor: "#0F172A",
secondaryColor: "#38BDF8",
consultationFee: 500,
currency: "₹",
workingHours: [
{ start: "09:00", end: "13:00" },
{ start: "17:00", end: "22:00" }
],
daysOff: [0], // 0 = Sunday
holidays: ["2024-12-25", "2025-01-01"]
},
'sharma-clinic': {
name: "Dr. Sharma's Cardiology",
logo: "S",
primaryColor: "#1E3A8A",
secondaryColor: "#60A5FA",
consultationFee: 800,
currency: "₹",
workingHours: [
{ start: "10:00", end: "14:00" },
{ start: "18:00", end: "21:00" }
],
daysOff: [0, 6], // Sat, Sun
holidays: []
},
'apollo-hospitals': {
name: "Apollo Multispecialty",
logo: "A",
primaryColor: "#065F46",
secondaryColor: "#34D399",
consultationFee: 1200,
currency: "₹",
workingHours: [
{ start: "09:00", end: "22:00" }
],
daysOff: [],
holidays: ["2024-10-02"]
}
};
const TENANTS = {
'default': {
name: "Curio Clinic", logo: "C",
primaryColor: "#0F172A", secondaryColor: "#38BDF8",
consultationFee: 500, currency: "₹",
workingHours: [{ start: "09:00", end: "13:00" }, { start: "17:00", end: "22:00" }],
daysOff: [0], holidays: ["2024-12-25", "2025-01-01"]
},
'sharma-clinic': {
name: "Dr. Sharma's Cardiology", logo: "S",
primaryColor: "#1E3A8A", secondaryColor: "#60A5FA",
consultationFee: 800, currency: "₹",
workingHours: [{ start: "10:00", end: "14:00" }, { start: "18:00", end: "21:00" }],
daysOff: [0, 6], holidays: []
},
'apollo-hospitals': {
name: "Apollo Multispecialty", logo: "A",
primaryColor: "#065F46", secondaryColor: "#34D399",
consultationFee: 1200, currency: "₹",
workingHours: [{ start: "09:00", end: "22:00" }],
daysOff: [], holidays: ["2024-10-02"]
}
};
getTenantConfig(tenantId) {
return this.tenants[tenantId] || this.tenants['default'];
}
updateTenantConfig(tenantId, newConfig) {
if (!this.tenants[tenantId]) {
this.tenants[tenantId] = { ...this.tenants['default'] };
}
this.tenants[tenantId] = { ...this.tenants[tenantId], ...newConfig };
}
function getTenantConfig(tenantId) {
return TENANTS[tenantId] || TENANTS['default'];
}
module.exports = new ConfigManager();
function updateTenantConfig(tenantId, newConfig) {
if (!TENANTS[tenantId]) TENANTS[tenantId] = { ...TENANTS['default'] };
TENANTS[tenantId] = { ...TENANTS[tenantId], ...newConfig };
}
module.exports = { getTenantConfig, updateTenantConfig };

154
backend/db.js Normal file
View File

@ -0,0 +1,154 @@
/**
* db.js PostgreSQL connection pool + schema initialisation for Curio HMS.
* Tables: tenants, users, pending_registrations
*/
const { Pool } = require('pg');
const bcrypt = require('bcryptjs');
const pool = new Pool({
connectionString: process.env.DATABASE_URL || 'postgres://postgres:curio_secret@curio-db:5432/curio',
ssl: false,
});
// ── Schema ──────────────────────────────────────────────────────────────────
const SCHEMA_SQL = `
CREATE TABLE IF NOT EXISTS tenants (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
logo TEXT DEFAULT 'C',
primary_color TEXT DEFAULT '#0F172A',
secondary_color TEXT DEFAULT '#38BDF8',
consultation_fee INTEGER DEFAULT 500,
currency TEXT DEFAULT '₹',
plan TEXT DEFAULT 'basic',
status TEXT DEFAULT 'active',
whatsapp_number TEXT,
specialty TEXT,
city TEXT,
working_hours JSONB DEFAULT '[{"start":"09:00","end":"13:00"},{"start":"17:00","end":"22:00"}]',
days_off JSONB DEFAULT '[0]',
holidays JSONB DEFAULT '[]',
created_at TIMESTAMPTZ DEFAULT now()
);
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
tenant_id TEXT REFERENCES tenants(id) ON DELETE CASCADE,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
name TEXT NOT NULL,
role TEXT NOT NULL CHECK (role IN ('SUPER_ADMIN','OWNER','DOCTOR','RECEPTIONIST','PHARMACIST','LAB_TECH')),
status TEXT DEFAULT 'active',
created_at TIMESTAMPTZ DEFAULT now()
);
CREATE TABLE IF NOT EXISTS pending_registrations (
id SERIAL PRIMARY KEY,
owner_name TEXT NOT NULL,
clinic_name TEXT NOT NULL,
specialty TEXT,
city TEXT,
whatsapp_number TEXT NOT NULL,
email TEXT NOT NULL,
password_hash TEXT NOT NULL,
plan TEXT DEFAULT 'basic',
status TEXT DEFAULT 'pending',
created_at TIMESTAMPTZ DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_users_tenant ON users(tenant_id);
CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
CREATE INDEX IF NOT EXISTS idx_pending_status ON pending_registrations(status);
`;
// ── Seed super admin ─────────────────────────────────────────────────────────
async function seedSuperAdmin() {
const email = process.env.SUPER_ADMIN_EMAIL || 'admin@curio.app';
const password = process.env.SUPER_ADMIN_PASSWORD || 'superadmin';
const existing = await pool.query('SELECT id FROM users WHERE email = $1', [email]);
if (existing.rows.length > 0) return;
const hash = await bcrypt.hash(password, 10);
await pool.query(
`INSERT INTO users (tenant_id, email, password_hash, name, role)
VALUES (NULL, $1, $2, 'Super Admin', 'SUPER_ADMIN')`,
[email, hash]
);
console.log(`[DB] Super admin seeded: ${email}`);
}
// ── Seed legacy in-memory tenants into DB ─────────────────────────────────────
async function seedLegacyTenants() {
const legacy = [
{
id: 'default',
name: 'Curio Clinic',
logo: 'C',
primary_color: '#0F172A',
secondary_color: '#38BDF8',
consultation_fee: 500,
plan: 'basic',
working_hours: JSON.stringify([{ start: '09:00', end: '13:00' }, { start: '17:00', end: '22:00' }]),
days_off: JSON.stringify([0]),
},
{
id: 'sharma-clinic',
name: "Dr. Sharma's Cardiology",
logo: 'S',
primary_color: '#1E3A8A',
secondary_color: '#60A5FA',
consultation_fee: 800,
plan: 'pro',
working_hours: JSON.stringify([{ start: '10:00', end: '14:00' }, { start: '18:00', end: '21:00' }]),
days_off: JSON.stringify([0, 6]),
},
{
id: 'apollo-hospitals',
name: 'Apollo Multispecialty',
logo: 'A',
primary_color: '#065F46',
secondary_color: '#34D399',
consultation_fee: 1200,
plan: 'enterprise',
working_hours: JSON.stringify([{ start: '09:00', end: '22:00' }]),
days_off: JSON.stringify([]),
},
];
for (const t of legacy) {
await pool.query(
`INSERT INTO tenants (id, name, logo, primary_color, secondary_color, consultation_fee, plan, working_hours, days_off)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8::jsonb,$9::jsonb)
ON CONFLICT (id) DO NOTHING`,
[t.id, t.name, t.logo, t.primary_color, t.secondary_color, t.consultation_fee, t.plan, t.working_hours, t.days_off]
);
}
console.log('[DB] Legacy tenants seeded.');
}
// ── Init ──────────────────────────────────────────────────────────────────────
async function initSchema() {
try {
await pool.query(SCHEMA_SQL);
console.log('[DB] Schema ready.');
await seedSuperAdmin();
await seedLegacyTenants();
} catch (err) {
console.error('[DB] Schema init failed:', err.message);
// Don't crash — let server start even if DB is temporarily unavailable
}
}
// ── Exports ───────────────────────────────────────────────────────────────────
function query(sql, params) {
return pool.query(sql, params);
}
module.exports = { query, pool, initSchema };

View File

@ -5,7 +5,7 @@
* - 5 Walk-in slots
*/
const configManager = require('./configManager');
const { getTenantConfig } = require('./configManager');
const notificationManager = require('./notificationManager');
class QueueManager {
@ -14,7 +14,7 @@ class QueueManager {
}
getSlotKey(tenantId, date, time) {
const config = configManager.getTenantConfig(tenantId);
const config = getTenantConfig(tenantId);
const duration = config.slotDuration || 30;
const [hours, minutes] = time.split(':');
const roundedMins = parseInt(minutes) < duration ? '00' : duration;
@ -22,7 +22,7 @@ class QueueManager {
}
isAvailable(tenantId, date, time) {
const config = configManager.getTenantConfig(tenantId);
const config = getTenantConfig(tenantId);
const d = new Date(date + "T00:00:00");
// Check days off
@ -53,7 +53,7 @@ class QueueManager {
getSlotStatus(tenantId, date, time) {
const key = this.getSlotKey(tenantId, date, time);
if (!this.slots[key]) {
const config = configManager.getTenantConfig(tenantId);
const config = getTenantConfig(tenantId);
this.slots[key] = {
online: 0,
walkin: 0,
@ -69,7 +69,7 @@ class QueueManager {
return { success: false, message: "The clinic is closed at this time / on this day." };
}
const status = this.getSlotStatus(tenantId, date, time);
const config = configManager.getTenantConfig(tenantId);
const config = getTenantConfig(tenantId);
if (status.online < status.maxOnline) {
status.online++;
return {
@ -88,7 +88,7 @@ class QueueManager {
return { success: false, message: "The clinic is closed at this time / on this day." };
}
const status = this.getSlotStatus(tenantId, date, time);
const config = configManager.getTenantConfig(tenantId);
const config = getTenantConfig(tenantId);
if (status.walkin < status.maxWalkin) {
status.walkin++;
return {
@ -102,7 +102,7 @@ class QueueManager {
}
getDailyUpdates(patientId, tenantId = 'default') {
const config = configManager.getTenantConfig(tenantId);
const config = getTenantConfig(tenantId);
return [
`Good morning! Your appointment with ${config.name} is scheduled for today.`,
"Queue Update: The clinic is running 10 mins behind schedule. Please plan accordingly.",
@ -121,7 +121,7 @@ class QueueManager {
}
notifyAvailableSlot(tenantId, date, time) {
const config = configManager.getTenantConfig(tenantId);
const config = getTenantConfig(tenantId);
console.log(`[Queue] Triggering notifications for open slot: ${time}`);
// Mock finding a patient with a later slot

View File

@ -1,9 +1,14 @@
const express = require('express');
const path = require('path');
const botLogic = require('./botLogic');
const configManager = require('./configManager');
const { getTemporalClient } = require('./temporalClient');
const crypto = require('crypto');
const bcrypt = require('bcryptjs');
const botLogic = require('./botLogic');
const { getTenantConfig, updateTenantConfig } = require('./configManager');
const { getTemporalClient } = require('./temporalClient');
const { query, initSchema } = require('./db');
const { signToken, requireAuth } = require('./authMiddleware');
const app = express();
const port = 3000;
@ -11,17 +16,13 @@ app.use(express.json());
const staticRoot = path.join(__dirname, '../');
/** UTF-8 Content-Type for text assets (fixes emoji/₹ mojibake when proxy omits charset). */
// ── Helpers ───────────────────────────────────────────────────────────────────
function setUtf8ContentType(res, filePath) {
if (filePath.endsWith('.html')) {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
} else if (filePath.endsWith('.css')) {
res.setHeader('Content-Type', 'text/css; charset=utf-8');
} else if (filePath.endsWith('.js')) {
res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
} else if (filePath.endsWith('.json')) {
res.setHeader('Content-Type', 'application/json; charset=utf-8');
}
if (filePath.endsWith('.html')) res.setHeader('Content-Type', 'text/html; charset=utf-8');
else if (filePath.endsWith('.css')) res.setHeader('Content-Type', 'text/css; charset=utf-8');
else if (filePath.endsWith('.js')) res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
else if (filePath.endsWith('.json')) res.setHeader('Content-Type', 'application/json; charset=utf-8');
}
function setNoCacheHeaders(res) {
@ -36,98 +37,498 @@ function sendHtmlPage(res, filename) {
res.sendFile(path.join(staticRoot, filename));
}
// Serve static files
// Slug-safe clinic ID generator from clinic name
function slugify(name) {
return name.toLowerCase()
.replace(/[^\w\s-]/g, '')
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.slice(0, 40);
}
async function uniqueSlug(base) {
let slug = slugify(base);
let attempt = slug;
let counter = 2;
while (true) {
const existing = await query('SELECT id FROM tenants WHERE id = $1', [attempt]);
if (existing.rows.length === 0) return attempt;
attempt = `${slug}-${counter++}`;
}
}
// ── Static files ──────────────────────────────────────────────────────────────
app.use(express.static(staticRoot, {
setHeaders: (res, filePath) => {
setUtf8ContentType(res, filePath);
if (filePath.endsWith('.html')) {
setNoCacheHeaders(res);
}
if (filePath.endsWith('.html')) setNoCacheHeaders(res);
}
}));
// Primary Routes
app.get('/', (req, res) => sendHtmlPage(res, 'login.html'));
app.get('/admin', (req, res) => sendHtmlPage(res, 'admin.html'));
app.get('/dashboard', (req, res) => sendHtmlPage(res, 'dashboard.html'));
// ── Page routes ───────────────────────────────────────────────────────────────
// Multi-tenant Config API
app.get('/api/config/:tenantId', (req, res) => {
const config = configManager.getTenantConfig(req.params.tenantId);
res.json(config);
app.get('/', (req, res) => sendHtmlPage(res, 'login.html'));
app.get('/admin', (req, res) => sendHtmlPage(res, 'admin.html'));
app.get('/dashboard', (req, res) => sendHtmlPage(res, 'dashboard.html'));
app.get('/register', (req, res) => sendHtmlPage(res, 'register.html'));
app.get('/super-admin', (req, res) => sendHtmlPage(res, 'super-admin.html'));
// ── Multi-tenant Config API (DB-first, fallback to in-memory) ─────────────────
app.get('/api/config/:tenantId', async (req, res) => {
try {
const row = await query('SELECT * FROM tenants WHERE id = $1 AND status = $2', [req.params.tenantId, 'active']);
if (row.rows.length > 0) {
const t = row.rows[0];
return res.json({
name: t.name,
logo: t.logo,
primaryColor: t.primary_color,
secondaryColor: t.secondary_color,
consultationFee: t.consultation_fee,
currency: t.currency || '₹',
plan: t.plan,
specialty: t.specialty,
city: t.city,
workingHours: t.working_hours,
daysOff: t.days_off,
holidays: t.holidays,
});
}
} catch (err) {
console.error('[Config API] DB error, falling back to in-memory:', err.message);
}
// Fallback to in-memory config
res.json(getTenantConfig(req.params.tenantId));
});
// Official Twilio Webhook parsing middleware
// ── AUTH ROUTES ───────────────────────────────────────────────────────────────
app.use(express.urlencoded({ extended: true }));
// WhatsApp Webhook (Twilio)
app.post('/whatsapp/webhook', async (req, res) => {
// Twilio sends urlencoded fields: From, Body
// Or our mock sends json: from, body
const from = req.body.From || req.body.from;
const body = req.body.Body || req.body.body;
console.log(`[WhatsApp Webhook] Received message from ${from}: ${body}`);
if (!from || !body) {
return res.status(400).send("Missing from or body");
/**
* POST /api/auth/register
* Public submit a clinic registration for super admin approval
*/
app.post('/api/auth/register', async (req, res) => {
const { ownerName, clinicName, specialty, city, whatsappNumber, email, password, plan } = req.body;
if (!ownerName || !clinicName || !whatsappNumber || !email || !password) {
return res.status(400).json({ error: 'Missing required fields' });
}
if (password.length < 8) {
return res.status(400).json({ error: 'Password must be at least 8 characters' });
}
try {
// Check for duplicate email in users or pending
const dupUser = await query('SELECT id FROM users WHERE email = $1', [email]);
const dupPending = await query('SELECT id FROM pending_registrations WHERE email = $1 AND status = $2', [email, 'pending']);
if (dupUser.rows.length > 0 || dupPending.rows.length > 0) {
return res.status(409).json({ error: 'An account with this email already exists or is pending approval' });
}
const hash = await bcrypt.hash(password, 10);
const result = await query(
`INSERT INTO pending_registrations
(owner_name, clinic_name, specialty, city, whatsapp_number, email, password_hash, plan)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING id`,
[ownerName, clinicName, specialty || null, city || null, whatsappNumber, email, hash, plan || 'basic']
);
res.json({ success: true, registrationId: result.rows[0].id });
} catch (err) {
console.error('[Register]', err);
res.status(500).json({ error: 'Registration failed' });
}
});
/**
* POST /api/auth/login
* Public authenticate user, return JWT
*/
app.post('/api/auth/login', async (req, res) => {
const { email, password } = req.body;
if (!email || !password) return res.status(400).json({ error: 'Email and password required' });
try {
const result = await query('SELECT * FROM users WHERE email = $1', [email]);
if (result.rows.length === 0) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const user = result.rows[0];
// Check tenant status (super admin has null tenant_id — always allowed)
if (user.tenant_id) {
const tenant = await query('SELECT status FROM tenants WHERE id = $1', [user.tenant_id]);
if (tenant.rows.length === 0 || tenant.rows[0].status !== 'active') {
return res.status(403).json({ error: 'Your clinic account is suspended. Contact Curio support.' });
}
}
if (user.status !== 'active') {
return res.status(403).json({ error: 'Your account is inactive. Contact your clinic admin.' });
}
const match = await bcrypt.compare(password, user.password_hash);
if (!match) return res.status(401).json({ error: 'Invalid credentials' });
const token = signToken({
userId: user.id,
email: user.email,
name: user.name,
role: user.role,
tenantId: user.tenant_id,
});
res.json({ success: true, token, role: user.role, tenantId: user.tenant_id, name: user.name });
} catch (err) {
console.error('[Login]', err);
res.status(500).json({ error: 'Login failed' });
}
});
/**
* GET /api/auth/me
* Returns current user info (for page load verification)
*/
app.get('/api/auth/me', requireAuth(), (req, res) => {
res.json({ user: req.user });
});
// ── SUPER ADMIN ROUTES ────────────────────────────────────────────────────────
/**
* GET /api/super/stats
*/
app.get('/api/super/stats', requireAuth('SUPER_ADMIN'), async (req, res) => {
try {
const [clinics, pending, users] = await Promise.all([
query("SELECT COUNT(*) FROM tenants WHERE status = 'active'"),
query("SELECT COUNT(*) FROM pending_registrations WHERE status = 'pending'"),
query("SELECT COUNT(*) FROM users WHERE role != 'SUPER_ADMIN'"),
]);
res.json({
activeClinics: parseInt(clinics.rows[0].count),
pendingCount: parseInt(pending.rows[0].count),
totalUsers: parseInt(users.rows[0].count),
});
} catch (err) {
console.error('[Super Stats]', err);
res.status(500).json({ error: 'Failed to fetch stats' });
}
});
/**
* GET /api/super/clinics
*/
app.get('/api/super/clinics', requireAuth('SUPER_ADMIN'), async (req, res) => {
try {
const result = await query(
`SELECT t.*, COUNT(u.id) AS user_count
FROM tenants t
LEFT JOIN users u ON u.tenant_id = t.id
GROUP BY t.id ORDER BY t.created_at DESC`
);
res.json(result.rows);
} catch (err) {
console.error('[Super Clinics]', err);
res.status(500).json({ error: 'Failed to fetch clinics' });
}
});
/**
* POST /api/super/clinics
* Direct clinic creation by super admin (bypasses pending flow)
*/
app.post('/api/super/clinics', requireAuth('SUPER_ADMIN'), async (req, res) => {
const { ownerName, ownerEmail, ownerPassword, clinicName, specialty, city, whatsappNumber, plan,
primaryColor, secondaryColor, consultationFee } = req.body;
if (!ownerName || !ownerEmail || !ownerPassword || !clinicName) {
return res.status(400).json({ error: 'Missing required fields' });
}
try {
const tenantId = await uniqueSlug(clinicName);
const hash = await bcrypt.hash(ownerPassword, 10);
await query('BEGIN');
try {
await query(
`INSERT INTO tenants (id, name, logo, primary_color, secondary_color, consultation_fee, plan, specialty, city, whatsapp_number)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`,
[tenantId, clinicName, clinicName[0].toUpperCase(),
primaryColor || '#0F172A', secondaryColor || '#38BDF8',
consultationFee || 500, plan || 'basic',
specialty || null, city || null, whatsappNumber || null]
);
const userResult = await query(
`INSERT INTO users (tenant_id, email, password_hash, name, role)
VALUES ($1,$2,$3,$4,'OWNER') RETURNING id`,
[tenantId, ownerEmail, hash, ownerName]
);
await query('COMMIT');
res.json({ success: true, tenantId, userId: userResult.rows[0].id });
} catch (inner) {
await query('ROLLBACK');
throw inner;
}
} catch (err) {
console.error('[Super Create Clinic]', err);
if (err.code === '23505') return res.status(409).json({ error: 'Email already in use' });
res.status(500).json({ error: 'Failed to create clinic' });
}
});
/**
* PATCH /api/super/clinics/:id/status
* Toggle active / suspended
*/
app.patch('/api/super/clinics/:id/status', requireAuth('SUPER_ADMIN'), async (req, res) => {
const { status } = req.body;
if (!['active', 'suspended'].includes(status)) {
return res.status(400).json({ error: 'Status must be active or suspended' });
}
try {
await query('UPDATE tenants SET status = $1 WHERE id = $2', [status, req.params.id]);
res.json({ success: true });
} catch (err) {
console.error('[Super Clinic Status]', err);
res.status(500).json({ error: 'Failed to update status' });
}
});
/**
* DELETE /api/super/clinics/:id
*/
app.delete('/api/super/clinics/:id', requireAuth('SUPER_ADMIN'), async (req, res) => {
try {
await query('DELETE FROM tenants WHERE id = $1', [req.params.id]);
res.json({ success: true });
} catch (err) {
console.error('[Super Delete Clinic]', err);
res.status(500).json({ error: 'Failed to delete clinic' });
}
});
/**
* GET /api/super/clinics/:id/users
*/
app.get('/api/super/clinics/:id/users', requireAuth('SUPER_ADMIN'), async (req, res) => {
try {
const result = await query(
`SELECT id, name, email, role, status, created_at FROM users WHERE tenant_id = $1 ORDER BY created_at`,
[req.params.id]
);
res.json(result.rows);
} catch (err) {
console.error('[Super Clinic Users]', err);
res.status(500).json({ error: 'Failed to fetch users' });
}
});
/**
* POST /api/super/clinics/:id/users
* Add a user to a clinic
*/
app.post('/api/super/clinics/:id/users', requireAuth('SUPER_ADMIN'), async (req, res) => {
const { name, email, password, role } = req.body;
const validRoles = ['OWNER', 'DOCTOR', 'RECEPTIONIST', 'PHARMACIST', 'LAB_TECH'];
if (!name || !email || !password || !role) return res.status(400).json({ error: 'Missing required fields' });
if (!validRoles.includes(role)) return res.status(400).json({ error: 'Invalid role' });
try {
const hash = await bcrypt.hash(password, 10);
const result = await query(
`INSERT INTO users (tenant_id, email, password_hash, name, role) VALUES ($1,$2,$3,$4,$5) RETURNING id`,
[req.params.id, email, hash, name, role]
);
res.json({ success: true, userId: result.rows[0].id });
} catch (err) {
if (err.code === '23505') return res.status(409).json({ error: 'Email already in use' });
console.error('[Super Add User]', err);
res.status(500).json({ error: 'Failed to create user' });
}
});
/**
* PATCH /api/super/users/:userId/status
*/
app.patch('/api/super/users/:userId/status', requireAuth('SUPER_ADMIN'), async (req, res) => {
const { status } = req.body;
if (!['active', 'inactive'].includes(status)) return res.status(400).json({ error: 'Invalid status' });
try {
await query('UPDATE users SET status = $1 WHERE id = $2 AND role != $3', [status, req.params.userId, 'SUPER_ADMIN']);
res.json({ success: true });
} catch (err) {
console.error('[Super User Status]', err);
res.status(500).json({ error: 'Failed to update user status' });
}
});
/**
* DELETE /api/super/users/:userId
*/
app.delete('/api/super/users/:userId', requireAuth('SUPER_ADMIN'), async (req, res) => {
try {
await query('DELETE FROM users WHERE id = $1 AND role != $2', [req.params.userId, 'SUPER_ADMIN']);
res.json({ success: true });
} catch (err) {
console.error('[Super Delete User]', err);
res.status(500).json({ error: 'Failed to delete user' });
}
});
/**
* GET /api/super/pending
*/
app.get('/api/super/pending', requireAuth('SUPER_ADMIN'), async (req, res) => {
try {
const result = await query(
`SELECT id, owner_name, clinic_name, specialty, city, whatsapp_number, email, plan, status, created_at
FROM pending_registrations ORDER BY created_at DESC`
);
res.json(result.rows);
} catch (err) {
console.error('[Super Pending]', err);
res.status(500).json({ error: 'Failed to fetch pending registrations' });
}
});
/**
* POST /api/super/pending/:id/approve
* Creates tenant + owner user, marks pending as approved
*/
app.post('/api/super/pending/:id/approve', requireAuth('SUPER_ADMIN'), async (req, res) => {
try {
const result = await query('SELECT * FROM pending_registrations WHERE id = $1', [req.params.id]);
if (result.rows.length === 0) return res.status(404).json({ error: 'Registration not found' });
const p = result.rows[0];
if (p.status !== 'pending') return res.status(400).json({ error: 'Already processed' });
const tenantId = await uniqueSlug(p.clinic_name);
await query('BEGIN');
try {
await query(
`INSERT INTO tenants (id, name, logo, specialty, city, whatsapp_number, plan)
VALUES ($1,$2,$3,$4,$5,$6,$7)`,
[tenantId, p.clinic_name, p.clinic_name[0].toUpperCase(),
p.specialty, p.city, p.whatsapp_number, p.plan]
);
await query(
`INSERT INTO users (tenant_id, email, password_hash, name, role)
VALUES ($1,$2,$3,$4,'OWNER')`,
[tenantId, p.email, p.password_hash, p.owner_name]
);
await query(
`UPDATE pending_registrations SET status = 'approved' WHERE id = $1`,
[p.id]
);
await query('COMMIT');
res.json({ success: true, tenantId });
} catch (inner) {
await query('ROLLBACK');
throw inner;
}
} catch (err) {
console.error('[Super Approve]', err);
if (err.code === '23505') return res.status(409).json({ error: 'Email already registered' });
res.status(500).json({ error: 'Failed to approve registration' });
}
});
/**
* POST /api/super/pending/:id/reject
*/
app.post('/api/super/pending/:id/reject', requireAuth('SUPER_ADMIN'), async (req, res) => {
try {
await query("UPDATE pending_registrations SET status = 'rejected' WHERE id = $1", [req.params.id]);
res.json({ success: true });
} catch (err) {
console.error('[Super Reject]', err);
res.status(500).json({ error: 'Failed to reject registration' });
}
});
// ── CLINIC OWNER ROUTES ───────────────────────────────────────────────────────
/**
* PATCH /api/clinic/settings clinic owner updates own settings
*/
app.patch('/api/clinic/settings', requireAuth('OWNER'), async (req, res) => {
const { consultationFee, workingHours, daysOff, holidays, primaryColor, secondaryColor } = req.body;
const tenantId = req.user.tenantId;
try {
const fields = [];
const values = [];
let i = 1;
if (consultationFee !== undefined) { fields.push(`consultation_fee=$${i++}`); values.push(consultationFee); }
if (primaryColor !== undefined) { fields.push(`primary_color=$${i++}`); values.push(primaryColor); }
if (secondaryColor !== undefined) { fields.push(`secondary_color=$${i++}`); values.push(secondaryColor); }
if (workingHours !== undefined) { fields.push(`working_hours=$${i++}::jsonb`); values.push(JSON.stringify(workingHours)); }
if (daysOff !== undefined) { fields.push(`days_off=$${i++}::jsonb`); values.push(JSON.stringify(daysOff)); }
if (holidays !== undefined) { fields.push(`holidays=$${i++}::jsonb`); values.push(JSON.stringify(holidays)); }
if (fields.length === 0) return res.status(400).json({ error: 'No fields to update' });
values.push(tenantId);
await query(`UPDATE tenants SET ${fields.join(',')} WHERE id=$${i}`, values);
res.json({ success: true });
} catch (err) {
console.error('[Clinic Settings]', err);
res.status(500).json({ error: 'Failed to update settings' });
}
});
// ── WHATSAPP WEBHOOK ──────────────────────────────────────────────────────────
app.post('/whatsapp/webhook', async (req, res) => {
const from = req.body.From || req.body.from;
const body = req.body.Body || req.body.body;
console.log(`[WhatsApp Webhook] Received message from ${from}: ${body}`);
if (!from || !body) return res.status(400).send('Missing from or body');
try {
const temporalClient = await getTemporalClient();
// Use the phone number as the unique Workflow ID
const workflowId = `booking-${from.replace(/[^a-zA-Z0-9]/g, '')}`;
let handle;
try {
handle = temporalClient.workflow.getHandle(workflowId);
const desc = await handle.describe();
if (desc.status.name === 'RUNNING') {
// Ongoing conversation! Send a signal with the new message
console.log(`[WhatsApp Webhook] Signaling existing workflow ${workflowId}`);
await handle.signal('receive_message', body);
// Twilio expects a valid TwiML response. Empty response means no immediate automated reply.
// Our Temporal worker will asynchronously send a reply back via Twilio API.
res.type('text/xml').send('<Response></Response>');
return;
return res.type('text/xml').send('<Response></Response>');
}
} catch (err) {
// Workflow does not exist. We will start a new one below.
}
} catch (err) { /* start new */ }
console.log(`[WhatsApp Webhook] Starting new AppointmentBookingWorkflow for ${from}`);
await temporalClient.workflow.start('AppointmentBookingWorkflow', {
args: [body, from],
taskQueue: 'curaflow-tasks',
workflowId: workflowId,
args: [body, from], taskQueue: 'curaflow-tasks', workflowId,
});
res.type('text/xml').send('<Response></Response>');
} catch (err) {
console.error('[WhatsApp Webhook] Error processing message:', err);
console.error('[WhatsApp Webhook] Error:', err);
res.status(500).send('Internal Server Error');
}
});
// AI Scribe Endpoints
// ── AI SCRIBE ─────────────────────────────────────────────────────────────────
app.post('/api/ai/scribe/start', async (req, res) => {
try {
const { dictation } = req.body;
if (!dictation) return res.status(400).json({ error: 'Dictation is required' });
const temporalClient = await getTemporalClient();
const jobId = `scribe-${crypto.randomUUID()}`;
console.log(`[AI Scribe] Starting job ${jobId} for dictation of length ${dictation.length}`);
// Start the workflow asynchronously
await temporalClient.workflow.start('ClinicalIntakeWorkflow', {
args: [dictation],
taskQueue: 'curaflow-tasks',
workflowId: jobId,
args: [dictation], taskQueue: 'curaflow-tasks', workflowId: jobId,
});
res.json({ success: true, jobId });
} catch (err) {
console.error('[AI Scribe] Start Error:', err);
@ -137,54 +538,38 @@ app.post('/api/ai/scribe/start', async (req, res) => {
app.get('/api/ai/scribe/status/:jobId', async (req, res) => {
try {
const { jobId } = req.params;
const temporalClient = await getTemporalClient();
const handle = temporalClient.workflow.getHandle(jobId);
const handle = temporalClient.workflow.getHandle(req.params.jobId);
const description = await handle.describe();
// Check if completed
if (description.status.name === 'COMPLETED') {
const result = await handle.result();
return res.json({ status: 'COMPLETED', result });
return res.json({ status: 'COMPLETED', result: await handle.result() });
} else if (description.status.name === 'FAILED') {
return res.json({ status: 'FAILED' });
}
return res.json({ status: description.status.name });
res.json({ status: description.status.name });
} catch (err) {
// If not found or error
console.error(`[AI Scribe] Status Error for ${req.params.jobId}:`, err);
console.error('[AI Scribe] Status Error:', err);
res.status(500).json({ error: 'Failed to get job status' });
}
});
// Lab Watcher Endpoints
// ── LAB WATCHER ───────────────────────────────────────────────────────────────
app.post('/api/ai/lab/watch/start', async (req, res) => {
try {
const { patientId, baselineData } = req.body;
if (!patientId) return res.status(400).json({ error: 'Patient ID is required' });
const temporalClient = await getTemporalClient();
const workflowId = `lab-watcher-${patientId}`;
// Ensure we don't start it twice if it's already running
try {
const handle = temporalClient.workflow.getHandle(workflowId);
const desc = await handle.describe();
if (desc.status.name === 'RUNNING') {
return res.json({ success: true, message: 'Watcher already running' });
}
} catch (e) {
// Not found, so we proceed to start it
}
if (desc.status.name === 'RUNNING') return res.json({ success: true, message: 'Watcher already running' });
} catch (e) { /* start new */ }
await temporalClient.workflow.start('LabResultWatcherWorkflow', {
args: [baselineData || { baseline: "Patient is healthy", medications: [] }],
taskQueue: 'curaflow-tasks',
workflowId: workflowId,
args: [baselineData || { baseline: 'Patient is healthy', medications: [] }],
taskQueue: 'curaflow-tasks', workflowId,
});
res.json({ success: true });
} catch (err) {
console.error('[AI Lab Watcher] Start Error:', err);
@ -194,42 +579,38 @@ app.post('/api/ai/lab/watch/start', async (req, res) => {
app.post('/api/ai/lab/result/:patientId', async (req, res) => {
try {
const { patientId } = req.params;
const { result } = req.body;
if (!result) return res.status(400).json({ error: 'Lab result string is required' });
const temporalClient = await getTemporalClient();
const workflowId = `lab-watcher-${patientId}`;
const handle = temporalClient.workflow.getHandle(workflowId);
const handle = temporalClient.workflow.getHandle(`lab-watcher-${req.params.patientId}`);
await handle.signal('add_lab_result', result);
res.json({ success: true });
} catch (err) {
console.error(`[AI Lab Watcher] Signal Error for ${req.params.patientId}:`, err);
console.error('[AI Lab Watcher] Signal Error:', err);
res.status(500).json({ error: 'Failed to send lab result to AI Watcher' });
}
});
app.get('/api/ai/lab/alerts/:patientId', async (req, res) => {
try {
const { patientId } = req.params;
const temporalClient = await getTemporalClient();
const workflowId = `lab-watcher-${patientId}`;
try {
const handle = temporalClient.workflow.getHandle(workflowId);
const handle = temporalClient.workflow.getHandle(`lab-watcher-${req.params.patientId}`);
const alerts = await handle.query('get_alerts');
res.json({ success: true, alerts });
return res.json({ success: true, alerts });
} catch (e) {
// Workflow might not be running
res.json({ success: true, alerts: [] });
}
} catch (err) {
console.error(`[AI Lab Watcher] Query Error for ${req.params.patientId}:`, err);
console.error('[AI Lab Watcher] Query Error:', err);
res.status(500).json({ error: 'Failed to fetch alerts' });
}
});
app.listen(port, '0.0.0.0', () => {
console.log(`Curio WhatsApp Mock Server running at http://0.0.0.0:${port}`);
// ── START ─────────────────────────────────────────────────────────────────────
initSchema().then(() => {
app.listen(port, '0.0.0.0', () => {
console.log(`Curio HMS running at http://0.0.0.0:${port}`);
});
});

View File

@ -13,7 +13,7 @@ spec:
labels:
app: curio-app
annotations:
redeploy-timestamp: "2026-05-24T18:55:00"
redeploy-timestamp: "2026-05-25T21:43:00"
spec:
containers:
- name: curio

View File

@ -107,3 +107,27 @@
.auth-footer a:hover {
text-decoration: underline;
}
/* ── Utility ── */
.hidden { display: none !important; }
.auth-error {
background: #FEF2F2;
border: 1px solid #FCA5A5;
color: #DC2626;
padding: 0.75rem 1rem;
border-radius: 8px;
margin-bottom: 1.25rem;
font-size: 0.875rem;
text-align: left;
}
.btn-spinner { font-size: 0.9rem; }
code {
background: var(--bg);
padding: 0.1rem 0.4rem;
border-radius: 4px;
font-size: 0.82rem;
color: var(--primary);
}

View File

@ -4,8 +4,8 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login | Curio HMS</title>
<meta name="description" content="Login to Curio HMS — India's WhatsApp-first hospital management platform.">
<link rel="stylesheet" href="globals.css">
<link rel="stylesheet" href="index.css">
<link rel="stylesheet" href="login.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
@ -21,55 +21,100 @@
</div>
<h2>Welcome Back</h2>
<p>Login to manage your clinic OPD and accounts.</p>
<div id="loginError" class="auth-error hidden"></div>
<form id="loginForm">
<div class="input-group">
<label for="clinicId">Clinic ID / Email</label>
<input type="text" id="clinicId" placeholder="e.g. SHARMA-CLINIC-01" required>
<label for="loginEmail">Email Address</label>
<input type="email" id="loginEmail" placeholder="doctor@yourclinic.com" required autocomplete="email">
</div>
<div class="input-group">
<label for="password">Password</label>
<input type="password" id="password" placeholder="••••••••" required>
<label for="loginPassword">Password</label>
<input type="password" id="loginPassword" placeholder="••••••••" required autocomplete="current-password">
</div>
<button type="submit" class="btn-primary auth-btn">Login to Dashboard</button>
<button type="submit" class="btn-primary auth-btn" id="loginBtn">
<span id="loginBtnText">Login to Dashboard</span>
<span id="loginSpinner" class="btn-spinner hidden"></span>
</button>
</form>
<p class="auth-footer">New to Curio? <a href="register.html">Register your clinic</a></p>
<p class="auth-footer" style="font-size:0.78rem; color: var(--text-muted);">
Demo: <code>admin@curio.app</code> / <code>superadmin</code>
</p>
</div>
</div>
<script>
document.getElementById('loginForm').onsubmit = (e) => {
// Redirect if already logged in
(function() {
const token = localStorage.getItem('curio_token');
if (token) {
try {
const p = JSON.parse(atob(token.split('.')[1]));
if (p.exp && Date.now() / 1000 < p.exp) {
window.location.href = p.role === 'SUPER_ADMIN' ? 'super-admin.html' : 'dashboard.html';
}
} catch(_) {}
}
})();
const form = document.getElementById('loginForm');
const errBox = document.getElementById('loginError');
const btn = document.getElementById('loginBtn');
const btnTxt = document.getElementById('loginBtnText');
const spin = document.getElementById('loginSpinner');
function showError(msg) {
errBox.textContent = msg;
errBox.classList.remove('hidden');
}
form.addEventListener('submit', async (e) => {
e.preventDefault();
const email = e.target.querySelector('input[type="text"]').value;
const password = e.target.querySelector('input[type="password"]').value;
console.log("Attempting login for:", email);
errBox.classList.add('hidden');
btn.disabled = true;
btnTxt.textContent = 'Logging in...';
spin.classList.remove('hidden');
// System Admin
if (email === 'admin@curio.app' && password === 'superadmin') {
localStorage.setItem('userRole', 'SUPER_ADMIN');
localStorage.setItem('userEmail', email);
window.location.href = 'super-admin.html';
return;
const email = document.getElementById('loginEmail').value.trim();
const password = document.getElementById('loginPassword').value;
try {
const res = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
const data = await res.json();
if (!res.ok) {
showError(data.error || 'Login failed. Please try again.');
return;
}
// Store JWT and user info
localStorage.setItem('curio_token', data.token);
localStorage.setItem('userRole', data.role);
localStorage.setItem('userEmail', email);
localStorage.setItem('userName', data.name || '');
if (data.tenantId) localStorage.setItem('Curio_tenant', data.tenantId);
// Route by role
if (data.role === 'SUPER_ADMIN') {
window.location.href = 'super-admin.html';
} else {
window.location.href = 'dashboard.html';
}
} catch (err) {
showError('Network error. Please check your connection.');
} finally {
btn.disabled = false;
btnTxt.textContent = 'Login to Dashboard';
spin.classList.add('hidden');
}
// Mock Hospital Users
const users = {
'owner@sharma.clinic': { role: 'OWNER', pass: 'owner123' },
'doctor@sharma.clinic': { role: 'DOCTOR', pass: 'doc123' },
'rec@sharma.clinic': { role: 'RECEPTIONIST', pass: 'rec123' }
};
const user = users[email];
if (user && user.pass === password) {
localStorage.setItem('userRole', user.role);
localStorage.setItem('userEmail', email);
window.location.href = 'dashboard.html';
} else {
alert('Invalid credentials.\n\nTry:\n- admin@curio.app / superadmin\n- doctor@sharma.clinic / doc123');
}
};
});
</script>
</body>
</html>

16
node_modules/.bin/bcrypt generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../bcryptjs/bin/bcrypt" "$@"
else
exec node "$basedir/../bcryptjs/bin/bcrypt" "$@"
fi

17
node_modules/.bin/bcrypt.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\bcryptjs\bin\bcrypt" %*

28
node_modules/.bin/bcrypt.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../bcryptjs/bin/bcrypt" $args
} else {
& "$basedir/node$exe" "$basedir/../bcryptjs/bin/bcrypt" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../bcryptjs/bin/bcrypt" $args
} else {
& "node$exe" "$basedir/../bcryptjs/bin/bcrypt" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
node_modules/.bin/semver generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../semver/bin/semver.js" "$@"
else
exec node "$basedir/../semver/bin/semver.js" "$@"
fi

17
node_modules/.bin/semver.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\semver\bin\semver.js" %*

28
node_modules/.bin/semver.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args
} else {
& "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../semver/bin/semver.js" $args
} else {
& "node$exe" "$basedir/../semver/bin/semver.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

274
node_modules/.package-lock.json generated vendored
View File

@ -231,6 +231,15 @@
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
"license": "MIT"
},
"node_modules/bcryptjs": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.3.tgz",
"integrity": "sha512-GlF5wPWnSa/X5LKM1o0wz0suXIINz1iHRLvTS+sLyi7XPbe5ycmYI3DlZqVGZZtDgl4DmasFg7gOB3JYbphV5g==",
"license": "BSD-3-Clause",
"bin": {
"bcrypt": "bin/bcrypt"
}
},
"node_modules/body-parser": {
"version": "1.20.5",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.5.tgz",
@ -255,6 +264,12 @@
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/buffer-equal-constant-time": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
"license": "BSD-3-Clause"
},
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
@ -409,6 +424,15 @@
"node": ">= 0.4"
}
},
"node_modules/ecdsa-sig-formatter": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
"integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
"license": "Apache-2.0",
"dependencies": {
"safe-buffer": "^5.0.1"
}
},
"node_modules/ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
@ -722,12 +746,103 @@
"node": ">=8"
}
},
"node_modules/jsonwebtoken": {
"version": "9.0.3",
"resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz",
"integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==",
"license": "MIT",
"dependencies": {
"jws": "^4.0.1",
"lodash.includes": "^4.3.0",
"lodash.isboolean": "^3.0.3",
"lodash.isinteger": "^4.0.4",
"lodash.isnumber": "^3.0.3",
"lodash.isplainobject": "^4.0.6",
"lodash.isstring": "^4.0.1",
"lodash.once": "^4.0.0",
"ms": "^2.1.1",
"semver": "^7.5.4"
},
"engines": {
"node": ">=12",
"npm": ">=6"
}
},
"node_modules/jsonwebtoken/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/jwa": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",
"integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
"license": "MIT",
"dependencies": {
"buffer-equal-constant-time": "^1.0.1",
"ecdsa-sig-formatter": "1.0.11",
"safe-buffer": "^5.0.1"
}
},
"node_modules/jws": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",
"integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",
"license": "MIT",
"dependencies": {
"jwa": "^2.0.1",
"safe-buffer": "^5.0.1"
}
},
"node_modules/lodash.camelcase": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz",
"integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==",
"license": "MIT"
},
"node_modules/lodash.includes": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
"integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==",
"license": "MIT"
},
"node_modules/lodash.isboolean": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
"integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==",
"license": "MIT"
},
"node_modules/lodash.isinteger": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",
"integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==",
"license": "MIT"
},
"node_modules/lodash.isnumber": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",
"integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==",
"license": "MIT"
},
"node_modules/lodash.isplainobject": {
"version": "4.0.6",
"resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
"integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==",
"license": "MIT"
},
"node_modules/lodash.isstring": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",
"integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==",
"license": "MIT"
},
"node_modules/lodash.once": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
"integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==",
"license": "MIT"
},
"node_modules/long": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
@ -869,6 +984,135 @@
"integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==",
"license": "MIT"
},
"node_modules/pg": {
"version": "8.21.0",
"resolved": "https://registry.npmjs.org/pg/-/pg-8.21.0.tgz",
"integrity": "sha512-AUP1EYJuHraQGsVoCQVIcM7TEJVGtDzxWtGFZd8rds9d+CCXlU5Js1rYgfLNvxy9iJrpHjGrRjoi/3BT9fRyiA==",
"license": "MIT",
"peer": true,
"dependencies": {
"pg-connection-string": "^2.13.0",
"pg-pool": "^3.14.0",
"pg-protocol": "^1.14.0",
"pg-types": "2.2.0",
"pgpass": "1.0.5"
},
"engines": {
"node": ">= 16.0.0"
},
"optionalDependencies": {
"pg-cloudflare": "^1.4.0"
},
"peerDependencies": {
"pg-native": ">=3.0.1"
},
"peerDependenciesMeta": {
"pg-native": {
"optional": true
}
}
},
"node_modules/pg-cloudflare": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.0.tgz",
"integrity": "sha512-Vo7z/6rrQYxpNRylp4Tlob2elzbh+N/MOQbxFVWCxS7oEx6jF53GTJFxK2WWpKuBRkmiin4Mt+xofFDjx09R0A==",
"license": "MIT",
"optional": true
},
"node_modules/pg-connection-string": {
"version": "2.13.0",
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.13.0.tgz",
"integrity": "sha512-EMnU9E2fSULdsbErBbMaXJvFeD9B4+nPcM3f+4lsiCR0BHLPrLVjv3DbyM2hgQQviKJaTWIRRTjKjWlHg3p2ig==",
"license": "MIT"
},
"node_modules/pg-int8": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
"license": "ISC",
"engines": {
"node": ">=4.0.0"
}
},
"node_modules/pg-pool": {
"version": "3.14.0",
"resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz",
"integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==",
"license": "MIT",
"peerDependencies": {
"pg": ">=8.0"
}
},
"node_modules/pg-protocol": {
"version": "1.14.0",
"resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.14.0.tgz",
"integrity": "sha512-n5taZ1kO3s9ngDTVxsEznOqCyToTgz0FLuPq0B33COy5pPpuWJpY3/2oRBVETuOgzdqRXfWpM9HIhp2LBBT1BA==",
"license": "MIT"
},
"node_modules/pg-types": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
"license": "MIT",
"dependencies": {
"pg-int8": "1.0.1",
"postgres-array": "~2.0.0",
"postgres-bytea": "~1.0.0",
"postgres-date": "~1.0.4",
"postgres-interval": "^1.1.0"
},
"engines": {
"node": ">=4"
}
},
"node_modules/pgpass": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
"license": "MIT",
"dependencies": {
"split2": "^4.1.0"
}
},
"node_modules/postgres-array": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/postgres-bytea": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
"integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/postgres-date": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/postgres-interval": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
"license": "MIT",
"dependencies": {
"xtend": "^4.0.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/proto3-json-serializer": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/proto3-json-serializer/-/proto3-json-serializer-2.0.2.tgz",
@ -992,6 +1236,18 @@
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/semver": {
"version": "7.8.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.1.tgz",
"integrity": "sha512-rkVq3IXh+4FDGch+KwzX3aV9W3kO54GyEgpvBzSyctDA6Xtd7RJQV1xmXbeQp5v7+VzLOfVqiutSE6GICgPFvg==",
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/send": {
"version": "0.19.2",
"resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz",
@ -1115,6 +1371,15 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/split2": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
"integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
"license": "ISC",
"engines": {
"node": ">= 10.x"
}
},
"node_modules/statuses": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
@ -1235,6 +1500,15 @@
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/xtend": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
"license": "MIT",
"engines": {
"node": ">=0.4"
}
},
"node_modules/y18n": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",

27
node_modules/bcryptjs/LICENSE generated vendored Normal file
View File

@ -0,0 +1,27 @@
bcrypt.js
---------
Copyright (c) 2012 Nevins Bartolomeo <nevins.bartolomeo@gmail.com>
Copyright (c) 2012 Shane Girish <shaneGirish@gmail.com>
Copyright (c) 2025 Daniel Wirtz <dcode@dcode.io>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

201
node_modules/bcryptjs/README.md generated vendored Normal file
View File

@ -0,0 +1,201 @@
# bcrypt.js
Optimized bcrypt in JavaScript with zero dependencies, with TypeScript support. Compatible to the C++
[bcrypt](https://npmjs.org/package/bcrypt) binding on Node.js and also working in the browser.
[![Build Status](https://img.shields.io/github/actions/workflow/status/dcodeIO/bcrypt.js/test.yml?branch=main&label=test&logo=github)](https://github.com/dcodeIO/bcrypt.js/actions/workflows/test.yml) [![Publish Status](https://img.shields.io/github/actions/workflow/status/dcodeIO/bcrypt.js/publish.yml?branch=main&label=publish&logo=github)](https://github.com/dcodeIO/bcrypt.js/actions/workflows/publish.yml) [![npm](https://img.shields.io/npm/v/bcryptjs.svg?label=npm&color=007acc&logo=npm)](https://www.npmjs.com/package/bcryptjs)
## Security considerations
Besides incorporating a salt to protect against rainbow table attacks, bcrypt is an adaptive function: over time, the
iteration count can be increased to make it slower, so it remains resistant to brute-force search attacks even with
increasing computation power. ([see](http://en.wikipedia.org/wiki/Bcrypt))
While bcrypt.js is compatible to the C++ bcrypt binding, it is written in pure JavaScript and thus slower ([about 30%](https://github.com/dcodeIO/bcrypt.js/wiki/Benchmark)), effectively reducing the number of iterations that can be
processed in an equal time span.
The maximum input length is 72 bytes (note that UTF-8 encoded characters use up to 4 bytes) and the length of generated
hashes is 60 characters. Note that maximum input length is not implicitly checked by the library for compatibility with
the C++ binding on Node.js, but should be checked with `bcrypt.truncates(password)` where necessary.
## Usage
The package exports an ECMAScript module with an UMD fallback.
```
$> npm install bcryptjs
```
```ts
import bcrypt from "bcryptjs";
```
### Usage with a CDN
- From GitHub via [jsDelivr](https://www.jsdelivr.com):<br />
`https://cdn.jsdelivr.net/gh/dcodeIO/bcrypt.js@TAG/index.js` (ESM)
- From npm via [jsDelivr](https://www.jsdelivr.com):<br />
`https://cdn.jsdelivr.net/npm/bcryptjs@VERSION/index.js` (ESM)<br />
`https://cdn.jsdelivr.net/npm/bcryptjs@VERSION/umd/index.js` (UMD)
- From npm via [unpkg](https://unpkg.com):<br />
`https://unpkg.com/bcryptjs@VERSION/index.js` (ESM)<br />
`https://unpkg.com/bcryptjs@VERSION/umd/index.js` (UMD)
Replace `TAG` respectively `VERSION` with a [specific version](https://github.com/dcodeIO/bcrypt.js/releases) or omit it (not recommended in production) to use latest.
When using the ESM variant in a browser, the `crypto` import needs to be stubbed out, for example using an [import map](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script/type/importmap). Bundlers should omit it automatically.
### Usage - Sync
To hash a password:
```ts
const salt = bcrypt.genSaltSync(10);
const hash = bcrypt.hashSync("B4c0/\/", salt);
// Store hash in your password DB
```
To check a password:
```ts
// Load hash from your password DB
bcrypt.compareSync("B4c0/\/", hash); // true
bcrypt.compareSync("not_bacon", hash); // false
```
Auto-gen a salt and hash:
```ts
const hash = bcrypt.hashSync("bacon", 10);
```
### Usage - Async
To hash a password:
```ts
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash("B4c0/\/", salt);
// Store hash in your password DB
```
```ts
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash("B4c0/\/", salt, function (err, hash) {
// Store hash in your password DB
});
});
```
To check a password:
```ts
// Load hash from your password DB
await bcrypt.compare("B4c0/\/", hash); // true
await bcrypt.compare("not_bacon", hash); // false
```
```ts
// Load hash from your password DB
bcrypt.compare("B4c0/\/", hash, (err, res) => {
// res === true
});
bcrypt.compare("not_bacon", hash, (err, res) => {
// res === false
});
```
Auto-gen a salt and hash:
```ts
await bcrypt.hash("B4c0/\/", 10);
// Store hash in your password DB
```
```ts
bcrypt.hash("B4c0/\/", 10, (err, hash) => {
// Store hash in your password DB
});
```
**Note:** Under the hood, asynchronous APIs split an operation into small chunks. After the completion of a chunk, the execution of the next chunk is placed on the back of the [JS event queue](https://developer.mozilla.org/en/docs/Web/JavaScript/EventLoop), efficiently yielding for other computation to execute.
### Usage - Command Line
```
Usage: bcrypt <input> [rounds|salt]
```
## API
### Callback types
- **Callback<`T`>**: `(err: Error | null, result?: T) => void`<br />
Called with an error on failure or a value of type `T` upon success.
- **ProgressCallback**: `(percentage: number) => void`<br />
Called with the percentage of rounds completed (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms.
- **RandomFallback**: `(length: number) => number[]`<br />
Called to obtain random bytes when both [Web Crypto API](http://www.w3.org/TR/WebCryptoAPI/) and Node.js
[crypto](http://nodejs.org/api/crypto.html) are not available.
### Functions
- bcrypt.**genSaltSync**(rounds?: `number`): `string`<br />
Synchronously generates a salt. Number of rounds defaults to 10 when omitted.
- bcrypt.**genSalt**(rounds?: `number`): `Promise<string>`<br />
Asynchronously generates a salt. Number of rounds defaults to 10 when omitted.
- bcrypt.**genSalt**([rounds: `number`, ]callback: `Callback<string>`): `void`<br />
Asynchronously generates a salt. Number of rounds defaults to 10 when omitted.
- bcrypt.**truncates**(password: `string`): `boolean`<br />
Tests if a password will be truncated when hashed, that is its length is greater than 72 bytes when converted to UTF-8.
- bcrypt.**hashSync**(password: `string`, salt?: `number | string`): `string`
Synchronously generates a hash for the given password. Number of rounds defaults to 10 when omitted.
- bcrypt.**hash**(password: `string`, salt: `number | string`): `Promise<string>`<br />
Asynchronously generates a hash for the given password.
- bcrypt.**hash**(password: `string`, salt: `number | string`, callback: `Callback<string>`, progressCallback?: `ProgressCallback`): `void`<br />
Asynchronously generates a hash for the given password.
- bcrypt.**compareSync**(password: `string`, hash: `string`): `boolean`<br />
Synchronously tests a password against a hash.
- bcrypt.**compare**(password: `string`, hash: `string`): `Promise<boolean>`<br />
Asynchronously compares a password against a hash.
- bcrypt.**compare**(password: `string`, hash: `string`, callback: `Callback<boolean>`, progressCallback?: `ProgressCallback`)<br />
Asynchronously compares a password against a hash.
- bcrypt.**getRounds**(hash: `string`): `number`<br />
Gets the number of rounds used to encrypt the specified hash.
- bcrypt.**getSalt**(hash: `string`): `string`<br />
Gets the salt portion from a hash. Does not validate the hash.
- bcrypt.**setRandomFallback**(random: `RandomFallback`): `void`<br />
Sets the pseudo random number generator to use as a fallback if neither [Web Crypto API](http://www.w3.org/TR/WebCryptoAPI/) nor Node.js [crypto](http://nodejs.org/api/crypto.html) are available. Please note: It is highly important that the PRNG used is cryptographically secure and that it is seeded properly!
## Building
Building the UMD fallback:
```
$> npm run build
```
Running the [tests](./tests):
```
$> npm test
```
## Credits
Based on work started by Shane Girish at [bcrypt-nodejs](https://github.com/shaneGirish/bcrypt-nodejs), which is itself
based on [javascript-bcrypt](http://code.google.com/p/javascript-bcrypt/) (New BSD-licensed).

23
node_modules/bcryptjs/bin/bcrypt generated vendored Normal file
View File

@ -0,0 +1,23 @@
#!/usr/bin/env node
import path from "node:path";
import bcrypt from "../index.js";
if (process.argv.length < 3) {
console.log(
"Usage: " + path.basename(process.argv[1]) + " <input> [rounds|salt]",
);
process.exit(1);
} else {
var salt;
if (process.argv.length > 3) {
salt = process.argv[3];
var rounds = parseInt(salt, 10);
if (rounds == salt) {
salt = bcrypt.genSaltSync(rounds);
}
} else {
salt = bcrypt.genSaltSync();
}
console.log(bcrypt.hashSync(process.argv[2], salt));
}

3
node_modules/bcryptjs/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,3 @@
import * as bcrypt from "./types.js";
export * from "./types.js";
export default bcrypt;

1159
node_modules/bcryptjs/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

76
node_modules/bcryptjs/package.json generated vendored Normal file
View File

@ -0,0 +1,76 @@
{
"name": "bcryptjs",
"description": "Optimized bcrypt in plain JavaScript with zero dependencies, with TypeScript support. Compatible to 'bcrypt'.",
"version": "3.0.3",
"author": "Daniel Wirtz <dcode@dcode.io>",
"contributors": [
"Shane Girish <shaneGirish@gmail.com> (https://github.com/shaneGirish)",
"Alex Murray <> (https://github.com/alexmurray)",
"Nicolas Pelletier <> (https://github.com/NicolasPelletier)",
"Josh Rogers <> (https://github.com/geekymole)",
"Noah Isaacson <noah@nisaacson.com> (https://github.com/nisaacson)"
],
"repository": {
"type": "url",
"url": "https://github.com/dcodeIO/bcrypt.js.git"
},
"bugs": {
"url": "https://github.com/dcodeIO/bcrypt.js/issues"
},
"keywords": [
"bcrypt",
"password",
"auth",
"authentication",
"encryption",
"crypt",
"crypto"
],
"type": "module",
"main": "umd/index.js",
"types": "umd/index.d.ts",
"exports": {
".": {
"import": {
"types": "./index.d.ts",
"default": "./index.js"
},
"require": {
"types": "./umd/index.d.ts",
"default": "./umd/index.js"
}
}
},
"bin": {
"bcrypt": "bin/bcrypt"
},
"license": "BSD-3-Clause",
"scripts": {
"build": "node scripts/build.js",
"lint": "prettier --check .",
"format": "prettier --write .",
"test": "npm run test:unit && npm run test:typescript",
"test:unit": "node tests",
"test:typescript": "tsc --project tests/typescript/tsconfig.esnext.json && tsc --project tests/typescript/tsconfig.nodenext.json && tsc --project tests/typescript/tsconfig.commonjs.json && tsc --project tests/typescript/tsconfig.global.json"
},
"files": [
"index.js",
"index.d.ts",
"types.d.ts",
"umd/index.js",
"umd/index.d.ts",
"umd/types.d.ts",
"umd/package.json",
"LICENSE",
"README.md"
],
"browser": {
"crypto": false
},
"devDependencies": {
"bcrypt": "^5.1.1",
"esm2umd": "^0.3.1",
"prettier": "^3.5.0",
"typescript": "^5.7.3"
}
}

157
node_modules/bcryptjs/types.d.ts generated vendored Normal file
View File

@ -0,0 +1,157 @@
// Originally imported from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/8b36dbdf95b624b8a7cd7f8416f06c15d274f9e6/types/bcryptjs/index.d.ts
// MIT license.
/** Called with an error on failure or a value of type `T` upon success. */
type Callback<T> = (err: Error | null, result?: T) => void;
/** Called with the percentage of rounds completed (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms. */
type ProgressCallback = (percentage: number) => void;
/** Called to obtain random bytes when both Web Crypto API and Node.js crypto are not available. */
type RandomFallback = (length: number) => number[];
/**
* Sets the pseudo random number generator to use as a fallback if neither node's crypto module nor the Web Crypto API is available.
* Please note: It is highly important that the PRNG used is cryptographically secure and that it is seeded properly!
* @param random Function taking the number of bytes to generate as its sole argument, returning the corresponding array of cryptographically secure random byte values.
*/
export declare function setRandomFallback(random: RandomFallback): void;
/**
* Synchronously generates a salt.
* @param rounds Number of rounds to use, defaults to 10 if omitted
* @return Resulting salt
* @throws If a random fallback is required but not set
*/
export declare function genSaltSync(rounds?: number): string;
/**
* Asynchronously generates a salt.
* @param rounds Number of rounds to use, defaults to 10 if omitted
* @return Promise with resulting salt, if callback has been omitted
*/
export declare function genSalt(rounds?: number): Promise<string>;
/**
* Asynchronously generates a salt.
* @param callback Callback receiving the error, if any, and the resulting salt
*/
export declare function genSalt(callback: Callback<string>): void;
/**
* Asynchronously generates a salt.
* @param rounds Number of rounds to use, defaults to 10 if omitted
* @param callback Callback receiving the error, if any, and the resulting salt
*/
export declare function genSalt(
rounds: number,
callback: Callback<string>,
): void;
/**
* Synchronously generates a hash for the given password.
* @param password Password to hash
* @param salt Salt length to generate or salt to use, default to 10
* @return Resulting hash
*/
export declare function hashSync(
password: string,
salt?: number | string,
): string;
/**
* Asynchronously generates a hash for the given password.
* @param password Password to hash
* @param salt Salt length to generate or salt to use
* @return Promise with resulting hash, if callback has been omitted
*/
export declare function hash(
password: string,
salt: number | string,
): Promise<string>;
/**
* Asynchronously generates a hash for the given password.
* @param password Password to hash
* @param salt Salt length to generate or salt to use
* @param callback Callback receiving the error, if any, and the resulting hash
* @param progressCallback Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per MAX_EXECUTION_TIME = 100 ms.
*/
export declare function hash(
password: string,
salt: number | string,
callback?: Callback<string>,
progressCallback?: ProgressCallback,
): void;
/**
* Synchronously tests a password against a hash.
* @param password Password to test
* @param hash Hash to test against
* @return true if matching, otherwise false
*/
export declare function compareSync(password: string, hash: string): boolean;
/**
* Asynchronously tests a password against a hash.
* @param password Password to test
* @param hash Hash to test against
* @return Promise, if callback has been omitted
*/
export declare function compare(
password: string,
hash: string,
): Promise<boolean>;
/**
* Asynchronously tests a password against a hash.
* @param password Password to test
* @param hash Hash to test against
* @param callback Callback receiving the error, if any, otherwise the result
* @param progressCallback Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per MAX_EXECUTION_TIME = 100 ms.
*/
export declare function compare(
password: string,
hash: string,
callback?: Callback<boolean>,
progressCallback?: ProgressCallback,
): void;
/**
* Gets the number of rounds used to encrypt the specified hash.
* @param hash Hash to extract the used number of rounds from
* @return Number of rounds used
*/
export declare function getRounds(hash: string): number;
/**
* Gets the salt portion from a hash. Does not validate the hash.
* @param hash Hash to extract the salt from
* @return Extracted salt part
*/
export declare function getSalt(hash: string): string;
/**
* Tests if a password will be truncated when hashed, that is its length is
* greater than 72 bytes when converted to UTF-8.
* @param password The password to test
* @returns `true` if truncated, otherwise `false`
*/
export declare function truncates(password: string): boolean;
/**
* Encodes a byte array to base64 with up to len bytes of input, using the custom bcrypt alphabet.
* @function
* @param b Byte array
* @param len Maximum input length
*/
export declare function encodeBase64(
b: Readonly<ArrayLike<number>>,
len: number,
): string;
/**
* Decodes a base64 encoded string to up to len bytes of output, using the custom bcrypt alphabet.
* @function
* @param s String to decode
* @param len Maximum output length
*/
export declare function decodeBase64(s: string, len: number): number[];

3
node_modules/bcryptjs/umd/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,3 @@
import * as bcrypt from "./types.js";
export = bcrypt;
export as namespace bcrypt;

1220
node_modules/bcryptjs/umd/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

3
node_modules/bcryptjs/umd/package.json generated vendored Normal file
View File

@ -0,0 +1,3 @@
{
"type": "commonjs"
}

157
node_modules/bcryptjs/umd/types.d.ts generated vendored Normal file
View File

@ -0,0 +1,157 @@
// Originally imported from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/8b36dbdf95b624b8a7cd7f8416f06c15d274f9e6/types/bcryptjs/index.d.ts
// MIT license.
/** Called with an error on failure or a value of type `T` upon success. */
type Callback<T> = (err: Error | null, result?: T) => void;
/** Called with the percentage of rounds completed (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms. */
type ProgressCallback = (percentage: number) => void;
/** Called to obtain random bytes when both Web Crypto API and Node.js crypto are not available. */
type RandomFallback = (length: number) => number[];
/**
* Sets the pseudo random number generator to use as a fallback if neither node's crypto module nor the Web Crypto API is available.
* Please note: It is highly important that the PRNG used is cryptographically secure and that it is seeded properly!
* @param random Function taking the number of bytes to generate as its sole argument, returning the corresponding array of cryptographically secure random byte values.
*/
export declare function setRandomFallback(random: RandomFallback): void;
/**
* Synchronously generates a salt.
* @param rounds Number of rounds to use, defaults to 10 if omitted
* @return Resulting salt
* @throws If a random fallback is required but not set
*/
export declare function genSaltSync(rounds?: number): string;
/**
* Asynchronously generates a salt.
* @param rounds Number of rounds to use, defaults to 10 if omitted
* @return Promise with resulting salt, if callback has been omitted
*/
export declare function genSalt(rounds?: number): Promise<string>;
/**
* Asynchronously generates a salt.
* @param callback Callback receiving the error, if any, and the resulting salt
*/
export declare function genSalt(callback: Callback<string>): void;
/**
* Asynchronously generates a salt.
* @param rounds Number of rounds to use, defaults to 10 if omitted
* @param callback Callback receiving the error, if any, and the resulting salt
*/
export declare function genSalt(
rounds: number,
callback: Callback<string>,
): void;
/**
* Synchronously generates a hash for the given password.
* @param password Password to hash
* @param salt Salt length to generate or salt to use, default to 10
* @return Resulting hash
*/
export declare function hashSync(
password: string,
salt?: number | string,
): string;
/**
* Asynchronously generates a hash for the given password.
* @param password Password to hash
* @param salt Salt length to generate or salt to use
* @return Promise with resulting hash, if callback has been omitted
*/
export declare function hash(
password: string,
salt: number | string,
): Promise<string>;
/**
* Asynchronously generates a hash for the given password.
* @param password Password to hash
* @param salt Salt length to generate or salt to use
* @param callback Callback receiving the error, if any, and the resulting hash
* @param progressCallback Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per MAX_EXECUTION_TIME = 100 ms.
*/
export declare function hash(
password: string,
salt: number | string,
callback?: Callback<string>,
progressCallback?: ProgressCallback,
): void;
/**
* Synchronously tests a password against a hash.
* @param password Password to test
* @param hash Hash to test against
* @return true if matching, otherwise false
*/
export declare function compareSync(password: string, hash: string): boolean;
/**
* Asynchronously tests a password against a hash.
* @param password Password to test
* @param hash Hash to test against
* @return Promise, if callback has been omitted
*/
export declare function compare(
password: string,
hash: string,
): Promise<boolean>;
/**
* Asynchronously tests a password against a hash.
* @param password Password to test
* @param hash Hash to test against
* @param callback Callback receiving the error, if any, otherwise the result
* @param progressCallback Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per MAX_EXECUTION_TIME = 100 ms.
*/
export declare function compare(
password: string,
hash: string,
callback?: Callback<boolean>,
progressCallback?: ProgressCallback,
): void;
/**
* Gets the number of rounds used to encrypt the specified hash.
* @param hash Hash to extract the used number of rounds from
* @return Number of rounds used
*/
export declare function getRounds(hash: string): number;
/**
* Gets the salt portion from a hash. Does not validate the hash.
* @param hash Hash to extract the salt from
* @return Extracted salt part
*/
export declare function getSalt(hash: string): string;
/**
* Tests if a password will be truncated when hashed, that is its length is
* greater than 72 bytes when converted to UTF-8.
* @param password The password to test
* @returns `true` if truncated, otherwise `false`
*/
export declare function truncates(password: string): boolean;
/**
* Encodes a byte array to base64 with up to len bytes of input, using the custom bcrypt alphabet.
* @function
* @param b Byte array
* @param len Maximum input length
*/
export declare function encodeBase64(
b: Readonly<ArrayLike<number>>,
len: number,
): string;
/**
* Decodes a base64 encoded string to up to len bytes of output, using the custom bcrypt alphabet.
* @function
* @param s String to decode
* @param len Maximum output length
*/
export declare function decodeBase64(s: string, len: number): number[];

2
node_modules/buffer-equal-constant-time/.npmignore generated vendored Normal file
View File

@ -0,0 +1,2 @@
.*.sw[mnop]
node_modules/

4
node_modules/buffer-equal-constant-time/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,4 @@
language: node_js
node_js:
- "0.11"
- "0.10"

12
node_modules/buffer-equal-constant-time/LICENSE.txt generated vendored Normal file
View File

@ -0,0 +1,12 @@
Copyright (c) 2013, GoInstant Inc., a salesforce.com company
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of salesforce.com, nor GoInstant, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

50
node_modules/buffer-equal-constant-time/README.md generated vendored Normal file
View File

@ -0,0 +1,50 @@
# buffer-equal-constant-time
Constant-time `Buffer` comparison for node.js. Should work with browserify too.
[![Build Status](https://travis-ci.org/goinstant/buffer-equal-constant-time.png?branch=master)](https://travis-ci.org/goinstant/buffer-equal-constant-time)
```sh
npm install buffer-equal-constant-time
```
# Usage
```js
var bufferEq = require('buffer-equal-constant-time');
var a = new Buffer('asdf');
var b = new Buffer('asdf');
if (bufferEq(a,b)) {
// the same!
} else {
// different in at least one byte!
}
```
If you'd like to install an `.equal()` method onto the node.js `Buffer` and
`SlowBuffer` prototypes:
```js
require('buffer-equal-constant-time').install();
var a = new Buffer('asdf');
var b = new Buffer('asdf');
if (a.equal(b)) {
// the same!
} else {
// different in at least one byte!
}
```
To get rid of the installed `.equal()` method, call `.restore()`:
```js
require('buffer-equal-constant-time').restore();
```
# Legal
&copy; 2013 GoInstant Inc., a salesforce.com company
Licensed under the BSD 3-clause license.

41
node_modules/buffer-equal-constant-time/index.js generated vendored Normal file
View File

@ -0,0 +1,41 @@
/*jshint node:true */
'use strict';
var Buffer = require('buffer').Buffer; // browserify
var SlowBuffer = require('buffer').SlowBuffer;
module.exports = bufferEq;
function bufferEq(a, b) {
// shortcutting on type is necessary for correctness
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
return false;
}
// buffer sizes should be well-known information, so despite this
// shortcutting, it doesn't leak any information about the *contents* of the
// buffers.
if (a.length !== b.length) {
return false;
}
var c = 0;
for (var i = 0; i < a.length; i++) {
/*jshint bitwise:false */
c |= a[i] ^ b[i]; // XOR
}
return c === 0;
}
bufferEq.install = function() {
Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) {
return bufferEq(this, that);
};
};
var origBufEqual = Buffer.prototype.equal;
var origSlowBufEqual = SlowBuffer.prototype.equal;
bufferEq.restore = function() {
Buffer.prototype.equal = origBufEqual;
SlowBuffer.prototype.equal = origSlowBufEqual;
};

21
node_modules/buffer-equal-constant-time/package.json generated vendored Normal file
View File

@ -0,0 +1,21 @@
{
"name": "buffer-equal-constant-time",
"version": "1.0.1",
"description": "Constant-time comparison of Buffers",
"main": "index.js",
"scripts": {
"test": "mocha test.js"
},
"repository": "git@github.com:goinstant/buffer-equal-constant-time.git",
"keywords": [
"buffer",
"equal",
"constant-time",
"crypto"
],
"author": "GoInstant Inc., a salesforce.com company",
"license": "BSD-3-Clause",
"devDependencies": {
"mocha": "~1.15.1"
}
}

42
node_modules/buffer-equal-constant-time/test.js generated vendored Normal file
View File

@ -0,0 +1,42 @@
/*jshint node:true */
'use strict';
var bufferEq = require('./index');
var assert = require('assert');
describe('buffer-equal-constant-time', function() {
var a = new Buffer('asdfasdf123456');
var b = new Buffer('asdfasdf123456');
var c = new Buffer('asdfasdf');
describe('bufferEq', function() {
it('says a == b', function() {
assert.strictEqual(bufferEq(a, b), true);
});
it('says a != c', function() {
assert.strictEqual(bufferEq(a, c), false);
});
});
describe('install/restore', function() {
before(function() {
bufferEq.install();
});
after(function() {
bufferEq.restore();
});
it('installed an .equal method', function() {
var SlowBuffer = require('buffer').SlowBuffer;
assert.ok(Buffer.prototype.equal);
assert.ok(SlowBuffer.prototype.equal);
});
it('infected existing Buffers', function() {
assert.strictEqual(a.equal(b), true);
assert.strictEqual(a.equal(c), false);
});
});
});

1
node_modules/ecdsa-sig-formatter/CODEOWNERS generated vendored Normal file
View File

@ -0,0 +1 @@
* @omsmith

201
node_modules/ecdsa-sig-formatter/LICENSE generated vendored Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2015 D2L Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

65
node_modules/ecdsa-sig-formatter/README.md generated vendored Normal file
View File

@ -0,0 +1,65 @@
# ecdsa-sig-formatter
[![Build Status](https://travis-ci.org/Brightspace/node-ecdsa-sig-formatter.svg?branch=master)](https://travis-ci.org/Brightspace/node-ecdsa-sig-formatter) [![Coverage Status](https://coveralls.io/repos/Brightspace/node-ecdsa-sig-formatter/badge.svg)](https://coveralls.io/r/Brightspace/node-ecdsa-sig-formatter)
Translate between JOSE and ASN.1/DER encodings for ECDSA signatures
## Install
```sh
npm install ecdsa-sig-formatter --save
```
## Usage
```js
var format = require('ecdsa-sig-formatter');
var derSignature = '..'; // asn.1/DER encoded ecdsa signature
var joseSignature = format.derToJose(derSignature);
```
### API
---
#### `.derToJose(Buffer|String signature, String alg)` -> `String`
Convert the ASN.1/DER encoded signature to a JOSE-style concatenated signature.
Returns a _base64 url_ encoded `String`.
* If _signature_ is a `String`, it should be _base64_ encoded
* _alg_ must be one of _ES256_, _ES384_ or _ES512_
---
#### `.joseToDer(Buffer|String signature, String alg)` -> `Buffer`
Convert the JOSE-style concatenated signature to an ASN.1/DER encoded
signature. Returns a `Buffer`
* If _signature_ is a `String`, it should be _base64 url_ encoded
* _alg_ must be one of _ES256_, _ES384_ or _ES512_
## Contributing
1. **Fork** the repository. Committing directly against this repository is
highly discouraged.
2. Make your modifications in a branch, updating and writing new unit tests
as necessary in the `spec` directory.
3. Ensure that all tests pass with `npm test`
4. `rebase` your changes against master. *Do not merge*.
5. Submit a pull request to this repository. Wait for tests to run and someone
to chime in.
### Code Style
This repository is configured with [EditorConfig][EditorConfig] and
[ESLint][ESLint] rules.
[EditorConfig]: http://editorconfig.org/
[ESLint]: http://eslint.org

46
node_modules/ecdsa-sig-formatter/package.json generated vendored Normal file
View File

@ -0,0 +1,46 @@
{
"name": "ecdsa-sig-formatter",
"version": "1.0.11",
"description": "Translate ECDSA signatures between ASN.1/DER and JOSE-style concatenation",
"main": "src/ecdsa-sig-formatter.js",
"scripts": {
"check-style": "eslint .",
"pretest": "npm run check-style",
"test": "istanbul cover --root src _mocha -- spec",
"report-cov": "cat ./coverage/lcov.info | coveralls"
},
"typings": "./src/ecdsa-sig-formatter.d.ts",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/Brightspace/node-ecdsa-sig-formatter.git"
},
"keywords": [
"ecdsa",
"der",
"asn.1",
"jwt",
"jwa",
"jsonwebtoken",
"jose"
],
"author": "D2L Corporation",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/Brightspace/node-ecdsa-sig-formatter/issues"
},
"homepage": "https://github.com/Brightspace/node-ecdsa-sig-formatter#readme",
"dependencies": {
"safe-buffer": "^5.0.1"
},
"devDependencies": {
"bench": "^0.3.6",
"chai": "^3.5.0",
"coveralls": "^2.11.9",
"eslint": "^2.12.0",
"eslint-config-brightspace": "^0.2.1",
"istanbul": "^0.4.3",
"jwk-to-pem": "^1.2.5",
"mocha": "^2.5.3",
"native-crypto": "^1.7.0"
}
}

View File

@ -0,0 +1,17 @@
/// <reference types="node" />
declare module "ecdsa-sig-formatter" {
/**
* Convert the ASN.1/DER encoded signature to a JOSE-style concatenated signature. Returns a base64 url encoded String.
* If signature is a String, it should be base64 encoded
* alg must be one of ES256, ES384 or ES512
*/
export function derToJose(signature: Buffer | string, alg: string): string;
/**
* Convert the JOSE-style concatenated signature to an ASN.1/DER encoded signature. Returns a Buffer
* If signature is a String, it should be base64 url encoded
* alg must be one of ES256, ES384 or ES512
*/
export function joseToDer(signature: Buffer | string, alg: string): Buffer
}

View File

@ -0,0 +1,187 @@
'use strict';
var Buffer = require('safe-buffer').Buffer;
var getParamBytesForAlg = require('./param-bytes-for-alg');
var MAX_OCTET = 0x80,
CLASS_UNIVERSAL = 0,
PRIMITIVE_BIT = 0x20,
TAG_SEQ = 0x10,
TAG_INT = 0x02,
ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6),
ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6);
function base64Url(base64) {
return base64
.replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_');
}
function signatureAsBuffer(signature) {
if (Buffer.isBuffer(signature)) {
return signature;
} else if ('string' === typeof signature) {
return Buffer.from(signature, 'base64');
}
throw new TypeError('ECDSA signature must be a Base64 string or a Buffer');
}
function derToJose(signature, alg) {
signature = signatureAsBuffer(signature);
var paramBytes = getParamBytesForAlg(alg);
// the DER encoded param should at most be the param size, plus a padding
// zero, since due to being a signed integer
var maxEncodedParamLength = paramBytes + 1;
var inputLength = signature.length;
var offset = 0;
if (signature[offset++] !== ENCODED_TAG_SEQ) {
throw new Error('Could not find expected "seq"');
}
var seqLength = signature[offset++];
if (seqLength === (MAX_OCTET | 1)) {
seqLength = signature[offset++];
}
if (inputLength - offset < seqLength) {
throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining');
}
if (signature[offset++] !== ENCODED_TAG_INT) {
throw new Error('Could not find expected "int" for "r"');
}
var rLength = signature[offset++];
if (inputLength - offset - 2 < rLength) {
throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available');
}
if (maxEncodedParamLength < rLength) {
throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable');
}
var rOffset = offset;
offset += rLength;
if (signature[offset++] !== ENCODED_TAG_INT) {
throw new Error('Could not find expected "int" for "s"');
}
var sLength = signature[offset++];
if (inputLength - offset !== sLength) {
throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"');
}
if (maxEncodedParamLength < sLength) {
throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable');
}
var sOffset = offset;
offset += sLength;
if (offset !== inputLength) {
throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain');
}
var rPadding = paramBytes - rLength,
sPadding = paramBytes - sLength;
var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength);
for (offset = 0; offset < rPadding; ++offset) {
dst[offset] = 0;
}
signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength);
offset = paramBytes;
for (var o = offset; offset < o + sPadding; ++offset) {
dst[offset] = 0;
}
signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength);
dst = dst.toString('base64');
dst = base64Url(dst);
return dst;
}
function countPadding(buf, start, stop) {
var padding = 0;
while (start + padding < stop && buf[start + padding] === 0) {
++padding;
}
var needsSign = buf[start + padding] >= MAX_OCTET;
if (needsSign) {
--padding;
}
return padding;
}
function joseToDer(signature, alg) {
signature = signatureAsBuffer(signature);
var paramBytes = getParamBytesForAlg(alg);
var signatureBytes = signature.length;
if (signatureBytes !== paramBytes * 2) {
throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"');
}
var rPadding = countPadding(signature, 0, paramBytes);
var sPadding = countPadding(signature, paramBytes, signature.length);
var rLength = paramBytes - rPadding;
var sLength = paramBytes - sPadding;
var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength;
var shortLength = rsBytes < MAX_OCTET;
var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes);
var offset = 0;
dst[offset++] = ENCODED_TAG_SEQ;
if (shortLength) {
// Bit 8 has value "0"
// bits 7-1 give the length.
dst[offset++] = rsBytes;
} else {
// Bit 8 of first octet has value "1"
// bits 7-1 give the number of additional length octets.
dst[offset++] = MAX_OCTET | 1;
// length, base 256
dst[offset++] = rsBytes & 0xff;
}
dst[offset++] = ENCODED_TAG_INT;
dst[offset++] = rLength;
if (rPadding < 0) {
dst[offset++] = 0;
offset += signature.copy(dst, offset, 0, paramBytes);
} else {
offset += signature.copy(dst, offset, rPadding, paramBytes);
}
dst[offset++] = ENCODED_TAG_INT;
dst[offset++] = sLength;
if (sPadding < 0) {
dst[offset++] = 0;
signature.copy(dst, offset, paramBytes);
} else {
signature.copy(dst, offset, paramBytes + sPadding);
}
return dst;
}
module.exports = {
derToJose: derToJose,
joseToDer: joseToDer
};

View File

@ -0,0 +1,23 @@
'use strict';
function getParamSize(keySize) {
var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1);
return result;
}
var paramBytesForAlg = {
ES256: getParamSize(256),
ES384: getParamSize(384),
ES512: getParamSize(521)
};
function getParamBytesForAlg(alg) {
var paramBytes = paramBytesForAlg[alg];
if (paramBytes) {
return paramBytes;
}
throw new Error('Unknown algorithm "' + alg + '"');
}
module.exports = getParamBytesForAlg;

21
node_modules/jsonwebtoken/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015 Auth0, Inc. <support@auth0.com> (http://auth0.com)
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.

396
node_modules/jsonwebtoken/README.md generated vendored Normal file
View File

@ -0,0 +1,396 @@
# jsonwebtoken
| **Build** | **Dependency** |
|-----------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------|
| [![Build Status](https://secure.travis-ci.org/auth0/node-jsonwebtoken.svg?branch=master)](http://travis-ci.org/auth0/node-jsonwebtoken) | [![Dependency Status](https://david-dm.org/auth0/node-jsonwebtoken.svg)](https://david-dm.org/auth0/node-jsonwebtoken) |
An implementation of [JSON Web Tokens](https://tools.ietf.org/html/rfc7519).
This was developed against `draft-ietf-oauth-json-web-token-08`. It makes use of [node-jws](https://github.com/brianloveswords/node-jws)
# Install
```bash
$ npm install jsonwebtoken
```
# Migration notes
* [From v8 to v9](https://github.com/auth0/node-jsonwebtoken/wiki/Migration-Notes:-v8-to-v9)
* [From v7 to v8](https://github.com/auth0/node-jsonwebtoken/wiki/Migration-Notes:-v7-to-v8)
# Usage
### jwt.sign(payload, secretOrPrivateKey, [options, callback])
(Asynchronous) If a callback is supplied, the callback is called with the `err` or the JWT.
(Synchronous) Returns the JsonWebToken as string
`payload` could be an object literal, buffer or string representing valid JSON.
> **Please _note_ that** `exp` or any other claim is only set if the payload is an object literal. Buffer or string payloads are not checked for JSON validity.
> If `payload` is not a buffer or a string, it will be coerced into a string using `JSON.stringify`.
`secretOrPrivateKey` is a string (utf-8 encoded), buffer, object, or KeyObject containing either the secret for HMAC algorithms or the PEM
encoded private key for RSA and ECDSA. In case of a private key with passphrase an object `{ key, passphrase }` can be used (based on [crypto documentation](https://nodejs.org/api/crypto.html#crypto_sign_sign_private_key_output_format)), in this case be sure you pass the `algorithm` option.
When signing with RSA algorithms the minimum modulus length is 2048 except when the allowInsecureKeySizes option is set to true. Private keys below this size will be rejected with an error.
`options`:
* `algorithm` (default: `HS256`)
* `expiresIn`: expressed in seconds or a string describing a time span [vercel/ms](https://github.com/vercel/ms).
> Eg: `60`, `"2 days"`, `"10h"`, `"7d"`. A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default (`"120"` is equal to `"120ms"`).
* `notBefore`: expressed in seconds or a string describing a time span [vercel/ms](https://github.com/vercel/ms).
> Eg: `60`, `"2 days"`, `"10h"`, `"7d"`. A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default (`"120"` is equal to `"120ms"`).
* `audience`
* `issuer`
* `jwtid`
* `subject`
* `noTimestamp`
* `header`
* `keyid`
* `mutatePayload`: if true, the sign function will modify the payload object directly. This is useful if you need a raw reference to the payload after claims have been applied to it but before it has been encoded into a token.
* `allowInsecureKeySizes`: if true allows private keys with a modulus below 2048 to be used for RSA
* `allowInvalidAsymmetricKeyTypes`: if true, allows asymmetric keys which do not match the specified algorithm. This option is intended only for backwards compatability and should be avoided.
> There are no default values for `expiresIn`, `notBefore`, `audience`, `subject`, `issuer`. These claims can also be provided in the payload directly with `exp`, `nbf`, `aud`, `sub` and `iss` respectively, but you **_can't_** include in both places.
Remember that `exp`, `nbf` and `iat` are **NumericDate**, see related [Token Expiration (exp claim)](#token-expiration-exp-claim)
The header can be customized via the `options.header` object.
Generated jwts will include an `iat` (issued at) claim by default unless `noTimestamp` is specified. If `iat` is inserted in the payload, it will be used instead of the real timestamp for calculating other things like `exp` given a timespan in `options.expiresIn`.
Synchronous Sign with default (HMAC SHA256)
```js
var jwt = require('jsonwebtoken');
var token = jwt.sign({ foo: 'bar' }, 'shhhhh');
```
Synchronous Sign with RSA SHA256
```js
// sign with RSA SHA256
var privateKey = fs.readFileSync('private.key');
var token = jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256' });
```
Sign asynchronously
```js
jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256' }, function(err, token) {
console.log(token);
});
```
Backdate a jwt 30 seconds
```js
var older_token = jwt.sign({ foo: 'bar', iat: Math.floor(Date.now() / 1000) - 30 }, 'shhhhh');
```
#### Token Expiration (exp claim)
The standard for JWT defines an `exp` claim for expiration. The expiration is represented as a **NumericDate**:
> A JSON numeric value representing the number of seconds from 1970-01-01T00:00:00Z UTC until the specified UTC date/time, ignoring leap seconds. This is equivalent to the IEEE Std 1003.1, 2013 Edition [POSIX.1] definition "Seconds Since the Epoch", in which each day is accounted for by exactly 86400 seconds, other than that non-integer values can be represented. See RFC 3339 [RFC3339] for details regarding date/times in general and UTC in particular.
This means that the `exp` field should contain the number of seconds since the epoch.
Signing a token with 1 hour of expiration:
```javascript
jwt.sign({
exp: Math.floor(Date.now() / 1000) + (60 * 60),
data: 'foobar'
}, 'secret');
```
Another way to generate a token like this with this library is:
```javascript
jwt.sign({
data: 'foobar'
}, 'secret', { expiresIn: 60 * 60 });
//or even better:
jwt.sign({
data: 'foobar'
}, 'secret', { expiresIn: '1h' });
```
### jwt.verify(token, secretOrPublicKey, [options, callback])
(Asynchronous) If a callback is supplied, function acts asynchronously. The callback is called with the decoded payload if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will be called with the error.
(Synchronous) If a callback is not supplied, function acts synchronously. Returns the payload decoded if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will throw the error.
> __Warning:__ When the token comes from an untrusted source (e.g. user input or external requests), the returned decoded payload should be treated like any other user input; please make sure to sanitize and only work with properties that are expected
`token` is the JsonWebToken string
`secretOrPublicKey` is a string (utf-8 encoded), buffer, or KeyObject containing either the secret for HMAC algorithms, or the PEM
encoded public key for RSA and ECDSA.
If `jwt.verify` is called asynchronous, `secretOrPublicKey` can be a function that should fetch the secret or public key. See below for a detailed example
As mentioned in [this comment](https://github.com/auth0/node-jsonwebtoken/issues/208#issuecomment-231861138), there are other libraries that expect base64 encoded secrets (random bytes encoded using base64), if that is your case you can pass `Buffer.from(secret, 'base64')`, by doing this the secret will be decoded using base64 and the token verification will use the original random bytes.
`options`
* `algorithms`: List of strings with the names of the allowed algorithms. For instance, `["HS256", "HS384"]`.
> If not specified a defaults will be used based on the type of key provided
> * secret - ['HS256', 'HS384', 'HS512']
> * rsa - ['RS256', 'RS384', 'RS512']
> * ec - ['ES256', 'ES384', 'ES512']
> * default - ['RS256', 'RS384', 'RS512']
* `audience`: if you want to check audience (`aud`), provide a value here. The audience can be checked against a string, a regular expression or a list of strings and/or regular expressions.
> Eg: `"urn:foo"`, `/urn:f[o]{2}/`, `[/urn:f[o]{2}/, "urn:bar"]`
* `complete`: return an object with the decoded `{ payload, header, signature }` instead of only the usual content of the payload.
* `issuer` (optional): string or array of strings of valid values for the `iss` field.
* `jwtid` (optional): if you want to check JWT ID (`jti`), provide a string value here.
* `ignoreExpiration`: if `true` do not validate the expiration of the token.
* `ignoreNotBefore`...
* `subject`: if you want to check subject (`sub`), provide a value here
* `clockTolerance`: number of seconds to tolerate when checking the `nbf` and `exp` claims, to deal with small clock differences among different servers
* `maxAge`: the maximum allowed age for tokens to still be valid. It is expressed in seconds or a string describing a time span [vercel/ms](https://github.com/vercel/ms).
> Eg: `1000`, `"2 days"`, `"10h"`, `"7d"`. A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default (`"120"` is equal to `"120ms"`).
* `clockTimestamp`: the time in seconds that should be used as the current time for all necessary comparisons.
* `nonce`: if you want to check `nonce` claim, provide a string value here. It is used on Open ID for the ID Tokens. ([Open ID implementation notes](https://openid.net/specs/openid-connect-core-1_0.html#NonceNotes))
* `allowInvalidAsymmetricKeyTypes`: if true, allows asymmetric keys which do not match the specified algorithm. This option is intended only for backwards compatability and should be avoided.
```js
// verify a token symmetric - synchronous
var decoded = jwt.verify(token, 'shhhhh');
console.log(decoded.foo) // bar
// verify a token symmetric
jwt.verify(token, 'shhhhh', function(err, decoded) {
console.log(decoded.foo) // bar
});
// invalid token - synchronous
try {
var decoded = jwt.verify(token, 'wrong-secret');
} catch(err) {
// err
}
// invalid token
jwt.verify(token, 'wrong-secret', function(err, decoded) {
// err
// decoded undefined
});
// verify a token asymmetric
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, function(err, decoded) {
console.log(decoded.foo) // bar
});
// verify audience
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { audience: 'urn:foo' }, function(err, decoded) {
// if audience mismatch, err == invalid audience
});
// verify issuer
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer' }, function(err, decoded) {
// if issuer mismatch, err == invalid issuer
});
// verify jwt id
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer', jwtid: 'jwtid' }, function(err, decoded) {
// if jwt id mismatch, err == invalid jwt id
});
// verify subject
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer', jwtid: 'jwtid', subject: 'subject' }, function(err, decoded) {
// if subject mismatch, err == invalid subject
});
// alg mismatch
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { algorithms: ['RS256'] }, function (err, payload) {
// if token alg != RS256, err == invalid signature
});
// Verify using getKey callback
// Example uses https://github.com/auth0/node-jwks-rsa as a way to fetch the keys.
var jwksClient = require('jwks-rsa');
var client = jwksClient({
jwksUri: 'https://sandrino.auth0.com/.well-known/jwks.json'
});
function getKey(header, callback){
client.getSigningKey(header.kid, function(err, key) {
var signingKey = key.publicKey || key.rsaPublicKey;
callback(null, signingKey);
});
}
jwt.verify(token, getKey, options, function(err, decoded) {
console.log(decoded.foo) // bar
});
```
<details>
<summary><em></em>Need to peek into a JWT without verifying it? (Click to expand)</summary>
### jwt.decode(token [, options])
(Synchronous) Returns the decoded payload without verifying if the signature is valid.
> __Warning:__ This will __not__ verify whether the signature is valid. You should __not__ use this for untrusted messages. You most likely want to use `jwt.verify` instead.
> __Warning:__ When the token comes from an untrusted source (e.g. user input or external request), the returned decoded payload should be treated like any other user input; please make sure to sanitize and only work with properties that are expected
`token` is the JsonWebToken string
`options`:
* `json`: force JSON.parse on the payload even if the header doesn't contain `"typ":"JWT"`.
* `complete`: return an object with the decoded payload and header.
Example
```js
// get the decoded payload ignoring signature, no secretOrPrivateKey needed
var decoded = jwt.decode(token);
// get the decoded payload and header
var decoded = jwt.decode(token, {complete: true});
console.log(decoded.header);
console.log(decoded.payload)
```
</details>
## Errors & Codes
Possible thrown errors during verification.
Error is the first argument of the verification callback.
### TokenExpiredError
Thrown error if the token is expired.
Error object:
* name: 'TokenExpiredError'
* message: 'jwt expired'
* expiredAt: [ExpDate]
```js
jwt.verify(token, 'shhhhh', function(err, decoded) {
if (err) {
/*
err = {
name: 'TokenExpiredError',
message: 'jwt expired',
expiredAt: 1408621000
}
*/
}
});
```
### JsonWebTokenError
Error object:
* name: 'JsonWebTokenError'
* message:
* 'invalid token' - the header or payload could not be parsed
* 'jwt malformed' - the token does not have three components (delimited by a `.`)
* 'jwt signature is required'
* 'invalid signature'
* 'jwt audience invalid. expected: [OPTIONS AUDIENCE]'
* 'jwt issuer invalid. expected: [OPTIONS ISSUER]'
* 'jwt id invalid. expected: [OPTIONS JWT ID]'
* 'jwt subject invalid. expected: [OPTIONS SUBJECT]'
```js
jwt.verify(token, 'shhhhh', function(err, decoded) {
if (err) {
/*
err = {
name: 'JsonWebTokenError',
message: 'jwt malformed'
}
*/
}
});
```
### NotBeforeError
Thrown if current time is before the nbf claim.
Error object:
* name: 'NotBeforeError'
* message: 'jwt not active'
* date: 2018-10-04T16:10:44.000Z
```js
jwt.verify(token, 'shhhhh', function(err, decoded) {
if (err) {
/*
err = {
name: 'NotBeforeError',
message: 'jwt not active',
date: 2018-10-04T16:10:44.000Z
}
*/
}
});
```
## Algorithms supported
Array of supported algorithms. The following algorithms are currently supported.
| alg Parameter Value | Digital Signature or MAC Algorithm |
|---------------------|------------------------------------------------------------------------|
| HS256 | HMAC using SHA-256 hash algorithm |
| HS384 | HMAC using SHA-384 hash algorithm |
| HS512 | HMAC using SHA-512 hash algorithm |
| RS256 | RSASSA-PKCS1-v1_5 using SHA-256 hash algorithm |
| RS384 | RSASSA-PKCS1-v1_5 using SHA-384 hash algorithm |
| RS512 | RSASSA-PKCS1-v1_5 using SHA-512 hash algorithm |
| PS256 | RSASSA-PSS using SHA-256 hash algorithm (only node ^6.12.0 OR >=8.0.0) |
| PS384 | RSASSA-PSS using SHA-384 hash algorithm (only node ^6.12.0 OR >=8.0.0) |
| PS512 | RSASSA-PSS using SHA-512 hash algorithm (only node ^6.12.0 OR >=8.0.0) |
| ES256 | ECDSA using P-256 curve and SHA-256 hash algorithm |
| ES384 | ECDSA using P-384 curve and SHA-384 hash algorithm |
| ES512 | ECDSA using P-521 curve and SHA-512 hash algorithm |
| none | No digital signature or MAC value included |
## Refreshing JWTs
First of all, we recommend you to think carefully if auto-refreshing a JWT will not introduce any vulnerability in your system.
We are not comfortable including this as part of the library, however, you can take a look at [this example](https://gist.github.com/ziluvatar/a3feb505c4c0ec37059054537b38fc48) to show how this could be accomplished.
Apart from that example there are [an issue](https://github.com/auth0/node-jsonwebtoken/issues/122) and [a pull request](https://github.com/auth0/node-jsonwebtoken/pull/172) to get more knowledge about this topic.
# TODO
* X.509 certificate chain is not checked
## Issue Reporting
If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://auth0.com/whitehat) details the procedure for disclosing security issues.
## Author
[Auth0](https://auth0.com)
## License
This project is licensed under the MIT license. See the [LICENSE](LICENSE) file for more info.

30
node_modules/jsonwebtoken/decode.js generated vendored Normal file
View File

@ -0,0 +1,30 @@
var jws = require('jws');
module.exports = function (jwt, options) {
options = options || {};
var decoded = jws.decode(jwt, options);
if (!decoded) { return null; }
var payload = decoded.payload;
//try parse the payload
if(typeof payload === 'string') {
try {
var obj = JSON.parse(payload);
if(obj !== null && typeof obj === 'object') {
payload = obj;
}
} catch (e) { }
}
//return header if `complete` option is enabled. header includes claims
//such as `kid` and `alg` used to select the key within a JWKS needed to
//verify the signature
if (options.complete === true) {
return {
header: decoded.header,
payload: payload,
signature: decoded.signature
};
}
return payload;
};

8
node_modules/jsonwebtoken/index.js generated vendored Normal file
View File

@ -0,0 +1,8 @@
module.exports = {
decode: require('./decode'),
verify: require('./verify'),
sign: require('./sign'),
JsonWebTokenError: require('./lib/JsonWebTokenError'),
NotBeforeError: require('./lib/NotBeforeError'),
TokenExpiredError: require('./lib/TokenExpiredError'),
};

14
node_modules/jsonwebtoken/lib/JsonWebTokenError.js generated vendored Normal file
View File

@ -0,0 +1,14 @@
var JsonWebTokenError = function (message, error) {
Error.call(this, message);
if(Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
this.name = 'JsonWebTokenError';
this.message = message;
if (error) this.inner = error;
};
JsonWebTokenError.prototype = Object.create(Error.prototype);
JsonWebTokenError.prototype.constructor = JsonWebTokenError;
module.exports = JsonWebTokenError;

13
node_modules/jsonwebtoken/lib/NotBeforeError.js generated vendored Normal file
View File

@ -0,0 +1,13 @@
var JsonWebTokenError = require('./JsonWebTokenError');
var NotBeforeError = function (message, date) {
JsonWebTokenError.call(this, message);
this.name = 'NotBeforeError';
this.date = date;
};
NotBeforeError.prototype = Object.create(JsonWebTokenError.prototype);
NotBeforeError.prototype.constructor = NotBeforeError;
module.exports = NotBeforeError;

13
node_modules/jsonwebtoken/lib/TokenExpiredError.js generated vendored Normal file
View File

@ -0,0 +1,13 @@
var JsonWebTokenError = require('./JsonWebTokenError');
var TokenExpiredError = function (message, expiredAt) {
JsonWebTokenError.call(this, message);
this.name = 'TokenExpiredError';
this.expiredAt = expiredAt;
};
TokenExpiredError.prototype = Object.create(JsonWebTokenError.prototype);
TokenExpiredError.prototype.constructor = TokenExpiredError;
module.exports = TokenExpiredError;

View File

@ -0,0 +1,3 @@
const semver = require('semver');
module.exports = semver.satisfies(process.version, '>=15.7.0');

3
node_modules/jsonwebtoken/lib/psSupported.js generated vendored Normal file
View File

@ -0,0 +1,3 @@
var semver = require('semver');
module.exports = semver.satisfies(process.version, '^6.12.0 || >=8.0.0');

View File

@ -0,0 +1,3 @@
const semver = require('semver');
module.exports = semver.satisfies(process.version, '>=16.9.0');

18
node_modules/jsonwebtoken/lib/timespan.js generated vendored Normal file
View File

@ -0,0 +1,18 @@
var ms = require('ms');
module.exports = function (time, iat) {
var timestamp = iat || Math.floor(Date.now() / 1000);
if (typeof time === 'string') {
var milliseconds = ms(time);
if (typeof milliseconds === 'undefined') {
return;
}
return Math.floor(timestamp + milliseconds / 1000);
} else if (typeof time === 'number') {
return timestamp + time;
} else {
return;
}
};

66
node_modules/jsonwebtoken/lib/validateAsymmetricKey.js generated vendored Normal file
View File

@ -0,0 +1,66 @@
const ASYMMETRIC_KEY_DETAILS_SUPPORTED = require('./asymmetricKeyDetailsSupported');
const RSA_PSS_KEY_DETAILS_SUPPORTED = require('./rsaPssKeyDetailsSupported');
const allowedAlgorithmsForKeys = {
'ec': ['ES256', 'ES384', 'ES512'],
'rsa': ['RS256', 'PS256', 'RS384', 'PS384', 'RS512', 'PS512'],
'rsa-pss': ['PS256', 'PS384', 'PS512']
};
const allowedCurves = {
ES256: 'prime256v1',
ES384: 'secp384r1',
ES512: 'secp521r1',
};
module.exports = function(algorithm, key) {
if (!algorithm || !key) return;
const keyType = key.asymmetricKeyType;
if (!keyType) return;
const allowedAlgorithms = allowedAlgorithmsForKeys[keyType];
if (!allowedAlgorithms) {
throw new Error(`Unknown key type "${keyType}".`);
}
if (!allowedAlgorithms.includes(algorithm)) {
throw new Error(`"alg" parameter for "${keyType}" key type must be one of: ${allowedAlgorithms.join(', ')}.`)
}
/*
* Ignore the next block from test coverage because it gets executed
* conditionally depending on the Node version. Not ignoring it would
* prevent us from reaching the target % of coverage for versions of
* Node under 15.7.0.
*/
/* istanbul ignore next */
if (ASYMMETRIC_KEY_DETAILS_SUPPORTED) {
switch (keyType) {
case 'ec':
const keyCurve = key.asymmetricKeyDetails.namedCurve;
const allowedCurve = allowedCurves[algorithm];
if (keyCurve !== allowedCurve) {
throw new Error(`"alg" parameter "${algorithm}" requires curve "${allowedCurve}".`);
}
break;
case 'rsa-pss':
if (RSA_PSS_KEY_DETAILS_SUPPORTED) {
const length = parseInt(algorithm.slice(-3), 10);
const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = key.asymmetricKeyDetails;
if (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm) {
throw new Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${algorithm}.`);
}
if (saltLength !== undefined && saltLength > length >> 3) {
throw new Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${algorithm}.`)
}
}
break;
}
}
}

162
node_modules/jsonwebtoken/node_modules/ms/index.js generated vendored Normal file
View File

@ -0,0 +1,162 @@
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function (val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'weeks':
case 'week':
case 'w':
return n * w;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + 'd';
}
if (msAbs >= h) {
return Math.round(ms / h) + 'h';
}
if (msAbs >= m) {
return Math.round(ms / m) + 'm';
}
if (msAbs >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, 'day');
}
if (msAbs >= h) {
return plural(ms, msAbs, h, 'hour');
}
if (msAbs >= m) {
return plural(ms, msAbs, m, 'minute');
}
if (msAbs >= s) {
return plural(ms, msAbs, s, 'second');
}
return ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
}

21
node_modules/jsonwebtoken/node_modules/ms/license.md generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2020 Vercel, Inc.
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.

38
node_modules/jsonwebtoken/node_modules/ms/package.json generated vendored Normal file
View File

@ -0,0 +1,38 @@
{
"name": "ms",
"version": "2.1.3",
"description": "Tiny millisecond conversion utility",
"repository": "vercel/ms",
"main": "./index",
"files": [
"index.js"
],
"scripts": {
"precommit": "lint-staged",
"lint": "eslint lib/* bin/*",
"test": "mocha tests.js"
},
"eslintConfig": {
"extends": "eslint:recommended",
"env": {
"node": true,
"es6": true
}
},
"lint-staged": {
"*.js": [
"npm run lint",
"prettier --single-quote --write",
"git add"
]
},
"license": "MIT",
"devDependencies": {
"eslint": "4.18.2",
"expect.js": "0.3.1",
"husky": "0.14.3",
"lint-staged": "5.0.0",
"mocha": "4.0.1",
"prettier": "2.0.5"
}
}

59
node_modules/jsonwebtoken/node_modules/ms/readme.md generated vendored Normal file
View File

@ -0,0 +1,59 @@
# ms
![CI](https://github.com/vercel/ms/workflows/CI/badge.svg)
Use this package to easily convert various time formats to milliseconds.
## Examples
```js
ms('2 days') // 172800000
ms('1d') // 86400000
ms('10h') // 36000000
ms('2.5 hrs') // 9000000
ms('2h') // 7200000
ms('1m') // 60000
ms('5s') // 5000
ms('1y') // 31557600000
ms('100') // 100
ms('-3 days') // -259200000
ms('-1h') // -3600000
ms('-200') // -200
```
### Convert from Milliseconds
```js
ms(60000) // "1m"
ms(2 * 60000) // "2m"
ms(-3 * 60000) // "-3m"
ms(ms('10 hours')) // "10h"
```
### Time Format Written-Out
```js
ms(60000, { long: true }) // "1 minute"
ms(2 * 60000, { long: true }) // "2 minutes"
ms(-3 * 60000, { long: true }) // "-3 minutes"
ms(ms('10 hours'), { long: true }) // "10 hours"
```
## Features
- Works both in [Node.js](https://nodejs.org) and in the browser
- If a number is supplied to `ms`, a string with a unit is returned
- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`)
- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned
## Related Packages
- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time.
## Caught a Bug?
1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device
2. Link the package to the global module directory: `npm link`
3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms!
As always, you can run the tests using: `npm test`

70
node_modules/jsonwebtoken/package.json generated vendored Normal file
View File

@ -0,0 +1,70 @@
{
"name": "jsonwebtoken",
"version": "9.0.3",
"description": "JSON Web Token implementation (symmetric and asymmetric)",
"main": "index.js",
"nyc": {
"check-coverage": true,
"lines": 95,
"statements": 95,
"functions": 100,
"branches": 95,
"exclude": [
"./test/**"
],
"reporter": [
"json",
"lcov",
"text-summary"
]
},
"scripts": {
"lint": "eslint .",
"coverage": "nyc mocha --use_strict",
"test": "mocha"
},
"repository": {
"type": "git",
"url": "https://github.com/auth0/node-jsonwebtoken"
},
"keywords": [
"jwt"
],
"author": "auth0",
"license": "MIT",
"bugs": {
"url": "https://github.com/auth0/node-jsonwebtoken/issues"
},
"dependencies": {
"jws": "^4.0.1",
"lodash.includes": "^4.3.0",
"lodash.isboolean": "^3.0.3",
"lodash.isinteger": "^4.0.4",
"lodash.isnumber": "^3.0.3",
"lodash.isplainobject": "^4.0.6",
"lodash.isstring": "^4.0.1",
"lodash.once": "^4.0.0",
"ms": "^2.1.1",
"semver": "^7.5.4"
},
"devDependencies": {
"atob": "^2.1.2",
"chai": "^4.1.2",
"conventional-changelog": "~1.1.0",
"eslint": "^4.19.1",
"mocha": "^5.2.0",
"nsp": "^2.6.2",
"nyc": "^11.9.0",
"sinon": "^6.0.0"
},
"engines": {
"npm": ">=6",
"node": ">=12"
},
"files": [
"lib",
"decode.js",
"sign.js",
"verify.js"
]
}

253
node_modules/jsonwebtoken/sign.js generated vendored Normal file
View File

@ -0,0 +1,253 @@
const timespan = require('./lib/timespan');
const PS_SUPPORTED = require('./lib/psSupported');
const validateAsymmetricKey = require('./lib/validateAsymmetricKey');
const jws = require('jws');
const includes = require('lodash.includes');
const isBoolean = require('lodash.isboolean');
const isInteger = require('lodash.isinteger');
const isNumber = require('lodash.isnumber');
const isPlainObject = require('lodash.isplainobject');
const isString = require('lodash.isstring');
const once = require('lodash.once');
const { KeyObject, createSecretKey, createPrivateKey } = require('crypto')
const SUPPORTED_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'HS256', 'HS384', 'HS512', 'none'];
if (PS_SUPPORTED) {
SUPPORTED_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512');
}
const sign_options_schema = {
expiresIn: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"expiresIn" should be a number of seconds or string representing a timespan' },
notBefore: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"notBefore" should be a number of seconds or string representing a timespan' },
audience: { isValid: function(value) { return isString(value) || Array.isArray(value); }, message: '"audience" must be a string or array' },
algorithm: { isValid: includes.bind(null, SUPPORTED_ALGS), message: '"algorithm" must be a valid string enum value' },
header: { isValid: isPlainObject, message: '"header" must be an object' },
encoding: { isValid: isString, message: '"encoding" must be a string' },
issuer: { isValid: isString, message: '"issuer" must be a string' },
subject: { isValid: isString, message: '"subject" must be a string' },
jwtid: { isValid: isString, message: '"jwtid" must be a string' },
noTimestamp: { isValid: isBoolean, message: '"noTimestamp" must be a boolean' },
keyid: { isValid: isString, message: '"keyid" must be a string' },
mutatePayload: { isValid: isBoolean, message: '"mutatePayload" must be a boolean' },
allowInsecureKeySizes: { isValid: isBoolean, message: '"allowInsecureKeySizes" must be a boolean'},
allowInvalidAsymmetricKeyTypes: { isValid: isBoolean, message: '"allowInvalidAsymmetricKeyTypes" must be a boolean'}
};
const registered_claims_schema = {
iat: { isValid: isNumber, message: '"iat" should be a number of seconds' },
exp: { isValid: isNumber, message: '"exp" should be a number of seconds' },
nbf: { isValid: isNumber, message: '"nbf" should be a number of seconds' }
};
function validate(schema, allowUnknown, object, parameterName) {
if (!isPlainObject(object)) {
throw new Error('Expected "' + parameterName + '" to be a plain object.');
}
Object.keys(object)
.forEach(function(key) {
const validator = schema[key];
if (!validator) {
if (!allowUnknown) {
throw new Error('"' + key + '" is not allowed in "' + parameterName + '"');
}
return;
}
if (!validator.isValid(object[key])) {
throw new Error(validator.message);
}
});
}
function validateOptions(options) {
return validate(sign_options_schema, false, options, 'options');
}
function validatePayload(payload) {
return validate(registered_claims_schema, true, payload, 'payload');
}
const options_to_payload = {
'audience': 'aud',
'issuer': 'iss',
'subject': 'sub',
'jwtid': 'jti'
};
const options_for_objects = [
'expiresIn',
'notBefore',
'noTimestamp',
'audience',
'issuer',
'subject',
'jwtid',
];
module.exports = function (payload, secretOrPrivateKey, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
} else {
options = options || {};
}
const isObjectPayload = typeof payload === 'object' &&
!Buffer.isBuffer(payload);
const header = Object.assign({
alg: options.algorithm || 'HS256',
typ: isObjectPayload ? 'JWT' : undefined,
kid: options.keyid
}, options.header);
function failure(err) {
if (callback) {
return callback(err);
}
throw err;
}
if (!secretOrPrivateKey && options.algorithm !== 'none') {
return failure(new Error('secretOrPrivateKey must have a value'));
}
if (secretOrPrivateKey != null && !(secretOrPrivateKey instanceof KeyObject)) {
try {
secretOrPrivateKey = createPrivateKey(secretOrPrivateKey)
} catch (_) {
try {
secretOrPrivateKey = createSecretKey(typeof secretOrPrivateKey === 'string' ? Buffer.from(secretOrPrivateKey) : secretOrPrivateKey)
} catch (_) {
return failure(new Error('secretOrPrivateKey is not valid key material'));
}
}
}
if (header.alg.startsWith('HS') && secretOrPrivateKey.type !== 'secret') {
return failure(new Error((`secretOrPrivateKey must be a symmetric key when using ${header.alg}`)))
} else if (/^(?:RS|PS|ES)/.test(header.alg)) {
if (secretOrPrivateKey.type !== 'private') {
return failure(new Error((`secretOrPrivateKey must be an asymmetric key when using ${header.alg}`)))
}
if (!options.allowInsecureKeySizes &&
!header.alg.startsWith('ES') &&
secretOrPrivateKey.asymmetricKeyDetails !== undefined && //KeyObject.asymmetricKeyDetails is supported in Node 15+
secretOrPrivateKey.asymmetricKeyDetails.modulusLength < 2048) {
return failure(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`));
}
}
if (typeof payload === 'undefined') {
return failure(new Error('payload is required'));
} else if (isObjectPayload) {
try {
validatePayload(payload);
}
catch (error) {
return failure(error);
}
if (!options.mutatePayload) {
payload = Object.assign({},payload);
}
} else {
const invalid_options = options_for_objects.filter(function (opt) {
return typeof options[opt] !== 'undefined';
});
if (invalid_options.length > 0) {
return failure(new Error('invalid ' + invalid_options.join(',') + ' option for ' + (typeof payload ) + ' payload'));
}
}
if (typeof payload.exp !== 'undefined' && typeof options.expiresIn !== 'undefined') {
return failure(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.'));
}
if (typeof payload.nbf !== 'undefined' && typeof options.notBefore !== 'undefined') {
return failure(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.'));
}
try {
validateOptions(options);
}
catch (error) {
return failure(error);
}
if (!options.allowInvalidAsymmetricKeyTypes) {
try {
validateAsymmetricKey(header.alg, secretOrPrivateKey);
} catch (error) {
return failure(error);
}
}
const timestamp = payload.iat || Math.floor(Date.now() / 1000);
if (options.noTimestamp) {
delete payload.iat;
} else if (isObjectPayload) {
payload.iat = timestamp;
}
if (typeof options.notBefore !== 'undefined') {
try {
payload.nbf = timespan(options.notBefore, timestamp);
}
catch (err) {
return failure(err);
}
if (typeof payload.nbf === 'undefined') {
return failure(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));
}
}
if (typeof options.expiresIn !== 'undefined' && typeof payload === 'object') {
try {
payload.exp = timespan(options.expiresIn, timestamp);
}
catch (err) {
return failure(err);
}
if (typeof payload.exp === 'undefined') {
return failure(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));
}
}
Object.keys(options_to_payload).forEach(function (key) {
const claim = options_to_payload[key];
if (typeof options[key] !== 'undefined') {
if (typeof payload[claim] !== 'undefined') {
return failure(new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.'));
}
payload[claim] = options[key];
}
});
const encoding = options.encoding || 'utf8';
if (typeof callback === 'function') {
callback = callback && once(callback);
jws.createSign({
header: header,
privateKey: secretOrPrivateKey,
payload: payload,
encoding: encoding
}).once('error', callback)
.once('done', function (signature) {
// TODO: Remove in favor of the modulus length check before signing once node 15+ is the minimum supported version
if(!options.allowInsecureKeySizes && /^(?:RS|PS)/.test(header.alg) && signature.length < 256) {
return callback(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`))
}
callback(null, signature);
});
} else {
let signature = jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding});
// TODO: Remove in favor of the modulus length check before signing once node 15+ is the minimum supported version
if(!options.allowInsecureKeySizes && /^(?:RS|PS)/.test(header.alg) && signature.length < 256) {
throw new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`)
}
return signature
}
};

263
node_modules/jsonwebtoken/verify.js generated vendored Normal file
View File

@ -0,0 +1,263 @@
const JsonWebTokenError = require('./lib/JsonWebTokenError');
const NotBeforeError = require('./lib/NotBeforeError');
const TokenExpiredError = require('./lib/TokenExpiredError');
const decode = require('./decode');
const timespan = require('./lib/timespan');
const validateAsymmetricKey = require('./lib/validateAsymmetricKey');
const PS_SUPPORTED = require('./lib/psSupported');
const jws = require('jws');
const {KeyObject, createSecretKey, createPublicKey} = require("crypto");
const PUB_KEY_ALGS = ['RS256', 'RS384', 'RS512'];
const EC_KEY_ALGS = ['ES256', 'ES384', 'ES512'];
const RSA_KEY_ALGS = ['RS256', 'RS384', 'RS512'];
const HS_ALGS = ['HS256', 'HS384', 'HS512'];
if (PS_SUPPORTED) {
PUB_KEY_ALGS.splice(PUB_KEY_ALGS.length, 0, 'PS256', 'PS384', 'PS512');
RSA_KEY_ALGS.splice(RSA_KEY_ALGS.length, 0, 'PS256', 'PS384', 'PS512');
}
module.exports = function (jwtString, secretOrPublicKey, options, callback) {
if ((typeof options === 'function') && !callback) {
callback = options;
options = {};
}
if (!options) {
options = {};
}
//clone this object since we are going to mutate it.
options = Object.assign({}, options);
let done;
if (callback) {
done = callback;
} else {
done = function(err, data) {
if (err) throw err;
return data;
};
}
if (options.clockTimestamp && typeof options.clockTimestamp !== 'number') {
return done(new JsonWebTokenError('clockTimestamp must be a number'));
}
if (options.nonce !== undefined && (typeof options.nonce !== 'string' || options.nonce.trim() === '')) {
return done(new JsonWebTokenError('nonce must be a non-empty string'));
}
if (options.allowInvalidAsymmetricKeyTypes !== undefined && typeof options.allowInvalidAsymmetricKeyTypes !== 'boolean') {
return done(new JsonWebTokenError('allowInvalidAsymmetricKeyTypes must be a boolean'));
}
const clockTimestamp = options.clockTimestamp || Math.floor(Date.now() / 1000);
if (!jwtString){
return done(new JsonWebTokenError('jwt must be provided'));
}
if (typeof jwtString !== 'string') {
return done(new JsonWebTokenError('jwt must be a string'));
}
const parts = jwtString.split('.');
if (parts.length !== 3){
return done(new JsonWebTokenError('jwt malformed'));
}
let decodedToken;
try {
decodedToken = decode(jwtString, { complete: true });
} catch(err) {
return done(err);
}
if (!decodedToken) {
return done(new JsonWebTokenError('invalid token'));
}
const header = decodedToken.header;
let getSecret;
if(typeof secretOrPublicKey === 'function') {
if(!callback) {
return done(new JsonWebTokenError('verify must be called asynchronous if secret or public key is provided as a callback'));
}
getSecret = secretOrPublicKey;
}
else {
getSecret = function(header, secretCallback) {
return secretCallback(null, secretOrPublicKey);
};
}
return getSecret(header, function(err, secretOrPublicKey) {
if(err) {
return done(new JsonWebTokenError('error in secret or public key callback: ' + err.message));
}
const hasSignature = parts[2].trim() !== '';
if (!hasSignature && secretOrPublicKey){
return done(new JsonWebTokenError('jwt signature is required'));
}
if (hasSignature && !secretOrPublicKey) {
return done(new JsonWebTokenError('secret or public key must be provided'));
}
if (!hasSignature && !options.algorithms) {
return done(new JsonWebTokenError('please specify "none" in "algorithms" to verify unsigned tokens'));
}
if (secretOrPublicKey != null && !(secretOrPublicKey instanceof KeyObject)) {
try {
secretOrPublicKey = createPublicKey(secretOrPublicKey);
} catch (_) {
try {
secretOrPublicKey = createSecretKey(typeof secretOrPublicKey === 'string' ? Buffer.from(secretOrPublicKey) : secretOrPublicKey);
} catch (_) {
return done(new JsonWebTokenError('secretOrPublicKey is not valid key material'))
}
}
}
if (!options.algorithms) {
if (secretOrPublicKey.type === 'secret') {
options.algorithms = HS_ALGS;
} else if (['rsa', 'rsa-pss'].includes(secretOrPublicKey.asymmetricKeyType)) {
options.algorithms = RSA_KEY_ALGS
} else if (secretOrPublicKey.asymmetricKeyType === 'ec') {
options.algorithms = EC_KEY_ALGS
} else {
options.algorithms = PUB_KEY_ALGS
}
}
if (options.algorithms.indexOf(decodedToken.header.alg) === -1) {
return done(new JsonWebTokenError('invalid algorithm'));
}
if (header.alg.startsWith('HS') && secretOrPublicKey.type !== 'secret') {
return done(new JsonWebTokenError((`secretOrPublicKey must be a symmetric key when using ${header.alg}`)))
} else if (/^(?:RS|PS|ES)/.test(header.alg) && secretOrPublicKey.type !== 'public') {
return done(new JsonWebTokenError((`secretOrPublicKey must be an asymmetric key when using ${header.alg}`)))
}
if (!options.allowInvalidAsymmetricKeyTypes) {
try {
validateAsymmetricKey(header.alg, secretOrPublicKey);
} catch (e) {
return done(e);
}
}
let valid;
try {
valid = jws.verify(jwtString, decodedToken.header.alg, secretOrPublicKey);
} catch (e) {
return done(e);
}
if (!valid) {
return done(new JsonWebTokenError('invalid signature'));
}
const payload = decodedToken.payload;
if (typeof payload.nbf !== 'undefined' && !options.ignoreNotBefore) {
if (typeof payload.nbf !== 'number') {
return done(new JsonWebTokenError('invalid nbf value'));
}
if (payload.nbf > clockTimestamp + (options.clockTolerance || 0)) {
return done(new NotBeforeError('jwt not active', new Date(payload.nbf * 1000)));
}
}
if (typeof payload.exp !== 'undefined' && !options.ignoreExpiration) {
if (typeof payload.exp !== 'number') {
return done(new JsonWebTokenError('invalid exp value'));
}
if (clockTimestamp >= payload.exp + (options.clockTolerance || 0)) {
return done(new TokenExpiredError('jwt expired', new Date(payload.exp * 1000)));
}
}
if (options.audience) {
const audiences = Array.isArray(options.audience) ? options.audience : [options.audience];
const target = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
const match = target.some(function (targetAudience) {
return audiences.some(function (audience) {
return audience instanceof RegExp ? audience.test(targetAudience) : audience === targetAudience;
});
});
if (!match) {
return done(new JsonWebTokenError('jwt audience invalid. expected: ' + audiences.join(' or ')));
}
}
if (options.issuer) {
const invalid_issuer =
(typeof options.issuer === 'string' && payload.iss !== options.issuer) ||
(Array.isArray(options.issuer) && options.issuer.indexOf(payload.iss) === -1);
if (invalid_issuer) {
return done(new JsonWebTokenError('jwt issuer invalid. expected: ' + options.issuer));
}
}
if (options.subject) {
if (payload.sub !== options.subject) {
return done(new JsonWebTokenError('jwt subject invalid. expected: ' + options.subject));
}
}
if (options.jwtid) {
if (payload.jti !== options.jwtid) {
return done(new JsonWebTokenError('jwt jwtid invalid. expected: ' + options.jwtid));
}
}
if (options.nonce) {
if (payload.nonce !== options.nonce) {
return done(new JsonWebTokenError('jwt nonce invalid. expected: ' + options.nonce));
}
}
if (options.maxAge) {
if (typeof payload.iat !== 'number') {
return done(new JsonWebTokenError('iat required when maxAge is specified'));
}
const maxAgeTimestamp = timespan(options.maxAge, payload.iat);
if (typeof maxAgeTimestamp === 'undefined') {
return done(new JsonWebTokenError('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));
}
if (clockTimestamp >= maxAgeTimestamp + (options.clockTolerance || 0)) {
return done(new TokenExpiredError('maxAge exceeded', new Date(maxAgeTimestamp * 1000)));
}
}
if (options.complete === true) {
const signature = decodedToken.signature;
return done(null, {
header: header,
payload: payload,
signature: signature
});
}
return done(null, payload);
});
};

17
node_modules/jwa/LICENSE generated vendored Normal file
View File

@ -0,0 +1,17 @@
Copyright (c) 2013 Brian J. Brennan
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.

150
node_modules/jwa/README.md generated vendored Normal file
View File

@ -0,0 +1,150 @@
# node-jwa [![Build Status](https://travis-ci.org/brianloveswords/node-jwa.svg?branch=master)](https://travis-ci.org/brianloveswords/node-jwa)
A
[JSON Web Algorithms](http://tools.ietf.org/id/draft-ietf-jose-json-web-algorithms-08.html)
implementation focusing (exclusively, at this point) on the algorithms necessary for
[JSON Web Signatures](http://self-issued.info/docs/draft-ietf-jose-json-web-signature.html).
This library supports all of the required, recommended and optional cryptographic algorithms for JWS:
alg Parameter Value | Digital Signature or MAC Algorithm
----------------|----------------------------
HS256 | HMAC using SHA-256 hash algorithm
HS384 | HMAC using SHA-384 hash algorithm
HS512 | HMAC using SHA-512 hash algorithm
RS256 | RSASSA using SHA-256 hash algorithm
RS384 | RSASSA using SHA-384 hash algorithm
RS512 | RSASSA using SHA-512 hash algorithm
PS256 | RSASSA-PSS using SHA-256 hash algorithm
PS384 | RSASSA-PSS using SHA-384 hash algorithm
PS512 | RSASSA-PSS using SHA-512 hash algorithm
ES256 | ECDSA using P-256 curve and SHA-256 hash algorithm
ES384 | ECDSA using P-384 curve and SHA-384 hash algorithm
ES512 | ECDSA using P-521 curve and SHA-512 hash algorithm
none | No digital signature or MAC value included
Please note that PS* only works on Node 6.12+ (excluding 7.x).
# Requirements
In order to run the tests, a recent version of OpenSSL is
required. **The version that comes with OS X (OpenSSL 0.9.8r 8 Feb
2011) is not recent enough**, as it does not fully support ECDSA
keys. You'll need to use a version > 1.0.0; I tested with OpenSSL 1.0.1c 10 May 2012.
# Testing
To run the tests, do
```bash
$ npm test
```
This will generate a bunch of keypairs to use in testing. If you want to
generate new keypairs, do `make clean` before running `npm test` again.
## Methodology
I spawn `openssl dgst -sign` to test OpenSSL sign → JS verify and
`openssl dgst -verify` to test JS sign → OpenSSL verify for each of the
RSA and ECDSA algorithms.
# Usage
## jwa(algorithm)
Creates a new `jwa` object with `sign` and `verify` methods for the
algorithm. Valid values for algorithm can be found in the table above
(`'HS256'`, `'HS384'`, etc) and are case-sensitive. Passing an invalid
algorithm value will throw a `TypeError`.
## jwa#sign(input, secretOrPrivateKey)
Sign some input with either a secret for HMAC algorithms, or a private
key for RSA and ECDSA algorithms.
If input is not already a string or buffer, `JSON.stringify` will be
called on it to attempt to coerce it.
For the HMAC algorithm, `secretOrPrivateKey` should be a string or a
buffer. For ECDSA and RSA, the value should be a string representing a
PEM encoded **private** key.
Output [base64url](http://en.wikipedia.org/wiki/Base64#URL_applications)
formatted. This is for convenience as JWS expects the signature in this
format. If your application needs the output in a different format,
[please open an issue](https://github.com/brianloveswords/node-jwa/issues). In
the meantime, you can use
[brianloveswords/base64url](https://github.com/brianloveswords/base64url)
to decode the signature.
As of nodejs *v0.11.8*, SPKAC support was introduce. If your nodeJs
version satisfies, then you can pass an object `{ key: '..', passphrase: '...' }`
## jwa#verify(input, signature, secretOrPublicKey)
Verify a signature. Returns `true` or `false`.
`signature` should be a base64url encoded string.
For the HMAC algorithm, `secretOrPublicKey` should be a string or a
buffer. For ECDSA and RSA, the value should be a string represented a
PEM encoded **public** key.
# Example
HMAC
```js
const jwa = require('jwa');
const hmac = jwa('HS256');
const input = 'super important stuff';
const secret = 'shhhhhh';
const signature = hmac.sign(input, secret);
hmac.verify(input, signature, secret) // === true
hmac.verify(input, signature, 'trickery!') // === false
```
With keys
```js
const fs = require('fs');
const jwa = require('jwa');
const privateKey = fs.readFileSync(__dirname + '/ecdsa-p521-private.pem');
const publicKey = fs.readFileSync(__dirname + '/ecdsa-p521-public.pem');
const ecdsa = jwa('ES512');
const input = 'very important stuff';
const signature = ecdsa.sign(input, privateKey);
ecdsa.verify(input, signature, publicKey) // === true
```
## License
MIT
```
Copyright (c) 2013 Brian J. Brennan
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.
```

266
node_modules/jwa/index.js generated vendored Normal file
View File

@ -0,0 +1,266 @@
var Buffer = require('safe-buffer').Buffer;
var crypto = require('crypto');
var formatEcdsa = require('ecdsa-sig-formatter');
var util = require('util');
var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".'
var MSG_INVALID_SECRET = 'secret must be a string or buffer';
var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer';
var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object';
var supportsKeyObjects = typeof crypto.createPublicKey === 'function';
if (supportsKeyObjects) {
MSG_INVALID_VERIFIER_KEY += ' or a KeyObject';
MSG_INVALID_SECRET += 'or a KeyObject';
}
function checkIsPublicKey(key) {
if (Buffer.isBuffer(key)) {
return;
}
if (typeof key === 'string') {
return;
}
if (!supportsKeyObjects) {
throw typeError(MSG_INVALID_VERIFIER_KEY);
}
if (typeof key !== 'object') {
throw typeError(MSG_INVALID_VERIFIER_KEY);
}
if (typeof key.type !== 'string') {
throw typeError(MSG_INVALID_VERIFIER_KEY);
}
if (typeof key.asymmetricKeyType !== 'string') {
throw typeError(MSG_INVALID_VERIFIER_KEY);
}
if (typeof key.export !== 'function') {
throw typeError(MSG_INVALID_VERIFIER_KEY);
}
};
function checkIsPrivateKey(key) {
if (Buffer.isBuffer(key)) {
return;
}
if (typeof key === 'string') {
return;
}
if (typeof key === 'object') {
return;
}
throw typeError(MSG_INVALID_SIGNER_KEY);
};
function checkIsSecretKey(key) {
if (Buffer.isBuffer(key)) {
return;
}
if (typeof key === 'string') {
return key;
}
if (!supportsKeyObjects) {
throw typeError(MSG_INVALID_SECRET);
}
if (typeof key !== 'object') {
throw typeError(MSG_INVALID_SECRET);
}
if (key.type !== 'secret') {
throw typeError(MSG_INVALID_SECRET);
}
if (typeof key.export !== 'function') {
throw typeError(MSG_INVALID_SECRET);
}
}
function fromBase64(base64) {
return base64
.replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_');
}
function toBase64(base64url) {
base64url = base64url.toString();
var padding = 4 - base64url.length % 4;
if (padding !== 4) {
for (var i = 0; i < padding; ++i) {
base64url += '=';
}
}
return base64url
.replace(/\-/g, '+')
.replace(/_/g, '/');
}
function typeError(template) {
var args = [].slice.call(arguments, 1);
var errMsg = util.format.bind(util, template).apply(null, args);
return new TypeError(errMsg);
}
function bufferOrString(obj) {
return Buffer.isBuffer(obj) || typeof obj === 'string';
}
function normalizeInput(thing) {
if (!bufferOrString(thing))
thing = JSON.stringify(thing);
return thing;
}
function createHmacSigner(bits) {
return function sign(thing, secret) {
checkIsSecretKey(secret);
thing = normalizeInput(thing);
var hmac = crypto.createHmac('sha' + bits, secret);
var sig = (hmac.update(thing), hmac.digest('base64'))
return fromBase64(sig);
}
}
var bufferEqual;
var timingSafeEqual = 'timingSafeEqual' in crypto ? function timingSafeEqual(a, b) {
if (a.byteLength !== b.byteLength) {
return false;
}
return crypto.timingSafeEqual(a, b)
} : function timingSafeEqual(a, b) {
if (!bufferEqual) {
bufferEqual = require('buffer-equal-constant-time');
}
return bufferEqual(a, b)
}
function createHmacVerifier(bits) {
return function verify(thing, signature, secret) {
var computedSig = createHmacSigner(bits)(thing, secret);
return timingSafeEqual(Buffer.from(signature), Buffer.from(computedSig));
}
}
function createKeySigner(bits) {
return function sign(thing, privateKey) {
checkIsPrivateKey(privateKey);
thing = normalizeInput(thing);
// Even though we are specifying "RSA" here, this works with ECDSA
// keys as well.
var signer = crypto.createSign('RSA-SHA' + bits);
var sig = (signer.update(thing), signer.sign(privateKey, 'base64'));
return fromBase64(sig);
}
}
function createKeyVerifier(bits) {
return function verify(thing, signature, publicKey) {
checkIsPublicKey(publicKey);
thing = normalizeInput(thing);
signature = toBase64(signature);
var verifier = crypto.createVerify('RSA-SHA' + bits);
verifier.update(thing);
return verifier.verify(publicKey, signature, 'base64');
}
}
function createPSSKeySigner(bits) {
return function sign(thing, privateKey) {
checkIsPrivateKey(privateKey);
thing = normalizeInput(thing);
var signer = crypto.createSign('RSA-SHA' + bits);
var sig = (signer.update(thing), signer.sign({
key: privateKey,
padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST
}, 'base64'));
return fromBase64(sig);
}
}
function createPSSKeyVerifier(bits) {
return function verify(thing, signature, publicKey) {
checkIsPublicKey(publicKey);
thing = normalizeInput(thing);
signature = toBase64(signature);
var verifier = crypto.createVerify('RSA-SHA' + bits);
verifier.update(thing);
return verifier.verify({
key: publicKey,
padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST
}, signature, 'base64');
}
}
function createECDSASigner(bits) {
var inner = createKeySigner(bits);
return function sign() {
var signature = inner.apply(null, arguments);
signature = formatEcdsa.derToJose(signature, 'ES' + bits);
return signature;
};
}
function createECDSAVerifer(bits) {
var inner = createKeyVerifier(bits);
return function verify(thing, signature, publicKey) {
signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64');
var result = inner(thing, signature, publicKey);
return result;
};
}
function createNoneSigner() {
return function sign() {
return '';
}
}
function createNoneVerifier() {
return function verify(thing, signature) {
return signature === '';
}
}
module.exports = function jwa(algorithm) {
var signerFactories = {
hs: createHmacSigner,
rs: createKeySigner,
ps: createPSSKeySigner,
es: createECDSASigner,
none: createNoneSigner,
}
var verifierFactories = {
hs: createHmacVerifier,
rs: createKeyVerifier,
ps: createPSSKeyVerifier,
es: createECDSAVerifer,
none: createNoneVerifier,
}
var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);
if (!match)
throw typeError(MSG_INVALID_ALGORITHM, algorithm);
var algo = (match[1] || match[3]).toLowerCase();
var bits = match[2];
return {
sign: signerFactories[algo](bits),
verify: verifierFactories[algo](bits),
}
};

6
node_modules/jwa/opslevel.yml generated vendored Normal file
View File

@ -0,0 +1,6 @@
---
version: 1
repository:
owner: iam_protocols
tier:
tags:

37
node_modules/jwa/package.json generated vendored Normal file
View File

@ -0,0 +1,37 @@
{
"name": "jwa",
"version": "2.0.1",
"description": "JWA implementation (supports all JWS algorithms)",
"main": "index.js",
"directories": {
"test": "test"
},
"dependencies": {
"buffer-equal-constant-time": "^1.0.1",
"ecdsa-sig-formatter": "1.0.11",
"safe-buffer": "^5.0.1"
},
"devDependencies": {
"base64url": "^2.0.0",
"jwk-to-pem": "^2.0.1",
"semver": "4.3.6",
"tap": "6.2.0"
},
"scripts": {
"test": "make test"
},
"repository": {
"type": "git",
"url": "git://github.com/brianloveswords/node-jwa.git"
},
"keywords": [
"jwa",
"jws",
"jwt",
"rsa",
"ecdsa",
"hmac"
],
"author": "Brian J. Brennan <brianloveswords@gmail.com>",
"license": "MIT"
}

56
node_modules/jws/CHANGELOG.md generated vendored Normal file
View File

@ -0,0 +1,56 @@
# Change Log
All notable changes to this project will be documented in this file.
## [4.0.1]
### Changed
- Fix advisory GHSA-869p-cjfg-cm3x: createSign and createVerify now require
that a non empty secret is provided (via opts.secret, opts.privateKey or opts.key)
when using HMAC algorithms.
- Upgrading JWA version to 2.0.1, adressing a compatibility issue for Node >= 25.
## [3.2.3]
### Changed
- Fix advisory GHSA-869p-cjfg-cm3x: createSign and createVerify now require
that a non empty secret is provided (via opts.secret, opts.privateKey or opts.key)
when using HMAC algorithms.
- Upgrading JWA version to 1.4.2, adressing a compatibility issue for Node >= 25.
## [3.0.0]
### Changed
- **BREAKING**: `jwt.verify` now requires an `algorithm` parameter, and
`jws.createVerify` requires an `algorithm` option. The `"alg"` field
signature headers is ignored. This mitigates a critical security flaw
in the library which would allow an attacker to generate signatures with
arbitrary contents that would be accepted by `jwt.verify`. See
https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
for details.
## [2.0.0] - 2015-01-30
### Changed
- **BREAKING**: Default payload encoding changed from `binary` to
`utf8`. `utf8` is a is a more sensible default than `binary` because
many payloads, as far as I can tell, will contain user-facing
strings that could be in any language. (<code>[6b6de48]</code>)
- Code reorganization, thanks [@fearphage]! (<code>[7880050]</code>)
### Added
- Option in all relevant methods for `encoding`. For those few users
that might be depending on a `binary` encoding of the messages, this
is for them. (<code>[6b6de48]</code>)
[unreleased]: https://github.com/brianloveswords/node-jws/compare/v2.0.0...HEAD
[2.0.0]: https://github.com/brianloveswords/node-jws/compare/v1.0.1...v2.0.0
[7880050]: https://github.com/brianloveswords/node-jws/commit/7880050
[6b6de48]: https://github.com/brianloveswords/node-jws/commit/6b6de48
[@fearphage]: https://github.com/fearphage

17
node_modules/jws/LICENSE generated vendored Normal file
View File

@ -0,0 +1,17 @@
Copyright (c) 2013 Brian J. Brennan
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.

22
node_modules/jws/index.js generated vendored Normal file
View File

@ -0,0 +1,22 @@
/*global exports*/
var SignStream = require('./lib/sign-stream');
var VerifyStream = require('./lib/verify-stream');
var ALGORITHMS = [
'HS256', 'HS384', 'HS512',
'RS256', 'RS384', 'RS512',
'PS256', 'PS384', 'PS512',
'ES256', 'ES384', 'ES512'
];
exports.ALGORITHMS = ALGORITHMS;
exports.sign = SignStream.sign;
exports.verify = VerifyStream.verify;
exports.decode = VerifyStream.decode;
exports.isValid = VerifyStream.isValid;
exports.createSign = function createSign(opts) {
return new SignStream(opts);
};
exports.createVerify = function createVerify(opts) {
return new VerifyStream(opts);
};

55
node_modules/jws/lib/data-stream.js generated vendored Normal file
View File

@ -0,0 +1,55 @@
/*global module, process*/
var Buffer = require('safe-buffer').Buffer;
var Stream = require('stream');
var util = require('util');
function DataStream(data) {
this.buffer = null;
this.writable = true;
this.readable = true;
// No input
if (!data) {
this.buffer = Buffer.alloc(0);
return this;
}
// Stream
if (typeof data.pipe === 'function') {
this.buffer = Buffer.alloc(0);
data.pipe(this);
return this;
}
// Buffer or String
// or Object (assumedly a passworded key)
if (data.length || typeof data === 'object') {
this.buffer = data;
this.writable = false;
process.nextTick(function () {
this.emit('end', data);
this.readable = false;
this.emit('close');
}.bind(this));
return this;
}
throw new TypeError('Unexpected data type ('+ typeof data + ')');
}
util.inherits(DataStream, Stream);
DataStream.prototype.write = function write(data) {
this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]);
this.emit('data', data);
};
DataStream.prototype.end = function end(data) {
if (data)
this.write(data);
this.emit('end', data);
this.emit('close');
this.writable = false;
this.readable = false;
};
module.exports = DataStream;

83
node_modules/jws/lib/sign-stream.js generated vendored Normal file
View File

@ -0,0 +1,83 @@
/*global module*/
var Buffer = require('safe-buffer').Buffer;
var DataStream = require('./data-stream');
var jwa = require('jwa');
var Stream = require('stream');
var toString = require('./tostring');
var util = require('util');
function base64url(string, encoding) {
return Buffer
.from(string, encoding)
.toString('base64')
.replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_');
}
function jwsSecuredInput(header, payload, encoding) {
encoding = encoding || 'utf8';
var encodedHeader = base64url(toString(header), 'binary');
var encodedPayload = base64url(toString(payload), encoding);
return util.format('%s.%s', encodedHeader, encodedPayload);
}
function jwsSign(opts) {
var header = opts.header;
var payload = opts.payload;
var secretOrKey = opts.secret || opts.privateKey;
var encoding = opts.encoding;
var algo = jwa(header.alg);
var securedInput = jwsSecuredInput(header, payload, encoding);
var signature = algo.sign(securedInput, secretOrKey);
return util.format('%s.%s', securedInput, signature);
}
function SignStream(opts) {
var secret = opts.secret;
secret = secret == null ? opts.privateKey : secret;
secret = secret == null ? opts.key : secret;
if (/^hs/i.test(opts.header.alg) === true && secret == null) {
throw new TypeError('secret must be a string or buffer or a KeyObject')
}
var secretStream = new DataStream(secret);
this.readable = true;
this.header = opts.header;
this.encoding = opts.encoding;
this.secret = this.privateKey = this.key = secretStream;
this.payload = new DataStream(opts.payload);
this.secret.once('close', function () {
if (!this.payload.writable && this.readable)
this.sign();
}.bind(this));
this.payload.once('close', function () {
if (!this.secret.writable && this.readable)
this.sign();
}.bind(this));
}
util.inherits(SignStream, Stream);
SignStream.prototype.sign = function sign() {
try {
var signature = jwsSign({
header: this.header,
payload: this.payload.buffer,
secret: this.secret.buffer,
encoding: this.encoding
});
this.emit('done', signature);
this.emit('data', signature);
this.emit('end');
this.readable = false;
return signature;
} catch (e) {
this.readable = false;
this.emit('error', e);
this.emit('close');
}
};
SignStream.sign = jwsSign;
module.exports = SignStream;

10
node_modules/jws/lib/tostring.js generated vendored Normal file
View File

@ -0,0 +1,10 @@
/*global module*/
var Buffer = require('buffer').Buffer;
module.exports = function toString(obj) {
if (typeof obj === 'string')
return obj;
if (typeof obj === 'number' || Buffer.isBuffer(obj))
return obj.toString();
return JSON.stringify(obj);
};

125
node_modules/jws/lib/verify-stream.js generated vendored Normal file
View File

@ -0,0 +1,125 @@
/*global module*/
var Buffer = require('safe-buffer').Buffer;
var DataStream = require('./data-stream');
var jwa = require('jwa');
var Stream = require('stream');
var toString = require('./tostring');
var util = require('util');
var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;
function isObject(thing) {
return Object.prototype.toString.call(thing) === '[object Object]';
}
function safeJsonParse(thing) {
if (isObject(thing))
return thing;
try { return JSON.parse(thing); }
catch (e) { return undefined; }
}
function headerFromJWS(jwsSig) {
var encodedHeader = jwsSig.split('.', 1)[0];
return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary'));
}
function securedInputFromJWS(jwsSig) {
return jwsSig.split('.', 2).join('.');
}
function signatureFromJWS(jwsSig) {
return jwsSig.split('.')[2];
}
function payloadFromJWS(jwsSig, encoding) {
encoding = encoding || 'utf8';
var payload = jwsSig.split('.')[1];
return Buffer.from(payload, 'base64').toString(encoding);
}
function isValidJws(string) {
return JWS_REGEX.test(string) && !!headerFromJWS(string);
}
function jwsVerify(jwsSig, algorithm, secretOrKey) {
if (!algorithm) {
var err = new Error("Missing algorithm parameter for jws.verify");
err.code = "MISSING_ALGORITHM";
throw err;
}
jwsSig = toString(jwsSig);
var signature = signatureFromJWS(jwsSig);
var securedInput = securedInputFromJWS(jwsSig);
var algo = jwa(algorithm);
return algo.verify(securedInput, signature, secretOrKey);
}
function jwsDecode(jwsSig, opts) {
opts = opts || {};
jwsSig = toString(jwsSig);
if (!isValidJws(jwsSig))
return null;
var header = headerFromJWS(jwsSig);
if (!header)
return null;
var payload = payloadFromJWS(jwsSig);
if (header.typ === 'JWT' || opts.json)
payload = JSON.parse(payload, opts.encoding);
return {
header: header,
payload: payload,
signature: signatureFromJWS(jwsSig)
};
}
function VerifyStream(opts) {
opts = opts || {};
var secretOrKey = opts.secret;
secretOrKey = secretOrKey == null ? opts.publicKey : secretOrKey;
secretOrKey = secretOrKey == null ? opts.key : secretOrKey;
if (/^hs/i.test(opts.algorithm) === true && secretOrKey == null) {
throw new TypeError('secret must be a string or buffer or a KeyObject')
}
var secretStream = new DataStream(secretOrKey);
this.readable = true;
this.algorithm = opts.algorithm;
this.encoding = opts.encoding;
this.secret = this.publicKey = this.key = secretStream;
this.signature = new DataStream(opts.signature);
this.secret.once('close', function () {
if (!this.signature.writable && this.readable)
this.verify();
}.bind(this));
this.signature.once('close', function () {
if (!this.secret.writable && this.readable)
this.verify();
}.bind(this));
}
util.inherits(VerifyStream, Stream);
VerifyStream.prototype.verify = function verify() {
try {
var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer);
var obj = jwsDecode(this.signature.buffer, this.encoding);
this.emit('done', valid, obj);
this.emit('data', valid);
this.emit('end');
this.readable = false;
return valid;
} catch (e) {
this.readable = false;
this.emit('error', e);
this.emit('close');
}
};
VerifyStream.decode = jwsDecode;
VerifyStream.isValid = isValidJws;
VerifyStream.verify = jwsVerify;
module.exports = VerifyStream;

6
node_modules/jws/opslevel.yml generated vendored Normal file
View File

@ -0,0 +1,6 @@
---
version: 1
repository:
owner: iam_protocols
tier:
tags:

34
node_modules/jws/package.json generated vendored Normal file
View File

@ -0,0 +1,34 @@
{
"name": "jws",
"version": "4.0.1",
"description": "Implementation of JSON Web Signatures",
"main": "index.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "make test"
},
"repository": {
"type": "git",
"url": "git://github.com/brianloveswords/node-jws.git"
},
"keywords": [
"jws",
"json",
"web",
"signatures"
],
"author": "Brian J Brennan",
"license": "MIT",
"readmeFilename": "readme.md",
"gitHead": "c0f6b27bcea5a2ad2e304d91c2e842e4076a6b03",
"dependencies": {
"jwa": "^2.0.1",
"safe-buffer": "^5.0.1"
},
"devDependencies": {
"semver": "^5.1.0",
"tape": "~2.14.0"
}
}

255
node_modules/jws/readme.md generated vendored Normal file
View File

@ -0,0 +1,255 @@
# node-jws [![Build Status](https://secure.travis-ci.org/brianloveswords/node-jws.svg)](http://travis-ci.org/brianloveswords/node-jws)
An implementation of [JSON Web Signatures](http://self-issued.info/docs/draft-ietf-jose-json-web-signature.html).
This was developed against `draft-ietf-jose-json-web-signature-08` and
implements the entire spec **except** X.509 Certificate Chain
signing/verifying (patches welcome).
There are both synchronous (`jws.sign`, `jws.verify`) and streaming
(`jws.createSign`, `jws.createVerify`) APIs.
# Install
```bash
$ npm install jws
```
# Usage
## jws.ALGORITHMS
Array of supported algorithms. The following algorithms are currently supported.
alg Parameter Value | Digital Signature or MAC Algorithm
----------------|----------------------------
HS256 | HMAC using SHA-256 hash algorithm
HS384 | HMAC using SHA-384 hash algorithm
HS512 | HMAC using SHA-512 hash algorithm
RS256 | RSASSA using SHA-256 hash algorithm
RS384 | RSASSA using SHA-384 hash algorithm
RS512 | RSASSA using SHA-512 hash algorithm
PS256 | RSASSA-PSS using SHA-256 hash algorithm
PS384 | RSASSA-PSS using SHA-384 hash algorithm
PS512 | RSASSA-PSS using SHA-512 hash algorithm
ES256 | ECDSA using P-256 curve and SHA-256 hash algorithm
ES384 | ECDSA using P-384 curve and SHA-384 hash algorithm
ES512 | ECDSA using P-521 curve and SHA-512 hash algorithm
none | No digital signature or MAC value included
## jws.sign(options)
(Synchronous) Return a JSON Web Signature for a header and a payload.
Options:
* `header`
* `payload`
* `secret` or `privateKey`
* `encoding` (Optional, defaults to 'utf8')
`header` must be an object with an `alg` property. `header.alg` must be
one a value found in `jws.ALGORITHMS`. See above for a table of
supported algorithms.
If `payload` is not a buffer or a string, it will be coerced into a string
using `JSON.stringify`.
Example
```js
const signature = jws.sign({
header: { alg: 'HS256' },
payload: 'h. jon benjamin',
secret: 'has a van',
});
```
## jws.verify(signature, algorithm, secretOrKey)
(Synchronous) Returns `true` or `false` for whether a signature matches a
secret or key.
`signature` is a JWS Signature. `header.alg` must be a value found in `jws.ALGORITHMS`.
See above for a table of supported algorithms. `secretOrKey` is a string or
buffer containing either the secret for HMAC algorithms, or the PEM
encoded public key for RSA and ECDSA.
Note that the `"alg"` value from the signature header is ignored.
## jws.decode(signature)
(Synchronous) Returns the decoded header, decoded payload, and signature
parts of the JWS Signature.
Returns an object with three properties, e.g.
```js
{ header: { alg: 'HS256' },
payload: 'h. jon benjamin',
signature: 'YOWPewyGHKu4Y_0M_vtlEnNlqmFOclqp4Hy6hVHfFT4'
}
```
## jws.createSign(options)
Returns a new SignStream object.
Options:
* `header` (required)
* `payload`
* `key` || `privateKey` || `secret`
* `encoding` (Optional, defaults to 'utf8')
Other than `header`, all options expect a string or a buffer when the
value is known ahead of time, or a stream for convenience.
`key`/`privateKey`/`secret` may also be an object when using an encrypted
private key, see the [crypto documentation][encrypted-key-docs].
Example:
```js
// This...
jws.createSign({
header: { alg: 'RS256' },
privateKey: privateKeyStream,
payload: payloadStream,
}).on('done', function(signature) {
// ...
});
// is equivalent to this:
const signer = jws.createSign({
header: { alg: 'RS256' },
});
privateKeyStream.pipe(signer.privateKey);
payloadStream.pipe(signer.payload);
signer.on('done', function(signature) {
// ...
});
```
## jws.createVerify(options)
Returns a new VerifyStream object.
Options:
* `signature`
* `algorithm`
* `key` || `publicKey` || `secret`
* `encoding` (Optional, defaults to 'utf8')
All options expect a string or a buffer when the value is known ahead of
time, or a stream for convenience.
Example:
```js
// This...
jws.createVerify({
publicKey: pubKeyStream,
signature: sigStream,
}).on('done', function(verified, obj) {
// ...
});
// is equivilant to this:
const verifier = jws.createVerify();
pubKeyStream.pipe(verifier.publicKey);
sigStream.pipe(verifier.signature);
verifier.on('done', function(verified, obj) {
// ...
});
```
## Class: SignStream
A `Readable Stream` that emits a single data event (the calculated
signature) when done.
### Event: 'done'
`function (signature) { }`
### signer.payload
A `Writable Stream` that expects the JWS payload. Do *not* use if you
passed a `payload` option to the constructor.
Example:
```js
payloadStream.pipe(signer.payload);
```
### signer.secret<br>signer.key<br>signer.privateKey
A `Writable Stream`. Expects the JWS secret for HMAC, or the privateKey
for ECDSA and RSA. Do *not* use if you passed a `secret` or `key` option
to the constructor.
Example:
```js
privateKeyStream.pipe(signer.privateKey);
```
## Class: VerifyStream
This is a `Readable Stream` that emits a single data event, the result
of whether or not that signature was valid.
### Event: 'done'
`function (valid, obj) { }`
`valid` is a boolean for whether or not the signature is valid.
### verifier.signature
A `Writable Stream` that expects a JWS Signature. Do *not* use if you
passed a `signature` option to the constructor.
### verifier.secret<br>verifier.key<br>verifier.publicKey
A `Writable Stream` that expects a public key or secret. Do *not* use if you
passed a `key` or `secret` option to the constructor.
# TODO
* It feels like there should be some convenience options/APIs for
defining the algorithm rather than having to define a header object
with `{ alg: 'ES512' }` or whatever every time.
* X.509 support, ugh
# License
MIT
```
Copyright (c) 2013-2015 Brian J. Brennan
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.
```
[encrypted-key-docs]: https://nodejs.org/api/crypto.html#crypto_sign_sign_private_key_output_format

47
node_modules/lodash.includes/LICENSE generated vendored Normal file
View File

@ -0,0 +1,47 @@
Copyright jQuery Foundation and other contributors <https://jquery.org/>
Based on Underscore.js, copyright Jeremy Ashkenas,
DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
This software consists of voluntary contributions made by many
individuals. For exact contribution history, see the revision history
available at https://github.com/lodash/lodash
The following license applies to all parts of this software except as
documented below:
====
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.
====
Copyright and related rights for sample code are waived via CC0. Sample
code is defined as all source code displayed within the prose of the
documentation.
CC0: http://creativecommons.org/publicdomain/zero/1.0/
====
Files located in the node_modules and vendor directories are externally
maintained libraries used by this software which have their own
licenses; we recommend you read them, as their terms may differ from the
terms above.

18
node_modules/lodash.includes/README.md generated vendored Normal file
View File

@ -0,0 +1,18 @@
# lodash.includes v4.3.0
The [lodash](https://lodash.com/) method `_.includes` exported as a [Node.js](https://nodejs.org/) module.
## Installation
Using npm:
```bash
$ {sudo -H} npm i -g npm
$ npm i --save lodash.includes
```
In Node.js:
```js
var includes = require('lodash.includes');
```
See the [documentation](https://lodash.com/docs#includes) or [package source](https://github.com/lodash/lodash/blob/4.3.0-npm-packages/lodash.includes) for more details.

745
node_modules/lodash.includes/index.js generated vendored Normal file
View File

@ -0,0 +1,745 @@
/**
* lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
MAX_SAFE_INTEGER = 9007199254740991,
MAX_INTEGER = 1.7976931348623157e+308,
NAN = 0 / 0;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
stringTag = '[object String]',
symbolTag = '[object Symbol]';
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array ? array.length : 0,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromIndex, fromRight) {
var length = array.length,
index = fromIndex + (fromRight ? 1 : -1);
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
/**
* The base implementation of `_.indexOf` without `fromIndex` bounds checks.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOf(array, value, fromIndex) {
if (value !== value) {
return baseFindIndex(array, baseIsNaN, fromIndex);
}
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* The base implementation of `_.isNaN` without support for number objects.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
*/
function baseIsNaN(value) {
return value !== value;
}
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
/**
* The base implementation of `_.values` and `_.valuesIn` which creates an
* array of `object` property values corresponding to the property names
* of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the array of property values.
*/
function baseValues(object, props) {
return arrayMap(props, function(key) {
return object[key];
});
}
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object),
nativeMax = Math.max;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
// Safari 8.1 makes `arguments.callee` enumerable in strict mode.
// Safari 9 makes `arguments.length` enumerable in strict mode.
var result = (isArray(value) || isArguments(value))
? baseTimes(value.length, String)
: [];
var length = result.length,
skipIndexes = !!length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (key == 'length' || isIndex(key, length)))) {
result.push(key);
}
}
return result;
}
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(typeof value == 'number' || reIsUint.test(value)) &&
(value > -1 && value % 1 == 0 && value < length);
}
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
/**
* Checks if `value` is in `collection`. If `collection` is a string, it's
* checked for a substring of `value`, otherwise
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* is used for equality comparisons. If `fromIndex` is negative, it's used as
* the offset from the end of `collection`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {boolean} Returns `true` if `value` is found, else `false`.
* @example
*
* _.includes([1, 2, 3], 1);
* // => true
*
* _.includes([1, 2, 3], 1, 2);
* // => false
*
* _.includes({ 'a': 1, 'b': 2 }, 1);
* // => true
*
* _.includes('abcd', 'bc');
* // => true
*/
function includes(collection, value, fromIndex, guard) {
collection = isArrayLike(collection) ? collection : values(collection);
fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
var length = collection.length;
if (fromIndex < 0) {
fromIndex = nativeMax(length + fromIndex, 0);
}
return isString(collection)
? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
: (!!length && baseIndexOf(collection, value, fromIndex) > -1);
}
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
// Safari 8.1 makes `arguments.callee` enumerable in strict mode.
return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
(!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
}
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 8-9 which returns 'object' for typed array and other constructors.
var tag = isObject(value) ? objectToString.call(value) : '';
return tag == funcTag || tag == genTag;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a string, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag);
}
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && objectToString.call(value) == symbolTag);
}
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber(value);
if (value === INFINITY || value === -INFINITY) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/
function toInteger(value) {
var result = toFinite(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
/**
* Creates an array of the own enumerable string keyed property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.values(new Foo);
* // => [1, 2] (iteration order is not guaranteed)
*
* _.values('hi');
* // => ['h', 'i']
*/
function values(object) {
return object ? baseValues(object, keys(object)) : [];
}
module.exports = includes;

17
node_modules/lodash.includes/package.json generated vendored Normal file
View File

@ -0,0 +1,17 @@
{
"name": "lodash.includes",
"version": "4.3.0",
"description": "The lodash method `_.includes` exported as a module.",
"homepage": "https://lodash.com/",
"icon": "https://lodash.com/icon.svg",
"license": "MIT",
"keywords": "lodash-modularized, includes",
"author": "John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)",
"contributors": [
"John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)",
"Blaine Bublitz <blaine.bublitz@gmail.com> (https://github.com/phated)",
"Mathias Bynens <mathias@qiwi.be> (https://mathiasbynens.be/)"
],
"repository": "lodash/lodash",
"scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" }
}

22
node_modules/lodash.isboolean/LICENSE generated vendored Normal file
View File

@ -0,0 +1,22 @@
Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
Based on Underscore.js, copyright 2009-2016 Jeremy Ashkenas,
DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
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.

18
node_modules/lodash.isboolean/README.md generated vendored Normal file
View File

@ -0,0 +1,18 @@
# lodash.isboolean v3.0.3
The [lodash](https://lodash.com/) method `_.isBoolean` exported as a [Node.js](https://nodejs.org/) module.
## Installation
Using npm:
```bash
$ {sudo -H} npm i -g npm
$ npm i --save lodash.isboolean
```
In Node.js:
```js
var isBoolean = require('lodash.isboolean');
```
See the [documentation](https://lodash.com/docs#isBoolean) or [package source](https://github.com/lodash/lodash/blob/3.0.3-npm-packages/lodash.isboolean) for more details.

70
node_modules/lodash.isboolean/index.js generated vendored Normal file
View File

@ -0,0 +1,70 @@
/**
* lodash 3.0.3 (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** `Object#toString` result references. */
var boolTag = '[object Boolean]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/**
* Checks if `value` is classified as a boolean primitive or object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isBoolean(false);
* // => true
*
* _.isBoolean(null);
* // => false
*/
function isBoolean(value) {
return value === true || value === false ||
(isObjectLike(value) && objectToString.call(value) == boolTag);
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
module.exports = isBoolean;

17
node_modules/lodash.isboolean/package.json generated vendored Normal file
View File

@ -0,0 +1,17 @@
{
"name": "lodash.isboolean",
"version": "3.0.3",
"description": "The lodash method `_.isBoolean` exported as a module.",
"homepage": "https://lodash.com/",
"icon": "https://lodash.com/icon.svg",
"license": "MIT",
"keywords": "lodash-modularized, isboolean",
"author": "John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)",
"contributors": [
"John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)",
"Blaine Bublitz <blaine@iceddev.com> (https://github.com/phated)",
"Mathias Bynens <mathias@qiwi.be> (https://mathiasbynens.be/)"
],
"repository": "lodash/lodash",
"scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" }
}

47
node_modules/lodash.isinteger/LICENSE generated vendored Normal file
View File

@ -0,0 +1,47 @@
Copyright jQuery Foundation and other contributors <https://jquery.org/>
Based on Underscore.js, copyright Jeremy Ashkenas,
DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
This software consists of voluntary contributions made by many
individuals. For exact contribution history, see the revision history
available at https://github.com/lodash/lodash
The following license applies to all parts of this software except as
documented below:
====
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.
====
Copyright and related rights for sample code are waived via CC0. Sample
code is defined as all source code displayed within the prose of the
documentation.
CC0: http://creativecommons.org/publicdomain/zero/1.0/
====
Files located in the node_modules and vendor directories are externally
maintained libraries used by this software which have their own
licenses; we recommend you read them, as their terms may differ from the
terms above.

18
node_modules/lodash.isinteger/README.md generated vendored Normal file
View File

@ -0,0 +1,18 @@
# lodash.isinteger v4.0.4
The [lodash](https://lodash.com/) method `_.isInteger` exported as a [Node.js](https://nodejs.org/) module.
## Installation
Using npm:
```bash
$ {sudo -H} npm i -g npm
$ npm i --save lodash.isinteger
```
In Node.js:
```js
var isInteger = require('lodash.isinteger');
```
See the [documentation](https://lodash.com/docs#isInteger) or [package source](https://github.com/lodash/lodash/blob/4.0.4-npm-packages/lodash.isinteger) for more details.

265
node_modules/lodash.isinteger/index.js generated vendored Normal file
View File

@ -0,0 +1,265 @@
/**
* lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
MAX_INTEGER = 1.7976931348623157e+308,
NAN = 0 / 0;
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/**
* Checks if `value` is an integer.
*
* **Note:** This method is based on
* [`Number.isInteger`](https://mdn.io/Number/isInteger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an integer, else `false`.
* @example
*
* _.isInteger(3);
* // => true
*
* _.isInteger(Number.MIN_VALUE);
* // => false
*
* _.isInteger(Infinity);
* // => false
*
* _.isInteger('3');
* // => false
*/
function isInteger(value) {
return typeof value == 'number' && value == toInteger(value);
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && objectToString.call(value) == symbolTag);
}
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber(value);
if (value === INFINITY || value === -INFINITY) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/
function toInteger(value) {
var result = toFinite(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
module.exports = isInteger;

17
node_modules/lodash.isinteger/package.json generated vendored Normal file
View File

@ -0,0 +1,17 @@
{
"name": "lodash.isinteger",
"version": "4.0.4",
"description": "The lodash method `_.isInteger` exported as a module.",
"homepage": "https://lodash.com/",
"icon": "https://lodash.com/icon.svg",
"license": "MIT",
"keywords": "lodash-modularized, isinteger",
"author": "John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)",
"contributors": [
"John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)",
"Blaine Bublitz <blaine.bublitz@gmail.com> (https://github.com/phated)",
"Mathias Bynens <mathias@qiwi.be> (https://mathiasbynens.be/)"
],
"repository": "lodash/lodash",
"scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" }
}

22
node_modules/lodash.isnumber/LICENSE generated vendored Normal file
View File

@ -0,0 +1,22 @@
Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
Based on Underscore.js, copyright 2009-2016 Jeremy Ashkenas,
DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
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.

18
node_modules/lodash.isnumber/README.md generated vendored Normal file
View File

@ -0,0 +1,18 @@
# lodash.isnumber v3.0.3
The [lodash](https://lodash.com/) method `_.isNumber` exported as a [Node.js](https://nodejs.org/) module.
## Installation
Using npm:
```bash
$ {sudo -H} npm i -g npm
$ npm i --save lodash.isnumber
```
In Node.js:
```js
var isNumber = require('lodash.isnumber');
```
See the [documentation](https://lodash.com/docs#isNumber) or [package source](https://github.com/lodash/lodash/blob/3.0.3-npm-packages/lodash.isnumber) for more details.

79
node_modules/lodash.isnumber/index.js generated vendored Normal file
View File

@ -0,0 +1,79 @@
/**
* lodash 3.0.3 (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** `Object#toString` result references. */
var numberTag = '[object Number]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified
* as numbers, use the `_.isFinite` method.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isNumber(3);
* // => true
*
* _.isNumber(Number.MIN_VALUE);
* // => true
*
* _.isNumber(Infinity);
* // => true
*
* _.isNumber('3');
* // => false
*/
function isNumber(value) {
return typeof value == 'number' ||
(isObjectLike(value) && objectToString.call(value) == numberTag);
}
module.exports = isNumber;

17
node_modules/lodash.isnumber/package.json generated vendored Normal file
View File

@ -0,0 +1,17 @@
{
"name": "lodash.isnumber",
"version": "3.0.3",
"description": "The lodash method `_.isNumber` exported as a module.",
"homepage": "https://lodash.com/",
"icon": "https://lodash.com/icon.svg",
"license": "MIT",
"keywords": "lodash-modularized, isnumber",
"author": "John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)",
"contributors": [
"John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)",
"Blaine Bublitz <blaine@iceddev.com> (https://github.com/phated)",
"Mathias Bynens <mathias@qiwi.be> (https://mathiasbynens.be/)"
],
"repository": "lodash/lodash",
"scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" }
}

47
node_modules/lodash.isplainobject/LICENSE generated vendored Normal file
View File

@ -0,0 +1,47 @@
Copyright jQuery Foundation and other contributors <https://jquery.org/>
Based on Underscore.js, copyright Jeremy Ashkenas,
DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
This software consists of voluntary contributions made by many
individuals. For exact contribution history, see the revision history
available at https://github.com/lodash/lodash
The following license applies to all parts of this software except as
documented below:
====
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.
====
Copyright and related rights for sample code are waived via CC0. Sample
code is defined as all source code displayed within the prose of the
documentation.
CC0: http://creativecommons.org/publicdomain/zero/1.0/
====
Files located in the node_modules and vendor directories are externally
maintained libraries used by this software which have their own
licenses; we recommend you read them, as their terms may differ from the
terms above.

18
node_modules/lodash.isplainobject/README.md generated vendored Normal file
View File

@ -0,0 +1,18 @@
# lodash.isplainobject v4.0.6
The [lodash](https://lodash.com/) method `_.isPlainObject` exported as a [Node.js](https://nodejs.org/) module.
## Installation
Using npm:
```bash
$ {sudo -H} npm i -g npm
$ npm i --save lodash.isplainobject
```
In Node.js:
```js
var isPlainObject = require('lodash.isplainobject');
```
See the [documentation](https://lodash.com/docs#isPlainObject) or [package source](https://github.com/lodash/lodash/blob/4.0.6-npm-packages/lodash.isplainobject) for more details.

139
node_modules/lodash.isplainobject/index.js generated vendored Normal file
View File

@ -0,0 +1,139 @@
/**
* lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** `Object#toString` result references. */
var objectTag = '[object Object]';
/**
* Checks if `value` is a host object in IE < 9.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
*/
function isHostObject(value) {
// Many host objects are `Object` objects that can coerce to strings
// despite having improperly defined `toString` methods.
var result = false;
if (value != null && typeof value.toString != 'function') {
try {
result = !!(value + '');
} catch (e) {}
}
return result;
}
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
/** Used for built-in method references. */
var funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/** Built-in value references. */
var getPrototype = overArg(Object.getPrototypeOf, Object);
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike(value) ||
objectToString.call(value) != objectTag || isHostObject(value)) {
return false;
}
var proto = getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return (typeof Ctor == 'function' &&
Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
}
module.exports = isPlainObject;

17
node_modules/lodash.isplainobject/package.json generated vendored Normal file
View File

@ -0,0 +1,17 @@
{
"name": "lodash.isplainobject",
"version": "4.0.6",
"description": "The lodash method `_.isPlainObject` exported as a module.",
"homepage": "https://lodash.com/",
"icon": "https://lodash.com/icon.svg",
"license": "MIT",
"keywords": "lodash-modularized, isplainobject",
"author": "John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)",
"contributors": [
"John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)",
"Blaine Bublitz <blaine.bublitz@gmail.com> (https://github.com/phated)",
"Mathias Bynens <mathias@qiwi.be> (https://mathiasbynens.be/)"
],
"repository": "lodash/lodash",
"scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" }
}

22
node_modules/lodash.isstring/LICENSE generated vendored Normal file
View File

@ -0,0 +1,22 @@
Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
Based on Underscore.js, copyright 2009-2016 Jeremy Ashkenas,
DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
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.

18
node_modules/lodash.isstring/README.md generated vendored Normal file
View File

@ -0,0 +1,18 @@
# lodash.isstring v4.0.1
The [lodash](https://lodash.com/) method `_.isString` exported as a [Node.js](https://nodejs.org/) module.
## Installation
Using npm:
```bash
$ {sudo -H} npm i -g npm
$ npm i --save lodash.isstring
```
In Node.js:
```js
var isString = require('lodash.isstring');
```
See the [documentation](https://lodash.com/docs#isString) or [package source](https://github.com/lodash/lodash/blob/4.0.1-npm-packages/lodash.isstring) for more details.

95
node_modules/lodash.isstring/index.js generated vendored Normal file
View File

@ -0,0 +1,95 @@
/**
* lodash 4.0.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** `Object#toString` result references. */
var stringTag = '[object String]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @type Function
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag);
}
module.exports = isString;

17
node_modules/lodash.isstring/package.json generated vendored Normal file
View File

@ -0,0 +1,17 @@
{
"name": "lodash.isstring",
"version": "4.0.1",
"description": "The lodash method `_.isString` exported as a module.",
"homepage": "https://lodash.com/",
"icon": "https://lodash.com/icon.svg",
"license": "MIT",
"keywords": "lodash-modularized, isstring",
"author": "John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)",
"contributors": [
"John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)",
"Blaine Bublitz <blaine@iceddev.com> (https://github.com/phated)",
"Mathias Bynens <mathias@qiwi.be> (https://mathiasbynens.be/)"
],
"repository": "lodash/lodash",
"scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" }
}

47
node_modules/lodash.once/LICENSE generated vendored Normal file
View File

@ -0,0 +1,47 @@
Copyright jQuery Foundation and other contributors <https://jquery.org/>
Based on Underscore.js, copyright Jeremy Ashkenas,
DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
This software consists of voluntary contributions made by many
individuals. For exact contribution history, see the revision history
available at https://github.com/lodash/lodash
The following license applies to all parts of this software except as
documented below:
====
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.
====
Copyright and related rights for sample code are waived via CC0. Sample
code is defined as all source code displayed within the prose of the
documentation.
CC0: http://creativecommons.org/publicdomain/zero/1.0/
====
Files located in the node_modules and vendor directories are externally
maintained libraries used by this software which have their own
licenses; we recommend you read them, as their terms may differ from the
terms above.

18
node_modules/lodash.once/README.md generated vendored Normal file
View File

@ -0,0 +1,18 @@
# lodash.once v4.1.1
The [lodash](https://lodash.com/) method `_.once` exported as a [Node.js](https://nodejs.org/) module.
## Installation
Using npm:
```bash
$ {sudo -H} npm i -g npm
$ npm i --save lodash.once
```
In Node.js:
```js
var once = require('lodash.once');
```
See the [documentation](https://lodash.com/docs#once) or [package source](https://github.com/lodash/lodash/blob/4.1.1-npm-packages/lodash.once) for more details.

Some files were not shown because too many files have changed in this diff Show More