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.
Quick Start
Section titled “Quick Start”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}Module Categories
Section titled “Module Categories”Data Manipulation
Section titled “Data Manipulation”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_chunkmap_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
Cryptography & Security
Section titled “Cryptography & Security”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
Encoding & Decoding
Section titled “Encoding & Decoding”Various encoding and decoding utilities. Supports Base64, Hex, and URL encoding/decoding operations.
Key Functions:
base64Encode,base64Decode,base64UrlEncode,base64UrlDecodehexEncode,hexDecodeurlEncode,urlDecode
Network & Internet
Section titled “Network & Internet”Network and IP address utilities for network-based policies. Supports both IPv4 and IPv6 addresses and CIDR notation.
Key Functions:
cidrContains,cidrIntersects,cidrIsValid,cidrExpand,cidrMergeparseIP,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 & Time
Section titled “Date & Time”Date and time manipulation utilities. All timestamps are Unix timestamps (seconds since epoch).
Key Functions:
now,parse,format,addDuration,subtractDurationisBefore,isAfter,isBetween
Constants:
RFC3339,RFC3339Nano,RFC1123,RFC1123Z,RFC822,RFC822Z
JavaScript Globals
Section titled “JavaScript Globals”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
Pattern Matching
Section titled “Pattern Matching”Regular expression pattern matching and manipulation utilities. All patterns are compiled and cached for performance.
Key Functions:
match,find,findAll,replace,replaceAll,split
Version Management
Section titled “Version Management”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,stripPrefixmajor,minor,patch,prerelease,metadata
Identifiers
Section titled “Identifiers”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)
Complete Module List
Section titled “Complete Module List”| Module | Description | Category |
|---|---|---|
| @sentrie/collection | List and map manipulation utilities | Data Manipulation |
| @sentrie/crypto | Cryptographic functions (SHA-256) | Cryptography |
| @sentrie/encoding | Base64, Hex, and URL encoding/decoding | Encoding |
| @sentrie/hash | Hash functions (MD5, SHA-1, SHA-256, SHA-512, HMAC) | Cryptography |
| @sentrie/js | JavaScript globals (Math, String, Number, Date, JSON, Array) | JavaScript Globals |
| @sentrie/json | JSON validation utility | Data Manipulation |
| @sentrie/jwt | JSON Web Token decoding and verification | Security |
| @sentrie/net | Network and IP address utilities | Network |
| @sentrie/regex | Regular expression pattern matching | Pattern Matching |
| @sentrie/semver | Semantic version comparison and validation | Version Management |
| @sentrie/time | Date and time manipulation | Date & Time |
| @sentrie/url | URL parsing and manipulation | Network |
| @sentrie/uuid | UUID generation (v4, v6, v7) | Identifiers |
Common Use Cases
Section titled “Common Use Cases”Authentication & Authorization
Section titled “Authentication & Authorization”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}Data Validation
Section titled “Data Validation”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}Network Access Control
Section titled “Network Access Control”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}Time-Based Policies
Section titled “Time-Based Policies”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}Import Syntax
Section titled “Import Syntax”All modules use the same import syntax:
use { function1, function2 } from @sentrie/moduleYou can optionally use an alias:
use { function1, function2 } from @sentrie/moduleIf no alias is specified, the default alias is the last part of the module path.
Module Aliasing
Section titled “Module Aliasing”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()Best Practices
Section titled “Best Practices”-
Use appropriate modules - Choose the right module for your use case (e.g., use
@sentrie/hashfor secure hashing instead of@sentrie/crypto) -
Security considerations - Use SHA-256 or SHA-512 for secure hashing. Avoid MD5 and SHA-1 for security-sensitive operations.
-
Performance - Regex patterns are compiled and cached, so repeated use of the same pattern is efficient.
-
Type safety - All modules provide full TypeScript type definitions for better error detection and IntelliSense support.
-
Error handling - Most functions throw errors on invalid input. Always validate inputs before calling module functions.
-
Module organization - Use aliases when importing multiple functions from the same module to keep code readable.
See Also
Section titled “See Also”- Using TypeScript - Complete guide to using TypeScript in Sentrie
- Policy Pack Structure - Learn about organizing your policy pack
- Policy Language Reference - Complete reference for the Sentrie policy language