Skip to content

Built-in TypeScript Modules

Sentrie provides a comprehensive set of built-in TypeScript modules for common operations. These modules are available under the @sentrie/* namespace and can be imported using the use statement in your policies.

Import and use built-in modules in your policies:

namespace com/example/mypolicy
policy mypolicy {
use { now } from @sentrie/time
use { sha256 } from @sentrie/hash
use { parse } from @sentrie/js as json
use { isValid } from @sentrie/json as jsonUtil
fact data!: string
fact timestamp!: number
rule processData = default false {
let hash = sha256(data)
let currentTime = now()
let jsonData = json.parse(data)
let isValid = jsonUtil.isValid(data)
yield hash != "" and currentTime > timestamp and isValid
}
export decision of processData
}

List and map manipulation utilities. Functions are prefixed with list_ for array operations and map_ for object operations.

Key Functions:

  • list_includes, list_sort, list_unique, list_chunk
  • map_keys, map_values, map_get, map_merge

Access to JavaScript globals (Math, String, Number, Date, JSON, Array) as individual functions.

Key Functions:

  • Math: round, floor, ceil, max, min, abs, sqrt, pow, sin, cos, tan, etc.
  • String: length, fromCharCode
  • Number: isNaN, parseInt, parseFloat, isFinite, isInteger
  • Date: now, dateParse, UTC
  • JSON: parse, stringify
  • Array: isArray, from, of

JSON validation utility.

Key Functions:

  • isValid - Validates if a string is valid JSON

Comprehensive hash functions including MD5, SHA-1, SHA-256, SHA-512, and HMAC.

Key Functions:

  • md5, sha1, sha256, sha512, hmac

Security Note: MD5 and SHA-1 are cryptographically broken. Use SHA-256 or SHA-512 for secure hashing.

Basic cryptographic utilities including SHA-256 hashing.

Key Functions:

  • sha256

JSON Web Token decoding and verification utilities. Note: This module only decodes and verifies tokens; it does NOT create/generate tokens.

Key Functions:

  • decode, verify, getPayload, getHeader

Supported Algorithms: HS256, HS384, HS512

Various encoding and decoding utilities. Supports Base64, Hex, and URL encoding/decoding operations.

Key Functions:

  • base64Encode, base64Decode, base64UrlEncode, base64UrlDecode
  • hexEncode, hexDecode
  • urlEncode, urlDecode

Network and IP address utilities for network-based policies. Supports both IPv4 and IPv6 addresses and CIDR notation.

Key Functions:

  • cidrContains, cidrIntersects, cidrIsValid, cidrExpand, cidrMerge
  • parseIP, isIPv4, isIPv6, isPrivate, isPublic, isLoopback

URL parsing and manipulation utilities. Note: URL encoding/decoding is provided by the encoding module.

Key Functions:

  • parse, join, getHost, getPath, getQuery, isValid

Date and time manipulation utilities. All timestamps are Unix timestamps (seconds since epoch).

Key Functions:

  • now, parse, format, addDuration, subtractDuration
  • isBefore, isAfter, isBetween

Constants:

  • RFC3339, RFC3339Nano, RFC1123, RFC1123Z, RFC822, RFC822Z

Access to JavaScript globals (Math, String, Number, Date, JSON, Array) as individual functions. This module provides direct access to standard JavaScript functions.

Key Functions:

  • Math: round, floor, ceil, max, min, abs, sqrt, pow, sin, cos, tan, asin, acos, atan, atan2, sinh, cosh, tanh, exp, log, log10, log2, random
  • String: length, fromCharCode
  • Number: isNaN, parseInt, parseFloat, isFinite, isInteger
  • Date: now, dateParse, UTC
  • JSON: parse, stringify
  • Array: isArray, from, of

Constants:

  • E, PI, LN2, LN10, LOG2E, LOG10E, SQRT2, SQRT1_2, MAX_VALUE, MIN_VALUE

Regular expression pattern matching and manipulation utilities. All patterns are compiled and cached for performance.

Key Functions:

  • match, find, findAll, replace, replaceAll, split

Semantic version comparison and validation utilities. Supports the “v” prefix (e.g., "v1.2.3" is equivalent to "1.2.3").

Key Functions:

  • compare, isValid, satisfies, stripPrefix
  • major, minor, patch, prerelease, metadata

Functions for generating UUIDs (Universally Unique Identifiers).

Key Functions:

  • v4() - Random UUID (version 4)
  • v6() - Time-ordered UUID (version 6)
  • v7() - Time-ordered UUID with Unix timestamp (version 7)
ModuleDescriptionCategory
@sentrie/collectionList and map manipulation utilitiesData Manipulation
@sentrie/cryptoCryptographic functions (SHA-256)Cryptography
@sentrie/encodingBase64, Hex, and URL encoding/decodingEncoding
@sentrie/hashHash functions (MD5, SHA-1, SHA-256, SHA-512, HMAC)Cryptography
@sentrie/jsJavaScript globals (Math, String, Number, Date, JSON, Array)JavaScript Globals
@sentrie/jsonJSON validation utilityData Manipulation
@sentrie/jwtJSON Web Token decoding and verificationSecurity
@sentrie/netNetwork and IP address utilitiesNetwork
@sentrie/regexRegular expression pattern matchingPattern Matching
@sentrie/semverSemantic version comparison and validationVersion Management
@sentrie/timeDate and time manipulationDate & Time
@sentrie/urlURL parsing and manipulationNetwork
@sentrie/uuidUUID generation (v4, v6, v7)Identifiers
namespace com/example/auth
policy authentication {
use { sha256, hmac } from @sentrie/hash
use { decode, verify } from @sentrie/jwt
use { base64Decode } from @sentrie/encoding
fact token!: string
fact secretKey!: string
fact passwordInput!: string
fact expectedHash!: string
rule verifyToken = default false {
let isValid = jwt.verify(token, secretKey)
yield isValid
}
rule verifyPassword = default false {
let hash = hash.sha256(passwordInput)
yield hash == expectedHash
}
export decision of verifyToken
export decision of verifyPassword
}
namespace com/example/validation
policy validation {
use { match } from @sentrie/regex
use { length } from @sentrie/js as str
use { isValid } from @sentrie/json as jsonUtil
fact email!: string
fact jsonData!: string
rule validateEmail = default false {
let emailPattern = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"
let emailLength = str.length(email)
yield regex.match(emailPattern, email) and emailLength > 0
}
rule validateJson = default false {
yield jsonUtil.isValid(jsonData)
}
export decision of validateEmail
export decision of validateJson
}
namespace com/example/network
policy network {
use { cidrContains, isPrivate, parseIP } from @sentrie/net
use { getHost, isValid } from @sentrie/url
fact clientIp!: string
fact allowedCidr!: string
fact requestUrl!: string
rule checkAccess = default false {
let ip = net.parseIP(clientIp)
let isAllowed = net.cidrContains(allowedCidr, clientIp)
let isNotPrivate = not net.isPrivate(clientIp)
yield ip != null and isAllowed and isNotPrivate
}
rule validateUrl = default false {
let isValidUrl = url.isValid(requestUrl)
let host = url.getHost(requestUrl)
yield isValidUrl and host != ""
}
export decision of checkAccess
export decision of validateUrl
}
namespace com/example/time
policy time {
use { now, isBefore, addDuration, format } from @sentrie/time
fact tokenExpiry!: number
fact sessionStart!: number
rule checkTokenExpiry = default false {
let currentTime = time.now()
let isExpired = time.isBefore(tokenExpiry, currentTime)
yield not isExpired
}
rule checkSessionTimeout = default false {
let currentTime = time.now()
let sessionTimeout = time.addDuration(sessionStart, "1h")
let isExpired = time.isBefore(sessionTimeout, currentTime)
yield not isExpired
}
export decision of checkTokenExpiry
export decision of checkSessionTimeout
}

All modules use the same import syntax:

use { function1, function2 } from @sentrie/module

You can optionally use an alias:

use { function1, function2 } from @sentrie/module

If no alias is specified, the default alias is the last part of the module path.

When importing from a module, the default alias is the last part of the module path:

use { now } from @sentrie/time
-- Default alias is "time" (last part of @sentrie/time)
-- Use as: time.now()
  1. Use appropriate modules - Choose the right module for your use case (e.g., use @sentrie/hash for secure hashing instead of @sentrie/crypto)

  2. Security considerations - Use SHA-256 or SHA-512 for secure hashing. Avoid MD5 and SHA-1 for security-sensitive operations.

  3. Performance - Regex patterns are compiled and cached, so repeated use of the same pattern is efficient.

  4. Type safety - All modules provide full TypeScript type definitions for better error detection and IntelliSense support.

  5. Error handling - Most functions throw errors on invalid input. Always validate inputs before calling module functions.

  6. Module organization - Use aliases when importing multiple functions from the same module to keep code readable.