budibase/packages/backend-core/src/utils/utils.ts

240 lines
6.4 KiB
TypeScript
Raw Normal View History

import { getAllApps } from "../db"
2023-05-08 13:42:26 +02:00
import { Header, MAX_VALID_DATE, DocumentType, SEPARATOR } from "../constants"
import env from "../environment"
import * as tenancy from "../tenancy"
import * as context from "../context"
import {
App,
AuditedEventFriendlyName,
Ctx,
Event,
TenantResolutionStrategy,
} from "@budibase/types"
import { SetOption } from "cookies"
2021-04-11 12:35:55 +02:00
const jwt = require("jsonwebtoken")
const APP_PREFIX = DocumentType.APP + SEPARATOR
2022-03-23 17:45:06 +01:00
const PROD_APP_PREFIX = "/app/"
const BUILDER_PREVIEW_PATH = "/app/preview"
const BUILDER_PREFIX = "/builder"
const BUILDER_REFERER_PREFIX = `${BUILDER_PREFIX}/app/`
const PUBLIC_API_PREFIX = "/api/public/v1"
function confirmAppId(possibleAppId: string | undefined) {
return possibleAppId && possibleAppId.startsWith(APP_PREFIX)
? possibleAppId
: undefined
}
export async function resolveAppUrl(ctx: Ctx) {
2022-03-23 17:45:06 +01:00
const appUrl = ctx.path.split("/")[2]
let possibleAppUrl = `/${appUrl.toLowerCase()}`
let tenantId: string | null = context.getTenantId()
if (env.MULTI_TENANCY) {
// always use the tenant id from the subdomain in multi tenancy
// this ensures the logged-in user tenant id doesn't overwrite
// e.g. in the case of viewing a public app while already logged-in to another tenant
tenantId = tenancy.getTenantIDFromCtx(ctx, {
includeStrategies: [TenantResolutionStrategy.SUBDOMAIN],
})
2022-03-23 17:45:06 +01:00
}
// search prod apps for a url that matches
Per user pricing (#10378) * Update pro version to 2.4.44-alpha.9 (#10231) Co-authored-by: Budibase Staging Release Bot <> * Track installation and unique tenant id on licence activate (#10146) * changes and exports * removing the extend * Lint + tidy * Update account.ts --------- Co-authored-by: Rory Powell <rory.codes@gmail.com> Co-authored-by: mike12345567 <me@michaeldrury.co.uk> * Type updates for loading new plans (#10245) * Add new quota for max users on free plan * Split available vs purchased plan & price type definitions. Update usages of available prices and plans * Type fixes * Add types for minimums * New `PlanModel` type for `PER_USER` and `DAY_PASS` (#10247) * Add new quota for max users on free plan * Split available vs purchased plan & price type definitions. Update usages of available prices and plans * Type fixes * Add types for minimums * New `PlanModel` type for `PER_USER` and `DAY_PASS` * Add loadEnvFiles to lerna config for run command to prevent local test failures * Fix types in license test structure * Add quotas integration to user create / delete + migration (#10250) * Add new quota for max users on free plan * Split available vs purchased plan & price type definitions. Update usages of available prices and plans * Type fixes * Add types for minimums * New `PlanModel` type for `PER_USER` and `DAY_PASS` * Add loadEnvFiles to lerna config for run command to prevent local test failures * Fix types in license test structure * Add quotas integration to user create / delete * Always sync user count from view total_rows value for accuracy * Add migration to sync users * Add syncUsers.spec.ts * Lint * Types and structures for user subscription quantity sync (#10280) * Add new quota for max users on free plan * Split available vs purchased plan & price type definitions. Update usages of available prices and plans * Type fixes * Add types for minimums * New `PlanModel` type for `PER_USER` and `DAY_PASS` * Add loadEnvFiles to lerna config for run command to prevent local test failures * Fix types in license test structure * Add quotas integration to user create / delete * Always sync user count from view total_rows value for accuracy * Add migration to sync users * Add syncUsers.spec.ts * Prevent old installs from activating, track install info via get license request instead of on activation. * Add usesInvoicing to PurchasedPlan * Add min/max users to PurchasedPlan * Additional test structures for generating a license, remove maxUsers from PurchasedPlan - this is already present in the license quotas * Stripe integration for monthly prorations on annual plans * Integrate annual prorations with test clocks * Updated types, test utils and date processing for licensing (#10346) * Add new quota for max users on free plan * Split available vs purchased plan & price type definitions. Update usages of available prices and plans * Type fixes * Add types for minimums * New `PlanModel` type for `PER_USER` and `DAY_PASS` * Add loadEnvFiles to lerna config for run command to prevent local test failures * Fix types in license test structure * Add quotas integration to user create / delete * Always sync user count from view total_rows value for accuracy * Add migration to sync users * Add syncUsers.spec.ts * Prevent old installs from activating, track install info via get license request instead of on activation. * Add usesInvoicing to PurchasedPlan * Add min/max users to PurchasedPlan * Additional test structures for generating a license, remove maxUsers from PurchasedPlan - this is already present in the license quotas * Stripe integration for monthly prorations on annual plans * Integrate annual prorations with test clocks * Updated types, test utils and date processing * Lint * Pricing/billing page (#10353) * bbui updates for billing page * Require all PlanTypes in PlanMinimums for compile time safety * fix test package utils * Incoming user limits warnings (#10379) * incoming user limits warning * fix inlinealert button * add corretc button link and text to user alert * pr comments * simplify limit check * Types and test updates for subscription quantity changes in account-portal (#10372) * Add chance extensions for `arrayOf`. Update events spies with license events * Add generics to doInTenant response * Update account structure with quota usage * User count limits (#10385) * incoming user limits warning * fix inlinealert button * add corretc button link and text to user alert * pr comments * simplify limit check * user limit messaging on add users modal * user limit messaging on import users modal * update licensing store to be more generic * some styling updates * remove console log * Store tweaks * Add startDate to Quota type --------- Co-authored-by: Rory Powell <rory.codes@gmail.com> * Lint * Support custom lock options * Reactivity fixes for add user modals * Update ethereal email creds * Add warn for getting invite from code error * Extract disabling user import condition * Handling unlimited users in modals logic and adding start date processing to store * Lint * Integration testing fixes (#10389) * lint --------- Co-authored-by: Mateus Badan de Pieri <mateuspieri@gmail.com> Co-authored-by: mike12345567 <me@michaeldrury.co.uk> Co-authored-by: Peter Clement <PClmnt@users.noreply.github.com>
2023-04-24 10:31:48 +02:00
const apps: App[] = await context.doInTenant(
tenantId,
() => getAllApps({ dev: false }) as Promise<App[]>
2022-03-23 17:45:06 +01:00
)
const app = apps.filter(
a => a.url && a.url.toLowerCase() === possibleAppUrl
)[0]
return app && app.appId ? app.appId : undefined
}
2022-09-06 13:25:57 +02:00
export function isServingApp(ctx: Ctx) {
2022-09-06 13:25:57 +02:00
// dev app
if (ctx.path.startsWith(`/${APP_PREFIX}`)) {
return true
}
// prod app
if (ctx.path.startsWith(PROD_APP_PREFIX)) {
return true
}
return false
}
2022-03-23 17:45:06 +01:00
export function isServingBuilder(ctx: Ctx): boolean {
return ctx.path.startsWith(BUILDER_REFERER_PREFIX)
}
export function isServingBuilderPreview(ctx: Ctx): boolean {
return ctx.path.startsWith(BUILDER_PREVIEW_PATH)
}
export function isPublicApiRequest(ctx: Ctx): boolean {
return ctx.path.startsWith(PUBLIC_API_PREFIX)
}
/**
* Given a request tries to find the appId, which can be located in various places
* @param {object} ctx The main request body to look through.
* @returns {string|undefined} If an appId was found it will be returned.
*/
export async function getAppIdFromCtx(ctx: Ctx) {
2022-03-23 17:45:06 +01:00
// look in headers
const options = [ctx.request.headers[Header.APP_ID]]
let appId
for (let option of options) {
appId = confirmAppId(option as string)
if (appId) {
break
}
}
2022-03-23 17:45:06 +01:00
// look in body
if (!appId && ctx.request.body && ctx.request.body.appId) {
appId = confirmAppId(ctx.request.body.appId)
}
2022-03-23 17:45:06 +01:00
// look in the path
const pathId = parseAppIdFromUrl(ctx.path)
if (!appId && pathId) {
appId = confirmAppId(pathId)
}
// lookup using custom url - prod apps only
// filter out the builder preview path which collides with the prod app path
// to ensure we don't load all apps excessively
const isBuilderPreview = ctx.path.startsWith(BUILDER_PREVIEW_PATH)
const isViewingProdApp =
ctx.path.startsWith(PROD_APP_PREFIX) && !isBuilderPreview
if (!appId && isViewingProdApp) {
appId = confirmAppId(await resolveAppUrl(ctx))
}
2022-03-23 17:45:06 +01:00
// look in the referer - builder only
// make sure this is performed after prod app url resolution, in case the
// referer header is present from a builder redirect
const referer = ctx.request.headers.referer
if (!appId && referer?.includes(BUILDER_REFERER_PREFIX)) {
const refererId = parseAppIdFromUrl(ctx.request.headers.referer)
appId = confirmAppId(refererId)
2022-03-23 17:45:06 +01:00
}
return appId
}
function parseAppIdFromUrl(url?: string) {
if (!url) {
return
}
return url.split("/").find(subPath => subPath.startsWith(APP_PREFIX))
}
/**
* opens the contents of the specified encrypted JWT.
* @return {object} the contents of the token.
*/
export function openJwt(token: string) {
if (!token) {
return token
}
try {
return jwt.verify(token, env.JWT_SECRET)
} catch (e) {
if (env.JWT_SECRET_FALLBACK) {
// fallback to enable rotation
return jwt.verify(token, env.JWT_SECRET_FALLBACK)
} else {
throw e
}
}
}
export function isValidInternalAPIKey(apiKey: string) {
if (env.INTERNAL_API_KEY && env.INTERNAL_API_KEY === apiKey) {
return true
}
// fallback to enable rotation
if (
env.INTERNAL_API_KEY_FALLBACK &&
env.INTERNAL_API_KEY_FALLBACK === apiKey
) {
return true
}
return false
}
2021-04-11 12:35:55 +02:00
/**
* Get a cookie from context, and decrypt if necessary.
* @param {object} ctx The request which is to be manipulated.
* @param {string} name The name of the cookie to get.
*/
export function getCookie(ctx: Ctx, name: string) {
const cookie = ctx.cookies.get(name)
2021-04-11 12:35:55 +02:00
if (!cookie) {
return cookie
}
2021-04-11 12:35:55 +02:00
return openJwt(cookie)
2021-04-11 12:35:55 +02:00
}
/**
2021-07-06 19:10:04 +02:00
* Store a cookie for the request - it will not expire.
* @param {object} ctx The request which is to be manipulated.
* @param {string} name The name of the cookie to set.
* @param {string|object} value The value of cookie which will be set.
2021-12-03 13:39:20 +01:00
* @param {object} opts options like whether to sign.
*/
export function setCookie(
ctx: Ctx,
value: any,
name = "builder",
opts = { sign: true }
) {
2021-12-03 13:39:20 +01:00
if (value && opts && opts.sign) {
value = jwt.sign(value, env.JWT_SECRET)
2021-09-29 14:51:33 +02:00
}
2021-09-28 17:35:31 +02:00
const config: SetOption = {
2021-12-03 13:39:20 +01:00
expires: MAX_VALID_DATE,
2021-09-29 14:51:33 +02:00
path: "/",
httpOnly: false,
overwrite: true,
}
2021-09-28 17:35:31 +02:00
2022-04-08 02:28:22 +02:00
if (env.COOKIE_DOMAIN) {
config.domain = env.COOKIE_DOMAIN
}
2021-09-29 14:51:33 +02:00
ctx.cookies.set(name, value, config)
}
/**
* Utility function, simply calls setCookie with an empty string for value
*/
export function clearCookie(ctx: Ctx, name: string) {
setCookie(ctx, null, name)
}
/**
* Checks if the API call being made (based on the provided ctx object) is from the client. If
* the call is not from a client app then it is from the builder.
* @param {object} ctx The koa context object to be tested.
* @return {boolean} returns true if the call is from the client lib (a built app rather than the builder).
*/
export function isClient(ctx: Ctx) {
return ctx.headers[Header.TYPE] === "client"
}
export function timeout(timeMs: number) {
return new Promise(resolve => setTimeout(resolve, timeMs))
}
export function isAudited(event: Event) {
return !!AuditedEventFriendlyName[event]
}