@vigilbase/cli
Version:
Vigilbase CLI — security scanners, agent tools, and Vigilbase One from the terminal.
541 lines (540 loc) • 23.2 kB
JavaScript
// GENERATED from packages/api-contract/src/one/v1/reports-billing.ts by scripts/vendor-api-contract.mjs — do not edit
import { z } from 'zod';
import { defineOperation } from '../../core/operation.js';
import { CustomerParams, Id, ListQuery, ONE_READ_AUTH, page, READ_ERRORS, Timestamp } from './shared.js';
/**
* Reports, contracts and billing for one customer.
*
* Every operation runs the legacy route's guard inside its implementation:
* `read:customers` for reports, `read:contracts` for contracts and usage
* alerts, `read:billing` for billing, invoices and subscriptions. A partner's
* end customer (partner-billed, apps/one/src/lib/auth/partner-billed-access.ts)
* is refused every contracts and billing operation, and its reports carry no
* billing. Readers without billing access get null amounts.
*/
const nullableText = z.string().nullable();
const nullableNumber = z.number().nullable();
/** Money in the currency's minor units (cents), as Stripe counts it. */
const MinorUnits = z.number().int().meta({ description: 'Amount in the currency’s minor units (e.g. cents).' });
/** Money in major units as stored on contracts; null when the caller may not see amounts. */
const ContractAmount = z.number().nullable().meta({ description: 'Amount in major units; null when hidden from the caller (no billing access) or not set.' });
// ---------------------------------------------------------------- reports
export const ReportPeriod = z.object({ start: z.string(), end: z.string(), label: z.string() }).meta({ id: 'ReportPeriod' });
export const ReportSection = z.enum([
'threat_landscape',
'executive_summary',
'ai_analysis',
'endpoint',
'backup',
'cloudflare',
'support',
'billing',
]);
export const ReconReportStatus = z.enum(['pending', 'generating', 'completed', 'failed']);
/** A monthly security (Recon) report as listed. */
export const ReconReportSummary = z
.object({
id: Id,
period: ReportPeriod,
status: ReconReportStatus,
generatedAt: Timestamp.nullable(),
hasPublicLink: z.boolean(),
availableSections: z.array(ReportSection),
})
.meta({ id: 'ReconReportSummary' });
const ServiceSummaryItem = z.object({
status: z.enum(['healthy', 'warning', 'critical', 'inactive']),
keyMetric: z.string(),
keyMetricValue: z.union([z.string(), z.number()]),
change: nullableNumber,
});
const ReportInsight = z.object({
type: z.enum(['anomaly', 'trend', 'recommendation', 'highlight']),
severity: z.enum(['info', 'warning', 'critical', 'success']),
title: z.string(),
description: z.string(),
service: nullableText,
metric: nullableText,
value: nullableNumber,
previousValue: nullableNumber,
isIncreaseBetter: z.boolean(),
});
const Severity = z.enum(['critical', 'high', 'medium', 'low']);
/** One monthly security report: the narrative, each section's figures and, for billing readers, billing. */
export const ReconReport = z
.object({
id: Id,
customerId: Id,
customerName: nullableText,
period: ReportPeriod.extend({ type: z.string() }),
status: ReconReportStatus,
generatedAt: Timestamp.nullable(),
availableSections: z.array(ReportSection),
branding: z.object({
type: z.enum(['vigilbase', 'partner']),
partnerName: nullableText,
partnerLogoUrl: nullableText,
customerLogoUrl: nullableText,
accentColor: z.string(),
}),
publicLink: z
.object({ enabled: z.boolean(), expiresAt: Timestamp.nullable() })
.nullable()
.meta({ description: 'Whether a public share link exists. The link itself is a bearer URL and is not returned.' }),
executiveSummary: z.object({
overallScore: z.number().meta({ description: 'Score from 0 to 100. 0 when `scored` is false.' }),
scoreLabel: z.string().meta({ description: 'Excellent, Good, Fair or Needs Attention; "Not scored" when `scored` is false.' }),
scored: z.boolean().meta({ description: 'False when no service could be measured for the report, so `overallScore` carries no meaning.' }),
scoreVersion: z.number().int().nullable().meta({
description: '2 for the security score (Cloudflare Checkup and endpoint protection). Null for older reports, whose health score also counted support and cache performance and defaulted to 75 without data. Compare scores only within one version.',
}),
highlights: z.array(z.string()),
serviceSummary: z.record(z.string(), ServiceSummaryItem),
}),
threatLandscape: z.object({
title: z.string(),
summary: z.string(),
keyThreats: z.array(z.object({ name: z.string(), description: z.string(), severity: Severity, affectedSystems: z.array(z.string()) })),
industryAlerts: z.array(z.object({ industry: z.string(), title: z.string(), description: z.string(), severity: Severity })),
recommendations: z.array(z.object({ title: z.string(), description: z.string(), priority: z.enum(['high', 'medium', 'low']), category: z.string() })),
}),
insights: z.array(ReportInsight),
aiAnalysis: z
.object({
executiveSummary: z.string(),
securityAnalysis: z.string(),
performanceAnalysis: z.string(),
recommendedActions: z.array(z.string()),
keyHighlights: z.array(z.string()),
riskAssessment: z.object({ level: z.enum(['low', 'medium', 'high', 'critical']), factors: z.array(z.string()) }),
generatedAt: Timestamp.nullable(),
})
.nullable(),
comparison: z.object({
endpointChangePct: nullableNumber,
threatsChangePct: nullableNumber,
requestsChangePct: nullableNumber,
bandwidthChangePct: nullableNumber,
cacheHitChangePct: nullableNumber,
supportTicketsChangePct: nullableNumber,
securityThreatsChangePct: nullableNumber,
}),
endpoint: z.object({
ninjaOne: z.object({ deviceCount: z.number(), online: z.number(), offline: z.number() }).nullable(),
huntress: z
.object({
agentCount: z.number(),
threatsBySeverity: z.object({ critical: z.number(), high: z.number(), medium: z.number(), low: z.number() }),
remediatedThreats: z.number(),
})
.nullable(),
}),
backup: z.object({
afi: z
.object({ totalLicenses: z.number(), usedLicenses: z.number(), utilizationPercent: z.number(), backupSizeGB: z.number(), protectedUsers: z.number() })
.nullable(),
}),
cloudflare: z.object({
metrics: z.record(z.string(), z.unknown()).meta({ description: 'Traffic, cache, security and product figures for the period, as the report page shows them.' }),
zones: z.array(z.object({
zoneId: z.string(),
zoneName: z.string(),
status: z.string(),
requests: z.number(),
bandwidth: z.number(),
cacheHitRatio: z.number(),
threats: z.number(),
})),
configuration: z.record(z.string(), z.unknown()).nullable().meta({ description: 'The Cloudflare configuration review (checkup grades and findings), when the report has one.' }),
}),
support: z.object({
issuesCreated: z.number(),
issuesClosed: z.number(),
openIssues: z.number(),
averageResolutionTimeHours: nullableNumber,
issuesByPriority: z.object({ urgent: z.number(), high: z.number(), medium: z.number(), low: z.number() }),
slaCompliancePercent: nullableNumber,
}),
billing: z
.object({
activeContracts: z.number(),
totalContractValue: nullableNumber,
contractCurrency: nullableText,
invoicesInPeriod: z.object({
count: z.number(),
totalAmount: nullableNumber,
currency: nullableText,
paidOnTime: z.number(),
paidLate: z.number(),
}),
upcomingRenewals: z.array(z.object({ contractId: z.string(), name: z.string(), renewalDate: z.string(), value: nullableNumber, currency: nullableText })),
})
.nullable()
.meta({ description: 'Present only when the report has a billing section the caller may see; null for readers without billing access and for customers billed through a partner.' }),
})
.meta({ id: 'ReconReport' });
/** A monthly report or a quarterly business review in the customer's Reports view. */
export const CustomerReport = z
.object({
id: Id,
kind: z.enum(['monthly', 'quarterly']),
period: ReportPeriod,
status: z.string().meta({ description: 'Monthly: pending, generating, completed, failed. Quarterly: draft, published (staff also see drafts).' }),
updatedAt: Timestamp.nullable().meta({ description: 'Monthly: when the report was generated. Quarterly: last change.' }),
isShared: z.boolean().meta({ description: 'A public share link is enabled.' }),
})
.meta({ id: 'CustomerReport' });
// ---------------------------------------------------------------- contracts
export const ContractStatus = z.enum(['draft', 'pending', 'active', 'expired', 'terminated']);
export const ContractLineItem = z
.object({
id: Id,
name: nullableText,
description: nullableText,
serviceId: Id.nullable(),
quantity: nullableNumber,
unitPrice: ContractAmount,
totalPrice: ContractAmount,
includedQuantity: nullableNumber,
overageRate: ContractAmount,
quantityLimit: nullableNumber,
quantityUnit: nullableText,
bandwidthLimitTb: nullableNumber,
requestsLimitMillions: nullableNumber,
isActive: z.boolean(),
})
.meta({ id: 'ContractLineItem' });
export const ContractInvoice = z
.object({
id: Id,
stripeInvoiceId: nullableText,
invoiceNumber: nullableText,
amountDue: ContractAmount,
amountPaid: ContractAmount,
currency: nullableText,
status: nullableText,
invoiceDate: nullableText,
dueDate: nullableText,
paidAt: Timestamp.nullable(),
})
.meta({ id: 'ContractInvoice' });
/**
* A contract. A contract linked to this customer from its partner shows only
* its summary (name, status, dates); its values, line items and invoices are
* the partner's and come back null or empty.
*/
export const Contract = z
.object({
id: Id,
reference: nullableText.meta({ description: 'The human contract number, e.g. C-1001.' }),
name: z.string(),
description: nullableText,
status: nullableText,
isLinked: z.boolean().meta({ description: 'Owned by the partner and linked to this customer: a summary only.' }),
effectiveDate: nullableText,
expirationDate: nullableText,
signedDate: nullableText,
autoRenewal: z.boolean().nullable(),
renewalNoticeDays: z.number().int().nullable(),
billingFrequency: nullableText,
totalValue: ContractAmount,
currency: nullableText,
notes: nullableText.meta({ description: 'Vigilbase’s notes on the contract; null for callers outside Vigilbase.' }),
agreementUrl: nullableText.meta({ description: 'The signed agreement (Common Paper), an https link; null for callers outside Vigilbase.' }),
lineItems: z.array(ContractLineItem),
invoices: z.array(ContractInvoice),
createdAt: Timestamp.nullable(),
updatedAt: Timestamp.nullable(),
})
.meta({ id: 'Contract' });
export const ContractAttachment = z
.object({
id: Id,
fileName: z.string(),
fileSize: z.number().int().nullable(),
mimeType: nullableText,
attachmentType: nullableText,
description: nullableText,
version: z.number().int().nullable(),
isLatest: z.boolean(),
uploadedAt: Timestamp.nullable(),
})
.meta({ id: 'ContractAttachment' });
export const ContractDetail = Contract.extend({ attachments: z.array(ContractAttachment) }).meta({ id: 'ContractDetail' });
export const UsageAlert = z
.object({
contractId: Id,
contractName: z.string(),
serviceName: z.string(),
serviceType: z.string().meta({ description: 'Integration tool, e.g. cloudflare, ninja-one.' }),
usagePercentage: z.number(),
status: z.enum(['warning', 'critical', 'over_limit']),
})
.meta({ id: 'UsageAlert' });
// ---------------------------------------------------------------- billing (Stripe)
export const InvoiceStatus = z.enum(['draft', 'open', 'paid', 'uncollectible', 'void']);
/** A Stripe invoice. Amounts in minor units; links are Stripe's hosted invoice page and PDF. */
export const Invoice = z
.object({
id: z.string(),
number: nullableText,
status: InvoiceStatus.nullable(),
amountDue: MinorUnits,
amountPaid: MinorUnits,
amountRemaining: MinorUnits,
currency: z.string(),
description: nullableText,
subscriptionId: nullableText,
lineCount: z.number().int(),
createdAt: Timestamp,
dueDate: Timestamp.nullable(),
paidAt: Timestamp.nullable(),
hostedInvoiceUrl: nullableText,
invoicePdfUrl: nullableText,
})
.meta({ id: 'Invoice' });
export const SubscriptionItem = z
.object({
id: z.string(),
quantity: z.number().int().nullable(),
price: z.object({
id: z.string(),
nickname: nullableText,
unitAmount: MinorUnits.nullable(),
currency: nullableText,
billingScheme: z.enum(['per_unit', 'tiered']).nullable(),
interval: z.enum(['day', 'week', 'month', 'year']).nullable(),
intervalCount: z.number().int().nullable(),
usageType: z.enum(['licensed', 'metered']).nullable(),
transformQuantity: z.object({ divideBy: z.number().int(), round: z.enum(['up', 'down']) }).nullable(),
}),
product: z.object({ id: nullableText, name: z.string(), description: nullableText }),
})
.meta({ id: 'SubscriptionItem' });
/** A Stripe subscription with its priced items and product names. */
export const Subscription = z
.object({
id: z.string(),
status: z.string(),
description: z.string().meta({ description: 'Product names of the items, comma separated.' }),
currentPeriodStart: Timestamp.nullable(),
currentPeriodEnd: Timestamp.nullable(),
cancelAtPeriodEnd: z.boolean(),
canceledAt: Timestamp.nullable(),
createdAt: Timestamp,
items: z.array(SubscriptionItem),
})
.meta({ id: 'Subscription' });
export const CustomerBilling = z
.object({
isPartnerBilled: z.boolean().meta({ description: 'Billed through the partner: subscriptions and invoices are the partner’s, for this customer’s contracts.' }),
partner: z.object({ id: Id, name: nullableText }).nullable(),
billingContact: z
.object({ name: nullableText, email: nullableText })
.nullable()
.meta({ description: 'Name and email on the Stripe customer; null when billed through a partner or not set up.' }),
monthlyRecurringRevenue: MinorUnits.nullable().meta({ description: 'Recurring revenue per month in minor units, from subscriptions (or contracts when partner-billed).' }),
currency: nullableText,
subscriptions: z.array(Subscription),
invoices: z.array(Invoice),
paymentMethods: z.array(z.object({ id: z.string(), brand: nullableText, last4: nullableText, expMonth: z.number().int().nullable(), expYear: z.number().int().nullable() })),
contractCount: z.number().int().nullable().meta({ description: 'Contracts behind partner billing; null otherwise.' }),
})
.meta({ id: 'CustomerBilling' });
// ---------------------------------------------------------------- operations
const ReportParams = z.object({ customerId: Id, reportId: Id });
const ContractParams = z.object({ customerId: Id, contractId: Id });
export const listReconReports = defineOperation({
id: 'one.reconReports.list',
product: 'one',
version: 'v1',
method: 'GET',
path: '/customers/{customerId}/recon-reports',
summary: 'List monthly security reports',
description: 'The customer’s monthly security (Recon) reports, newest period first.',
tags: ['reports'],
stability: 'beta',
audience: 'customer',
auth: ONE_READ_AUTH,
permissions: ['read:customers'],
pagination: 'cursor',
request: { params: CustomerParams, query: ListQuery },
responses: { 200: page(ReconReportSummary) },
errors: READ_ERRORS,
legacy: [{ host: 'one', path: '/api/customers/{id}/recon/reports' }],
expose: { mcp: 'code-mode', cli: 'customers reports', llms: true },
});
export const getReconReport = defineOperation({
id: 'one.reconReports.get',
product: 'one',
version: 'v1',
method: 'GET',
path: '/customers/{customerId}/recon-reports/{reportId}',
summary: 'Get a monthly security report',
description: 'One monthly security report with its sections. Billing appears only for readers with billing access, and never for a customer billed through a partner.',
tags: ['reports'],
stability: 'beta',
audience: 'customer',
auth: ONE_READ_AUTH,
permissions: ['read:customers'],
request: { params: ReportParams },
responses: { 200: ReconReport },
errors: READ_ERRORS,
legacy: [{ host: 'one', path: '/api/customers/{id}/recon/reports/{reportId}' }],
expose: { mcp: 'code-mode', cli: 'customers report', llms: true },
});
export const listCustomerReports = defineOperation({
id: 'one.customerReports.list',
product: 'one',
version: 'v1',
method: 'GET',
path: '/customers/{customerId}/reports',
summary: 'List reports',
description: 'Monthly security reports and quarterly business reviews together, latest period first. Customers and partners see published quarterly reviews only.',
tags: ['reports'],
stability: 'beta',
audience: 'customer',
auth: ONE_READ_AUTH,
permissions: ['read:customers'],
pagination: 'cursor',
request: { params: CustomerParams, query: ListQuery },
responses: { 200: page(CustomerReport) },
errors: READ_ERRORS,
legacy: [{ host: 'one', path: '/api/customers/{id}/reports' }],
expose: { mcp: 'code-mode', llms: true },
});
export const listContracts = defineOperation({
id: 'one.contracts.list',
product: 'one',
version: 'v1',
method: 'GET',
path: '/customers/{customerId}/contracts',
summary: 'List contracts',
description: 'Contracts the customer owns or that its partner linked to it, newest first. Amounts are null without billing access.',
tags: ['contracts'],
stability: 'beta',
audience: 'customer',
auth: ONE_READ_AUTH,
permissions: ['read:contracts'],
pagination: 'cursor',
request: {
params: CustomerParams,
query: ListQuery.extend({
status: ContractStatus.optional(),
expiringWithinDays: z.coerce.number().int().min(0).max(3650).optional().meta({ description: 'Only contracts expiring between today and this many days ahead.' }),
}),
},
responses: { 200: page(Contract) },
errors: READ_ERRORS,
legacy: [{ host: 'one', path: '/api/customers/{id}/contracts' }],
expose: { mcp: 'code-mode', cli: 'customers contracts', llms: true },
});
export const getContract = defineOperation({
id: 'one.contracts.get',
product: 'one',
version: 'v1',
method: 'GET',
path: '/customers/{customerId}/contracts/{contractId}',
summary: 'Get a contract',
description: 'One contract with its line items, invoices and attachments. Amounts are null without billing access.',
tags: ['contracts'],
stability: 'beta',
audience: 'customer',
auth: ONE_READ_AUTH,
permissions: ['read:contracts'],
request: { params: ContractParams },
responses: { 200: ContractDetail },
errors: READ_ERRORS,
legacy: [{ host: 'one', path: '/api/customers/{id}/contracts/{contractId}' }],
expose: { mcp: 'code-mode', llms: true },
});
export const listUsageAlerts = defineOperation({
id: 'one.usageAlerts.list',
product: 'one',
version: 'v1',
method: 'GET',
path: '/customers/{customerId}/usage-alerts',
summary: 'List contract usage alerts',
description: 'Active contract line items whose usage is near or over the contracted limit, over-limit first.',
tags: ['contracts'],
stability: 'beta',
audience: 'customer',
auth: ONE_READ_AUTH,
permissions: ['read:contracts'],
pagination: 'cursor',
request: { params: CustomerParams, query: ListQuery },
responses: { 200: page(UsageAlert) },
errors: READ_ERRORS,
legacy: [{ host: 'one', path: '/api/customers/{id}/usage-alerts' }],
expose: { mcp: 'code-mode', llms: true },
});
export const getCustomerBilling = defineOperation({
id: 'one.customerBilling.get',
product: 'one',
version: 'v1',
method: 'GET',
path: '/customers/{customerId}/billing',
summary: 'Get billing',
description: 'The customer’s Stripe subscriptions, recent invoices, cards on file and monthly recurring revenue.',
tags: ['billing'],
stability: 'beta',
audience: 'customer',
auth: ONE_READ_AUTH,
permissions: ['read:billing'],
request: { params: CustomerParams },
responses: { 200: CustomerBilling },
errors: [...READ_ERRORS, 'upstream_unavailable'],
legacy: [{ host: 'one', path: '/api/customers/{id}/billing' }],
expose: { mcp: 'code-mode', cli: 'customers billing', llms: true },
});
export const listInvoices = defineOperation({
id: 'one.invoices.list',
product: 'one',
version: 'v1',
method: 'GET',
path: '/customers/{customerId}/invoices',
summary: 'List invoices',
description: 'The customer’s most recent Stripe invoices (up to 100), newest first. A customer billed through a partner sees only the invoices of its own contracts.',
tags: ['billing'],
stability: 'beta',
audience: 'customer',
auth: ONE_READ_AUTH,
permissions: ['read:billing'],
pagination: 'cursor',
request: { params: CustomerParams, query: ListQuery.extend({ status: InvoiceStatus.optional() }) },
responses: { 200: page(Invoice) },
errors: READ_ERRORS,
legacy: [{ host: 'one', path: '/api/customers/{id}/stripe/invoices' }],
expose: { mcp: 'code-mode', cli: 'customers invoices', llms: true },
});
export const listSubscriptions = defineOperation({
id: 'one.subscriptions.list',
product: 'one',
version: 'v1',
method: 'GET',
path: '/customers/{customerId}/subscriptions',
summary: 'List subscriptions',
description: 'The customer’s Stripe subscriptions with priced items. A customer billed through a partner sees only the subscriptions of its own contracts.',
tags: ['billing'],
stability: 'beta',
audience: 'customer',
auth: ONE_READ_AUTH,
permissions: ['read:billing'],
pagination: 'cursor',
request: { params: CustomerParams, query: ListQuery },
responses: { 200: page(Subscription) },
errors: READ_ERRORS,
legacy: [{ host: 'one', path: '/api/customers/{id}/stripe/subscriptions' }],
expose: { mcp: 'code-mode', cli: 'customers subscriptions', llms: true },
});
export const reportsBillingOperations = [
listReconReports,
getReconReport,
listCustomerReports,
listContracts,
getContract,
listUsageAlerts,
getCustomerBilling,
listInvoices,
listSubscriptions,
];