Package Exports
- @trap_stevo/star-vault
Readme
π Star-Vault
Unleash the future of data management with the ultimate platform for secure, scalable, and dynamic data operations. Power the next generation of applications by combining advanced encryption, revolutionary real-time querying, and seamless synchronization to create an ecosystem where data transforms into action.
π Features
- π Optional Encryption β Secure sensitive data at rest
- βοΈ Sharded Storage Engine β Efficiently scales writes across shards
- π§ In-Memory Caching β High-speed read layer with
StarCache
- π Write-Ahead Logging β Resilient logs with rotation and retention policies
- π Advanced Query Engine β Chainable and expressive queries with filtering, search, sorting, and spatial support
- π Real-Time Event Emission β Listen to data changes with fine-grained control
- π‘οΈ Authentication Layer β Optional handler to authorize every operation
- π Collection Wildcards β Seamlessly operate across multiple collections
βοΈ System Requirements
Requirement | Version |
---|---|
Node.js | β₯ 19.x |
npm | β₯ 9.x (recommended) |
OS | Windows, macOS, Linux |
π API Specifications
π§ Constructor
Use these parameters when initializing StarVault
.
new StarVault(dbPath, logPath, shardCount, maxLogSize, logRetention, options)
Core Parameters
Key | Description | Default |
---|---|---|
dbPath |
Root directory for all collection data; each collection is stored in sharded files. | Required |
logPath |
Directory where write-ahead logs (WAL) are stored for durability and replay. | Required |
shardCount |
Number of shards used per collection. More shards improve concurrency. | 4 |
maxLogSize |
Max size of each WAL file before rotation. Accepts values like "100MB" . |
"869MB" |
logRetention |
Duration to retain old WAL files. Accepts values like "1w" or "30d" . |
"1w" |
options
Object
Key | Description | Default |
---|---|---|
enableEncryption |
Enables encryption for data at rest. | false |
vaultPath |
Path to the vault metadata file used for encryption. | "./star-vault.json" |
masterKey |
Master encryption key for vault encryption. Must securely generate/store. | null |
authHandler |
Custom function that receives clientAuth and returns true /false . |
null |
authOptions |
Configuration object passed to internal StarAuth for authentication. |
{} |
auditHistory |
Turn on default auditing for history/timeline reads (writes entries to audit.log ). Also toggle per call. |
false |
enableMesh |
Turn on StarMesh sync layer. | false |
meshOptions |
Options passed to StarMesh when enableMesh = true . |
{} |
dirMode |
UNIX permission mode for directories (e.g., 0o700 ). |
0o700 |
fileMode |
UNIX permission mode for files (e.g., 0o600 ). |
0o600 |
π authOptions (StarAuth Configuration)
Pass this object under the options.authOptions
key when creating your StarVault
instance.
Collection Settings
Key | Description | Default |
---|---|---|
collection |
User collection name | "auth-users" |
sessionCollection |
Session tracking collection | "auth-sessions" |
resetCollection |
Password reset token collection | "auth-resets" |
lockCollection |
Lockout state tracking collection (per account/IP/UA). | "auth-locks" |
stellarCollection |
Magic link / code token collection | "stellar-auths" |
Session Behavior
These options control the creation, validation, and protection of sessions against brute-force attacks.
Key | Description | Default |
---|---|---|
tokenExpiry |
Lifetime of each session token in seconds. | 3600 (1 hour) |
sessionValidationFields |
Fields compared on every request to detect hijacking (e.g. IP, fingerprint). | ["ip", "fingerprint"] |
strictSessionValidation |
If true , any mismatch in validation fields invalidates the session. |
true |
enableSuspiciousCheck |
If true , compares geo/IP against recent sessions to flag anomalies. |
true |
sessionPolicy |
Session strategy: "default" (allow many), "strict" (1 active max), "replace" (replace old). |
"default" |
π Lockout Configuration
Controls the tracking, weighting, and escalation behavior of failed login attempts.
All options go inside options.authOptions.lockout
.
Key | Description | Default |
---|---|---|
strategy |
Lockout algorithm: "fixed" , "slidingWindow" , or "exponential" . |
"fixed" |
scopes |
Dimensions to track failures against: ["account", "ip", "ipua"] . |
["account", "ipua"] |
maxAttempts |
Failures allowed before triggering lock. | 5 |
baseDuration |
Base lockout duration in ms. | 15 * 60 * 1000 |
maxDuration |
Max lockout duration in ms (for exponential strategy). | 24 * 60 * 60 * 1000 |
minDuration |
Absolute minimum lock duration in ms (applies to all strategies; jitter wonβt go below this). | 30 * 1000 |
jitterDuration |
Random jitter Β± ms added to lock duration. | 15 * 1000 |
decayDuration |
Auto-decay failures if no attempts within this duration. | 30 * 60 * 1000 |
windowDuration |
For slidingWindow , the rolling time window in ms. |
10 * 60 * 1000 |
windowThreshold |
For slidingWindow , number of failures in the window that triggers lock. |
7 |
windowGrowth |
For slidingWindow , how lock duration grows when over threshold: "none" | "linear" | "exponential" . |
"none" |
windowGrowthFactor |
For slidingWindow: "exponential" β multiplier per extra failure over threshold. |
2 |
windowGrowthStep |
For slidingWindow: "linear" β extra ms per extra failure over threshold. |
baseDuration / 2 |
captchaAfter |
Number of failures after which a CAPTCHA challenge is required. | null |
otpAfter |
Number of failures after which an OTP challenge is required. | null |
captchaVerifier |
Function (req) => boolean to validate CAPTCHA. |
null |
otpVerifier |
Function ({ email, code }) => boolean to validate OTP. |
null |
onLock |
Callback (info) => void fired when a lock is applied. |
null |
onUnlock |
Callback (info) => void fired when a lock is cleared. |
null |
onChallenge |
Callback (info) => void fired when a CAPTCHA/OTP challenge is required. |
null |
notifyLock |
Optional notifier (info) => void for alerts/logging. |
null |
bypassed |
Function (req) => boolean to completely bypass lockout logic for trusted requests. |
null |
Timing Heuristics
options.authOptions.lockout.timingHeuristics
adds intelligence by classifying failures as bursts, normal, or human-like delays.
Key | Description | Default |
---|---|---|
enabled |
Enable timing heuristics. | true |
burstDetectionDuration |
Attempts within this ms count as a burst (weighted more). | 3000 |
humanDetectionDuration |
Attempts slower than this ms count as human/grace. | 45000 |
maxConsiderDuration |
Ignore intervals longer than this ms. | 600000 |
burstWeight |
Weight applied to burst failures. | 2.0 |
normalWeight |
Weight applied to normal failures. | 1.0 |
graceWeight |
Weight applied to grace (slow) failures. | 0.0 |
emaAlpha |
Alpha for exponential moving average of attempt intervals. | 0.3 |
decayOnGrace |
Whether to decay counters when a grace attempt is detected. | true |
decayStep |
How many failures to subtract during a grace decay. | 1 |
minFailures |
Clamp: minimum number of failures tracked. | 0 |
maxFailures |
Clamp: maximum number of failures tracked. | 9999 |
Example Fixed Lockout Config
authOptions: {
lockout: {
strategy: "fixed",
scopes: ["account", "ipua"],
maxAttempts: 5, // lock after N total failures
baseDuration: 15 * 60 * 1000, // fixed lock duration (with jitter)
minDuration: 30 * 1000,
jitterDuration: 15 * 1000, // desync scripted retries
decayDuration: 30 * 60 * 1000, // clear counters after idle period
// Optional human gates
captchaAfter: 3,
otpAfter: null,
captchaVerifier: async (req) => verifyCaptcha(req.body.token),
// Heuristics amplify bursts, forgive human pace
timingHeuristics: {
enabled: true,
burstDetectionDuration: 3000,
humanDetectionDuration: 45000,
burstWeight: 2.0,
normalWeight: 1.0,
graceWeight: 0.0,
emaAlpha: 0.3,
decayOnGrace: true,
decayStep: 1,
minFailures: 0,
maxFailures: 9999
},
onLock: (info) => console.log("LOCKED", info),
onUnlock: (info) => console.log("UNLOCKED", info),
onChallenge: (info) => console.log("CHALLENGE", info),
bypassed: (req) => false
}
}
π When to use: Simple setups where predictability matters. Good for smaller apps, prototypes, or admin dashboards where you want consistent enforcement.
Example Sliding Window Lockout Config
authOptions: {
lockout: {
strategy: "slidingWindow",
scopes: ["account", "ipua"],
windowDuration: 10 * 60 * 1000,
windowThreshold: 7,
baseDuration: 60 * 1000,
minDuration: 30 * 1000,
maxDuration: 24 * 60 * 60 * 1000,
jitterDuration: 15 * 1000,
windowGrowth: "exponential",
windowGrowthFactor: 2,
// windowGrowthStep: 30 * 1000, // if using "linear"
// Optional Human gates
captchaAfter: 3,
otpAfter: null,
captchaVerifier: async (req) => verifyCaptcha(req.body.token),
// Heuristics amplify bursts, forgive human pace
timingHeuristics: {
enabled: true,
burstDetectionDuration: 2000,
humanDetectionDuration: 45000,
burstWeight: 2.5,
normalWeight: 1.0,
graceWeight: 0.0,
emaAlpha: 0.35,
decayOnGrace: true,
decayStep: 1,
minFailures: 0,
maxFailures: 9999
},
onLock: (info) => console.log("LOCKED", info),
onUnlock: (info) => console.log("UNLOCKED", info),
onChallenge: (info) => console.log("CHALLENGE", info),
bypassed: (req) => false
}
}
π When to use: Ideal for games and consumer apps. Itβs forgiving to legit players (counters decay naturally) but still stops brute-force bursts quickly.
Example Exponential Lockout Config
authOptions: {
lockout: {
strategy: "exponential",
scopes: ["account", "ipua"],
maxAttempts: 5,
baseDuration: 30 * 1000,
minDuration: 30 * 1000,
maxDuration: 24 * 60 * 60 * 1000,
jitterDuration: 10 * 1000,
captchaAfter: 3,
otpAfter: 5,
captchaVerifier: async (req) => verifyCaptcha(req.body.token),
otpVerifier: async ({ email, code }) => verifyOtp(email, code),
onLock: (info) => console.log("LOCKED", info),
onUnlock: (info) => console.log("UNLOCKED", info),
timingHeuristics: {
enabled: true,
burstWeight: 3.0,
graceWeight: 0.0,
emaAlpha: 0.4
}
}
}
π When to use: Best for high-security apps, admin portals, or payment flows. Makes repeated brute-forcing impractical, but can be harsh for end-users if tuned too aggressively.
π§ Legacy Lockout
These highlight the original βsimpleβ lockout knobs. They remain in place for backward compatibility and apply in addition to the modern authOptions.lockout
logic.
Key | Description | Default |
---|---|---|
lockoutDuration |
(Legacy) Fixed lock duration (ms) after too many failed logins. | 900000 (15 minutes) |
maxLoginAttempts |
(Legacy) Number of failed attempts before the legacy lockout triggers. | 5 |
How they interact:
- On every failed login, the modern lockout mechanism (if configured) evaluates first.
- The legacy counters also increment and, if
failedAttempts >= maxLoginAttempts
, a fixed lock oflockoutDuration
is applied. - This ensures older deployments keep their original behavior while you migrate to the new model.
Recommendation:
- Prefer the new
authOptions.lockout
settings for fine-grained control. - If you want the legacy lockout to rarely affect users, set a very large
maxLoginAttempts
(e.g.,1_000_000
) and leave modern lockout to do the real work.
Example (modern lockout active, legacy effectively neutralized):
authOptions: {
// Modern lockout (recommended)
lockout: {
strategy: "exponential",
scopes: ["account", "ipua"],
maxAttempts: 5,
baseDuration: 15 * 60 * 1000, // 15 minutes
maxDuration: 24 * 60 * 60 * 1000 // 24 hours
// ...captcha/otp/timingHeuristics, etc.
},
maxLoginAttempts: 5,
lockoutDuration: 15 * 60 * 1000
}
Password Management
Key | Description | Default |
---|---|---|
passwordRequirements |
Object defining the password policy | { minLength: 8, requireLetter: true, requireNumber: true, requireSymbol: false } |
β minLength |
Minimum number of characters required | 8 |
β requireLetter |
Requires at least one letter (a-z or A-Z) | true |
β requireNumber |
Requires at least one numeric digit (0-9) | true |
β requireSymbol |
Requires at least one symbol (e.g., !@#$%^&* ) |
false |
β customValidator |
Optional custom function (password) => boolean for advanced password checks |
null |
lockingCombinations |
Password hash complexity | 10 |
π Star Locator Configuration
Key | Description | Default |
---|---|---|
enableGeo |
Enable geo lookups. | false |
enableReverseGeo |
Reverse geocode coordinates. | false |
enableGeoDebug |
Log provider results. | false |
geoProviders |
Extra providers (ip, {signal}) => result . |
[] |
ipgeolocationKey |
ipgeolocation.io key. | null |
ipinfoToken |
ipinfo.io token. | null |
nominatimUserAgent |
UA for Nominatim reverse geo. | "StarAuth/1.0 (star-vault@sclpowerful.com)" |
googleMapsKey |
Google Geocoding key. | null |
mapboxToken |
Mapbox token. | null |
geoCacheTtlMs |
Cache TTL. | 600000 |
geoDeadlineMs |
Deadline per lookup. | 3000 |
geoTimeoutMs |
Timeout per provider. | 2500 |
geoScoreOk |
Early-accept score threshold. | 5 |
geoMaxConcurrency |
Max concurrent calls. | 8 |
Example geo
Object in Sessions
geo: {
requestIP: "203.0.113.45",
ip: "203.0.113.45",
city: "City",
region: "Region",
country: "Country",
continent: "Continent",
org: "Org / ASN",
isp: "ISP",
loc: "12.3456,-98.7654",
timezone: "Area/City",
postal: "ZIP",
flag: "π",
confidence: 0.83,
geoAddress: "123 Main St, Example City, Country"
}
Custom Provider Registration
const vault = new StarVault(dataDir, logDir, 4, "869MB", "1w", {
authOptions: {
enableGeo: true,
enableReverseGeo: true,
ipinfoToken: process.env.IPINFO_TOKEN,
geoProviders: [
async function customProvider(ip, { signal }) {
return { city: "Custom City", country: "Customland" };
}
]
}
});
Stellar Login
Key | Description | Default |
---|---|---|
stellarRequestCooldown |
Minimum delay between stellar requests | 60000 (1 min) |
generateStellarCode |
Function to generate a stellar numeric code | 6-digit default |
Hooks & Extensions
Key | Description |
---|---|
onSuspiciousSession |
(currentSession, pastSession) => void |
handleHijack |
(session, field, expected, actual) => void |
onCleanup |
({ result, timestamp, vaultID }) => void |
tagSession |
(session, userData) => string[] |
Guest Session Configurations
Key | Description | Default |
---|---|---|
allowGuestSessions |
Enables or disables guest session support. | true |
guestInactivityThreshold |
Duration of inactivity (in ms) before considering a guest account stale. | 7 * 24 * 60 * 60 * 1000 (1w) |
cleanupGuestInterval |
Interval (in ms) to check for inactive guest accounts. | 5 * 60 * 1000 (5m) |
guestActivityTrackers |
Array of custom functions to execute on guest activity updates. | [] |
generateGuestID |
Function to generate guest user IDs. | () => "guest-" + UUID |
Cleanup & Locking
Key | Description | Default |
---|---|---|
vaultID |
ID for this vault instance | null |
autoCleanupInterval |
How often to auto-clean expired tokens | null |
expiredSessionCleanupInterval |
Interval for cleaning expired sessions | null |
cleanupExpiredTokensActionInfo |
Metadata for cleanup activity | {} |
cleanupExpiredTokensClientAuth |
Auth context used for cleanup calls | null |
cleanupExpiredSessionsActionInfo |
Metadata for session cleanup | {} |
cleanupExpiredSessionsClientAuth |
Auth context used during session cleanup | null |
π¦ Core Methods
The primary database interaction methods.
Method | Description | Sync/Async |
---|---|---|
create(collection, data, actionInfo = {}, clientAuth = null) |
Creates a new record in the specified collection. Returns the created record object. | β Sync |
update(collection, id, updates, actionInfo = {}, clientAuth = null) |
Updates an existing record by ID. Setting record data properties to undefined removes them respectively. Returns the updated record. Throws error if not found. | β Sync |
unset(collection, id, dotPaths = [], actionInfo = {}, clientAuth = null) |
Removes specific nested fields using dot notation (e.g., "profile.stats.xp"). Returns updated record. | β Sync |
deleteCollection(collection, actionInfo = {}, clientAuth = null) |
Deletes an entire collection. Returns { wholeCollection: true, deleted: true/false } . |
β Sync |
deleteRecord(collection, id, actionInfo = {}, clientAuth = null) |
Deletes a specific record by ID. Returns { id, deleted: true/false } . |
β Sync |
delete(collection, id, actionInfo = {}, clientAuth = null) |
Soft-deletes a record by filtering it out and overwriting the collection. Returns { id, deleted: true } . |
β Sync |
softDelete(collection, id, { reason = "soft-delete", deletedBy = null } = {}, actionInfo = {}, clientAuth = null) |
Mark a record as deleted without removing it. Sets flags: deleted: true , deletedAt , deletedReason , deletedBy . Emits update . Returns { id, softDeleted: true, at, reason, deletedBy } . |
β Sync |
restore(collection, id, { restoredBy = null } = {}, actionInfo = {}, clientAuth = null) |
Reverse a prior soft delete. Clears deleted* flags and sets restoredAt , restoredBy . Emits update . Returns { id, restored: true, at, restoredBy } . |
β Sync |
π§Ύ StarTransactions (WAL + Idempotency)
Star-Vault handles multi-record transactions with staged commits, WAL logging, and per-step idempotency.
Core Traits
- Logs each
TX-BEGIN
andTX-COMMIT
before writing data. - Replays committed groups safely after crash or restart.
- Keeps uncommitted changes isolated until commit.
Transaction Methods
// High-level helper
const { transactionID, result } = await vault.transact({ type: "transfer" }, async (t) => {
await t.update("accounts", "A", { balance: v => v - 100 });
await t.update("accounts", "B", { balance: v => v + 100 });
await t.create("ledger", { from: "A", to: "B", amount: 100, ts: Date.now() });
return "ok";
});
// Manual flow
const tx = await vault.begin({ type: "batch-import" });
await tx.create("users", { id: "u1", name: "Nova" });
await tx.softDelete("posts", "p-123", { reason: "policy", deletedBy: "mod-9" });
await tx.restore("posts", "p-123", { restoredBy: "mod-9" });
await tx.commit(); // or await tx.abort("reason");
Context | Method | Purpose | Sync/Async |
---|---|---|---|
vault | transact(actionInfo, fn) |
Open txn, run fn(tx) , commit on success, abort on failure. Returns { transactionID, result } . |
βοΈ Async |
vault | begin(actionInfo) |
Start txn and return handle { id, create, update, unset, deleteRecord, softDelete, restore, commit, abort } . |
βοΈ Async |
tx | create(collection, data, actionInfo?, clientAuth?) |
Stage record creation. | βοΈ Async |
tx | update(collection, id, updates, actionInfo?, clientAuth?) |
Stage record update; supports function deltas v => v - 50 . |
βοΈ Async |
tx | unset(collection, id, dotPaths = [], actionInfo?, clientAuth?) |
Stage removal of nested fields. | βοΈ Async |
tx | deleteRecord(collection, id, actionInfo?, clientAuth?) |
Stage hard deletion. | βοΈ Async |
tx | softDelete(collection, id, { reason?, deletedBy? } = {}, actionInfo?, clientAuth?) |
Stage soft deletion (flags only). | βοΈ Async |
tx | restore(collection, id, { restoredBy? } = {}, actionInfo?, clientAuth?) |
Stage record restoration. | βοΈ Async |
tx | commit(actionInfo?) |
Apply staged ops, refresh cache, emit events, seal WAL. | βοΈ Async |
tx | abort(reason = "manual") |
Discard staging and log TX-ABORT . |
βοΈ Async |
Idempotency and WAL
- Each step logs internal
transactionID
and deterministicidempotencyKey
. - Steps replay safely on crash recovery; duplicates ignored.
Example Flow
await vault.transact({ actor: "u42" }, async (tx) => {
await tx.create("users", { id: "42", name: "Orion" });
await tx.update("profiles", "42", { visits: v => v + 1 });
await tx.softDelete("sessions", "s-23", { reason: "expired", deletedBy: "system" });
});
π Query Engine
Chainable query builder for filtering and searching collection data.
vault.query("collection")
.whereRecord("id", "value") // Filters root record data by key-value pairs
.where({ key: "value" }) // Filters record data by key-value pairs
.search("field", "text") // Text search within a specific field
.recent("timestamp", "7d") // Gets records from the last 7 days
.near("location", { lat: 0, lng: 0 }, 50) // Geospatial filter within 50 units
.sort({ name: 1 }) // Sorts by a field (1 = asc, -1 = desc)
.select(["id", "name"]) // Selects specific fields
.limit(10) // Limits results
.offset(0) // Skips first N records
.filterBy(record => record.active) // Filters with custom function
.execute(exactCollection = false) // Run the query with optional strict collection matching
Method | Description | Sync/Async |
---|---|---|
query(collection) |
Begins a query on the specified collection. Returns a chainable builder. | β Sync |
whereRecord(criteria) |
Filters records by matching key-value pairs. Accepts both object and parameter inputs. | β Sync |
where(criteria) |
Filters records' data by matching key-value pairs. Accepts both object and parameter inputs. | β Sync |
search(field, text) |
Performs a text search within a specified field. | β Sync |
recent(field, duration) |
Filters records based on recency (e.g., "7d" = 7 days). |
β Sync |
near(field, center, radius) |
Filters based on proximity to a location object { lat, lng } . |
β Sync |
sort(criteria) |
Sorts the results by one or more fields. | β Sync |
select(fields) |
Selects only the specified fields for output. | β Sync |
limit(number) |
Restricts the number of records returned. | β Sync |
offset(number) |
Skips a number of records (used for pagination). | β Sync |
filterBy(fn) |
Filters using a custom function on each record. | β Sync |
callback(fn) |
Adds a side effect or transformation hook before execution. | β Sync |
execute(exactCollection = false) |
Run the query. If true , match only the exact collection name; otherwise, include related subcollections. |
β Sync |
getByID(collection, id) |
Shortcut to retrieve a single record by ID. | β Sync |
range(min, max) |
Static helper to return an inclusive array of numbers in a range. | β Sync |
π‘οΈ Authentication
All methods below require authOptions
configuration and are used for session/user management.
π€ User Registration & Authentication
Method | Description | Sync/Async |
---|---|---|
registerUser(email, password, actionInfo, clientAuth) |
Registers a new user. `. | βοΈ Async |
registerGuestUser(req, metadata, actionInfo, clientAuth) |
Registers a temporary guest user. `. | βοΈ Async |
loginGuestUser(accountID, req, actionInfo, clientAuth) |
Logs in a guest user and creates a session. `. | βοΈ Async |
loginUser(email, password, req, actionInfo, clientAuth) |
Logs in a user and creates a session. `. | βοΈ Async |
resumeUserSession(accountID, req, actionInfo, clientAuth) |
Resumes session from account ID (used for guest linking or session carryover). | βοΈ Async |
upgradeGuestUser(accountID, email, password, actionInfo, clientAuth) |
Converts a guest account to a full registered user. | βοΈ Async |
π°οΈ Session Management
Method | Description | Sync/Async |
---|---|---|
logoutUser(token, actionInfo, clientAuth) |
Logs out a user by invalidating their session token. | β Sync |
extendUserSession(token, ms, actionInfo, clientAuth) |
Extends an active session's duration. | β Sync |
cleanupExpiredAuthTokens(actionInfo, clientAuth) |
Cleans up expired tokens and invalid sessions. | β Sync |
cleanupInactiveGuests(actionInfo, clientAuth) |
Removes or deactivates inactive guest accounts. | βοΈ Async |
π Password & Magic Link Recovery
Method | Description | Sync/Async |
---|---|---|
updateUserPassword(userID, newPassword, actionInfo, clientAuth) |
Updates a user's password. | βοΈ Async |
requestUserPasswordReset(email, actionInfo, clientAuth) |
Sends a password reset token. | βοΈ Async |
resetUserPassword(token, newPassword, actionInfo, clientAuth) |
Resets password using a valid token. | βοΈ Async |
requestUserStellarLink(email, type, actionInfo, clientAuth) |
Sends a Stellar link (magic link or code) for login or verification. | βοΈ Async |
consumeUserStellarToken(token, type, req, actionInfo, clientAuth) |
Consumes a Stellar link/token to verify user and return session. | βοΈ Async |
π₯ Guest Account Management
Method | Description | Sync/Async |
---|---|---|
registerGuestUser(req, metadata, actionInfo, clientAuth) |
Registers a guest session with optional request/metadata. | βοΈ Async |
trackGuestActivity(userID, timestamp, actionInfo, clientAuth) |
Updates guest user's lastActiveAt timestamp. |
βοΈ Async |
upgradeGuestUser(accountID, email, password, actionInfo, clientAuth) |
Promotes a guest to a full registered account. | βοΈ Async |
cleanupInactiveGuests(actionInfo, clientAuth) |
Cleans up inactive or stale guest users based on threshold. | βοΈ Async |
π User Lifecycle Management
Method | Description | Sync/Async |
---|---|---|
updateUser(accountID, updatedMetadata, accountType, actionInfo, clientAuth) |
Updates a user by Account ID. Does not allow for password updates. | βοΈ Async |
deleteUser(userID, reason, actionInfo, clientAuth) |
Soft-deletes a user by ID. | βοΈ Async |
deleteUserByAccountID(accountID, reason, actionInfo, clientAuth) |
Soft-deletes a user using their account ID. | βοΈ Async |
reactivateUser(userID, actionInfo, clientAuth) |
Reactivates a previously deleted user. | βοΈ Async |
reactivateUserByAccountID(accountID, actionInfo, clientAuth) |
Reactivates a deleted user by account ID. | βοΈ Async |
π User & Session Querying
Method | Description | Sync/Async |
---|---|---|
getUserByAccountID(accountID, filter, accountType, actionInfo) |
Retrieves a user by account id. If a certain account type (default ~ guest). | βοΈ Async |
getUser(userID, filter, accountType, actionInfo) |
Retrieves a user by id. If a certain account type (default ~ guest). | βοΈ Async |
getUserSession(sessionID, actionInfo) |
Retrieves a session by id. | βοΈ Async |
listSessions(userID, filters, includeInactive, actionInfo) |
Lists sessions for a specific user. | βοΈ Async |
listAllSessions(filters, includeInactive, actionInfo) |
Lists all sessions across users. | βοΈ Async |
listUsers(filters, options, actionInfo) |
Lists users based on filters and options (pagination, includes). | βοΈ Async |
listUserActivity(options, actionInfo) |
Lists recent activity, including filtering by active, inactive, or recently seen users. | βοΈ Async |
π§© Internal Validation & Utility Methods
The following utility methods get utilized internally across authentication-related flows. You may call them directly for validation, diagnostics, or extension purposes.
Method | Description | Sync/Async |
---|---|---|
validEmail(email) |
Determines if an input email follows proper email address format. | β Sync |
satisfiesPasswordStrength(password) |
Validates whether the password meets the defined passwordRequirements . |
β Sync |
extractSessionMetadata(req) |
Extracts metadata (IP, fingerprint, user agent, etc.) from the request object . | β Sync |
lookupUserGeo(ip) |
Performs geo-IP lookup using built-in and custom geo services . | βοΈ Async |
π§ Record History & Timeline
Star-Vault reconstructs record history and a human-readable timeline from write-ahead logs (WAL). These calls support filtering, integrity checks, and encryption-aware output.
Methods
Method | Description | Sync/Async |
---|---|---|
getRecordHistory(collection, id, options = {}, actionInfo = {}, clientAuth = null) |
Returns detailed event entries for a record (time-ordered). | β Sync |
getRecordTimeline(collection, id, options = {}, actionInfo = {}, clientAuth = null) |
Returns a compact timeline (action, timestamp, brief summary). | β Sync |
options
(history/timeline)
Key | Type | Default | Notes |
---|---|---|---|
includeArchived |
boolean | true |
Include rotated *.archived files when present. |
verifyChecksums |
boolean | true |
Verify each entryβs SHA-256 checksum of data ; skip failures. |
includeSystem |
boolean | true |
Merge related system.log entries for the same collection /id (e.g., DELETE, TX events). |
actions |
string | string[] | undefined |
Allow-list of actions to include (e.g., ["WRITE","UPDATE"] ). Case-insensitive. |
excludeActions |
string | string[] | undefined |
Block-list of actions to exclude (e.g., ["DELETE"] ). Case-insensitive. |
since |
number | string | Date | undefined |
Include entries at/after this time (ms epoch, ISO string, or Date ). |
until |
number | string | Date | undefined |
Include entries at/before this time. |
match |
(row) => boolean | undefined |
Custom predicate that keeps/discards rows after other filters. |
includeDecrypted |
boolean | (defaults to true when a decryptor exists; otherwise false ) |
When true and encryption enabled, decrypt rows and populate dataDecrypted . |
audit |
boolean | undefined |
Per-call audit switch; when true , writes an audit entry (see Auditing). |
βΉοΈ Row shape: history entries include
source
,collection
,action
,id
,timestamp
,client
,data
,checksum
, pluseventID
,transactionID
,idempotencyKey
when present. WithincludeDecrypted
and a decryptor, output also includesdataEncrypted
anddataDecrypted
.
Audit Examples
// Full history (archived segments + checksum verification)
const history = vault.getRecordHistory("users/region1", "1760233994625", {
includeArchived: true,
verifyChecksums: true
}, { actor: "admin-1" }, { token: "valid" });
// Windowed, updates only
const updates = vault.getRecordHistory("users/region1", "1760233994625", {
actions: "UPDATE",
since: Date.now() - 60_000,
until: Date.now()
});
// Compact timeline, no deletions, explicit audit
const timeline = vault.getRecordTimeline("users/region1", "1760233994625", {
excludeActions: ["DELETE", "SOFT_DELETE"]
}, { audit: true }, { token: "valid" });
π§Ύ Auditing (History & Timeline Reads)
History/timeline reads can trigger auditing to audit.log
. Use this for compliance and access tracking.
Control switches
Auditing activates when any of the following holds:
options.audit === true
actionInfo.audit === true
new StarVault(..., { auditHistory: true })
On audit, Star-Vault writes logAudit
with:
action
:"HISTORY_READ"
or"TIMELINE_READ"
details
:{ kind, collection, id, count, filters }
filters
contains a sanitized view of options (booleans/timestamps, allow/block lists, and a flag that notes a custommatch
predicate).
Encryption enabled? The system may encrypt audit entries at rest.
Audit Example: global default
const vault = new StarVault("./data", "./logs", 4, "869MB", "1w", {
auditHistory: true
});
Audit Example: per-call
vault.getRecordHistory("orders", "o-123", { audit: true });
Audit Action names
HISTORY_READ
β written aftergetRecordHistory
completesTIMELINE_READ
β written aftergetRecordTimeline
completes
β οΈ Privacy Notes
- Handling sensitive data? Prefer
includeDecrypted: false
unless the caller truly needs decrypted payloads. - Console snippets show full records for clarity; in production, prefer logging only ids and checksums.
π Starchive (Storage Layer)
Starchive provides a unified storage abstraction for both local filesystem and remote S3-compatible backends.
You can configure it for local only, remote only, or a hybrid (both).
βοΈ Starchive Configuration Modes
Mode | Description | Example |
---|---|---|
Remote (S3) | Store files in any S3-compatible backend (AWS, MinIO, Wasabi, etc.). | starchive: { local: false, remote: { type: "s3", bucket: "mybucket", clientConfig: { region: "us-east-1" } }, defaultTarget: "remote" } |
Local (Filesystem) | Store files locally on disk under a managed .starchive directory. |
starchive: { local: { root: path.join(__dirname, "data", ".starchive") }, remote: false, defaultTarget: "local" } |
Hybrid | Support both local + S3; choose per call via { target: "local" } or { target: "remote" } . |
starchive: { local: { root: path.join(__dirname, "data", ".starchive") }, remote: { type: "s3", bucket: "mybucket", clientConfig: { region: "us-east-1" } }, defaultTarget: "remote" } |
βοΈ Starchive Configurations
Key | Type | Description | Example / Default |
---|---|---|---|
collection |
string | "starchive.files" |
The collection name you desire holding Starchive file records. | "starchive.files" |
local |
object | false |
Local adapter configuration or false to disable. |
{ root: "./data/.starchive" } |
remote |
object | false |
Remote adapter config (type: "s3" , bucket , clientConfig ). |
{ type: "s3", bucket: "mybucket", clientConfig: { region: "us-east-1" } } |
defaultTarget |
"local" | "remote" |
Which backend to use if not explicitly specified. | "local" |
remoteDefaultAlias |
string | null |
Default remote alias when using target: "remote" and no alias is supplied. |
First configured alias |
Remote clientConfig
fields (S3-compatible):
Key | Type | Description | Example |
---|---|---|---|
region |
string | AWS region. | "us-east-1" |
endpoint |
string | S3 endpoint override. | "https://s3.us-east-1.amazonaws.com" |
accessKeyID |
string | Access key ID. | "..." |
secretAccessKey |
string | Secret key. | "..." |
forcePathStyle |
boolean | Use path-style URLs instead of virtual-hosted. | true |
π Remote (S3)
starchive: {
local: false,
remote: {
type: "s3",
bucket: "mybucket",
clientConfig: {
secretAccessKey: ".../...",
accessKeyID: "...",
endpoint: "https://s3.us-east-1.amazonaws.com",
region: "us-east-...",
forcePathStyle: true
}
},
defaultTarget: "remote"
}
Multi-Remote Config Options
You can express remote
as:
Object map of aliases β config
starchive: { local: false, remote: { mediaCDN: { type: "s3", bucket: "media-prod", clientConfig: { region: "us-east-1" } }, logs: { type: "s3", bucket: "app-logs", clientConfig: { region: "us-west-2" } } }, defaultTarget: "remote", remoteDefaultAlias: "mediaCDN" // optional }
Array of remotes (alias inferred from
id
/alias
/bucket
)starchive: { local: false, remote: [ { id: "mediaCDN", type: "s3", bucket: "media-prod", clientConfig: { region: "us-east-1" } }, { alias: "logs", type: "s3", bucket: "app-logs", clientConfig: { region: "us-west-2" } } ], defaultTarget: "remote", remoteDefaultAlias: "mediaCDN" // optional }
βΉοΈ Per call, override the backend with
{ target: "local" }
or{ target: "remote", remoteAlias?: "alias", bucket?: "override-bucket" }
.
π» Local (Filesystem)
starchive: {
local: { root: path.join(__dirname, "data", ".starchive") },
remote: false,
defaultTarget: "local"
}
π Hybrid (Local + Remote)
starchive: {
local: { root: path.join(__dirname, "data", ".starchive") },
remote: {
type: "s3",
bucket: "mybucket",
clientConfig: { region: "us-east-1" }
},
defaultTarget: "remote" // default is S3; override per call with { target: "local" }
}
βΉοΈ Override the default per call with
{ target: "local" }
or{ target: "remote" }
.
π¦ Starchive Core Methods
Method | Description | Sync/Async |
---|---|---|
put({ key, data, target?, remoteAlias?, bucket?, prefix?, absolute?, contentType?, filename?, tags?, encrypt?, extra? }, actionInfo?, clientAuth?) |
Upload a buffer/stream/string. Records metadata (incl. { provider, key, bucket, alias } for S3). |
βοΈ Async |
putFile({ key, path, target?, remoteAlias?, bucket?, prefix?, absolute?, contentType?, filename?, tags?, encrypt?, extra? }, actionInfo?, clientAuth?) |
Upload from a local file path. | βοΈ Async |
putMany(entries, { target?, remoteAlias?, bucket?, concurrency?, prefix?, absolute? }, actionInfo?, clientAuth?) |
Batch upload buffers/files. Returns { complete, incomplete, records, total } . |
βοΈ Async |
getStream(key, { target?, remoteAlias?, bucket?, prefix?, absolute? }) |
Get an object as a readable stream. | βοΈ Async |
getStreamRange(key, start, end, { target?, remoteAlias?, bucket?, prefix?, absolute? }) |
Stream a byte range of an object. | βοΈ Async |
head(key, { target?, remoteAlias?, bucket?, prefix?, absolute? }) |
Get object headers/metadata. | βοΈ Async |
exists(key, { target?, remoteAlias?, bucket?, prefix?, absolute? }) |
Check if an object exists. | βοΈ Async |
remove(key, { target?, remoteAlias?, bucket?, record?, reason?, prefix?, absolute?, actionInfo?, clientAuth? }) |
Delete an object; optionally soft/hard-delete matching records. | βοΈ Async |
removeMany(keys, { target?, remoteAlias?, bucket?, record?, reason?, prefix?, absolute?, actionInfo?, clientAuth? }) |
Delete multiple objects; optionally soft/hard-delete records. | βοΈ Async |
copy(srcKey, dstKey, { target?, remoteAlias?, bucket?, prefix?, absolute? }) |
Copy an object. | βοΈ Async |
move(srcKey, dstKey, { target?, remoteAlias?, bucket?, prefix?, absolute? }) |
Move (copy+delete) an object. | βοΈ Async |
list({ target?, remoteAlias?, bucket?, prefix?, maxKeys?, continuationToken?, startAfter?, timeoutMS? }) |
List objects with pagination. | βοΈ Async |
listAll({ target?, remoteAlias?, bucket?, prefix?, pageSize?, timeoutMS? }) |
List all objects under a prefix. | βοΈ Async |
walk({ target?, remoteAlias?, bucket?, prefix? }) |
Async generator to recursively walk files/prefixes. | βοΈ Async |
βοΈ Starchive Convenience Methods
Method | Description | Sync/Async |
---|---|---|
write(key, data, { target?, remoteAlias?, bucket?, prefix?, absolute?, contentType?, filename?, tags?, extra?, actionInfo?, clientAuth? }) |
Wrapper over put for buffers/strings; infers filename. |
βοΈ Async |
writeText(key, text, opts?) |
Write UTF-8 text (content type set automatically). | βοΈ Async |
writeJSON(key, obj, { pretty?, ...opts }) |
Serialize and write JSON. | βοΈ Async |
read(key, opts?) |
Read entire object into a Buffer . |
βοΈ Async |
readText(key, opts?) |
Read object as UTF-8 string. | βοΈ Async |
readJSON(key, opts?) |
Read and parse JSON (returns null on empty/invalid JSON). |
βοΈ Async |
stat(key, opts?) |
Returns { size, lastModified, contentType } derived from head . |
βοΈ Async |
π°οΈ Remote Management Helpers
Method | Description |
---|---|
listRemotes(opts?) |
Returns the configured remotes. Pass { asObject: true } to get an object keyed by alias. |
getRemoteDefaultAlias() |
Get the current default remote alias. |
setRemoteDefaultAlias(alias) |
Set/switch the default remote alias at runtime. |
π Starchive Signing & Presigning
Method | Description | Sync/Async |
---|---|---|
sign.getDetails(fileID, { method = "GET", expiresInMs = 900000 }) |
Create an internal HMAC signature payload { fileID, method, exp, sig } . |
β Sync |
sign.verify({ id, m, e, s }) |
Verify payload against the current signing key and expiry. | β Sync |
presign.get(key, { target?, remoteAlias?, bucket?, ttlSeconds?, responseContentType?, responseContentDisposition?, timeoutMS?, prefix?, absolute? }) |
Generate S3 presigned GET URL (remote only). | βοΈ Async |
presign.put(key, { target?, remoteAlias?, bucket?, ttlSeconds?, contentType?, cacheControl?, contentDisposition?, tagging?, timeoutMS?, prefix?, absolute? }) |
Generate S3 presigned PUT URL (remote only). | βοΈ Async |
presign.getURL(key, opts?) |
Alias of presign.get . |
βοΈ Async |
presign.putURL(key, opts?) |
Alias of presign.put . |
βοΈ Async |
π Starchive Downloading
Method | Description | Sync/Async |
---|---|---|
download.buffer(key, { target?, remoteAlias?, bucket?, timeoutMS? }) |
Download file to Buffer . |
βοΈ Async |
download.file(key, outPath, { target?, remoteAlias?, bucket?, timeoutMS? }) |
Download file to disk. | βοΈ Async |
π Starchive Records
Method | Description | Sync/Async |
---|---|---|
records.getByID(id, actionInfo?) |
Fetch the stored file record by ID. | β Sync |
records.update(id, updates, actionInfo?, clientAuth?) |
Update metadata fields on a file record. | βοΈ Async |
records.deleteByID(id, { softDelete?, reason? }, actionInfo?, clientAuth?) |
Soft or hard delete a record by ID. | βοΈ Async |
records.deleteByQuery(queryFn, { softDelete?, reason? }, actionInfo?, clientAuth?) |
Delete/soft-delete many records matching a predicate. | βοΈ Async |
π§ Event Listening
Used for reactive, event-driven architecture patterns.
Method | Description | Sync/Async |
---|---|---|
listen(event, nodePath, callback) |
Registers a callback for a specific event (create , update , delete ) at a given path. |
β Sync |
emit(event, nodePath, data) |
Triggers callbacks for listeners whose paths match the emitted path. | β Sync |
π Collection & Path Matching
Utilities for dynamic collection operations and wildcard paths.
Method | Description | Sync/Async |
---|---|---|
getMatchingCollections(basePath) |
Resolves wildcard-based paths like logs/*/2025 to real collection names. |
β Sync |
matchesPath(listenerPath, nodePath) |
Checks if an emitted node path matches a listener's wildcard path. | β Sync |
π StarVault Events
StarVault emits real-time events that let you react to data and authentication lifecycle changes across your app. These include both record-level events and auth lifecycle events.
You can listen to them at multiple levels of granularity:
- π Global listeners (across all collections and records)
- π Collection-level listeners (any record in a collection)
- π§Ύ Record-specific listeners (a specific record path)
π Emitted Record Events (StarVault Core)
Event | Description | Emitted Path |
---|---|---|
create |
Fires on record creation. | collectionName/recordID |
update |
An existing record updated | collectionName/recordID |
delete |
A record got deleted (soft or hard) | collectionName/recordID |
π Emitted Auth Lifecycle Events (StarAuth)
Event | Description |
---|---|
guest:upgraded |
A guest account successfully upgraded to a full user |
guest:updated |
A guest account successfully updated |
user:updated |
A user account successfully updated |
session:resumed |
A user session resumed from a valid token |
user:guestExpired |
A guest account expired due to inactivity |
user:deleted |
A user account got marked for deletion |
user:reactivated |
A previously deleted user got reactivated |
π StarTransaction Lifecycle Events
Event | Description | Payload |
---|---|---|
tx:commit |
Fires after transaction commit and data application. | { count, startedAt, endedAt } |
tx:abort |
Fires when transaction aborts manually or through error. | { reason } |
tx:summary |
Fires after a transaction successfully commits and finalizes all operations. Ideal for analytics, dashboards, or external monitoring. | { transactionID, ops, startedAt, endedAt } |
πͺ Global Listener (All Changes Across Vault)
vault.listen("create", "*", (path, data) => {
console.log("Created:", path, data);
});
vault.listen("update", "*", (path, data) => {
console.log("Updated:", path, data);
});
vault.listen("delete", "*", (path, data) => {
console.log("Deleted:", path, data);
});
π Collection-Level Listener
vault.listen("create", "users/*", (path, data) => {
console.log("User created:", path, data);
});
vault.listen("update", "inventory/*", (path, data) => {
console.log("Inventory updated:", path, data);
});
π§ Record-Specific Listener
vault.listen("update", "orders/12345", (path, data) => {
console.log("Order updated:", data);
});
vault.listen("delete", "accounts/user-abc", (path, data) => {
console.log("User deleted:", data);
});
π― Advanced Wildcard Usage
// Match nested logs by year
vault.listen("update", "logs/*/2025/*", (path, data) => {
console.log("Log updated:", path);
});
π§ Listening to StarAuth Lifecycle Events
Use .on()
to subscribe to StarAuth-specific events:
vault.on("guest:upgraded", (info) => {
console.log("Guest upgraded:", info);
});
vault.on("user:deleted", (info) => {
console.log("User deleted:", info);
});
vault.on("user:reactivated", (info) => {
console.log("User reactivated:", info);
});
π Listening to StarTransaction Lifecycle Events
vault.listen("tx:commit", "*", (id, info) => {
console.log("Committed txn:", id, info);
});
vault.listen("tx:abort", "*", (id, info) => {
console.log("Aborted txn:", id, info);
});
vault.on("tx:summary", (transactionID, summary) => {
console.log("Transaction Summary:", transactionID, summary);
});
These event hooks power real-time dashboards, activity tracking, notifications, and custom automation β all deeply integrated with StarVault's reactive system.
β¨ Getting Started
π¦ Installation
npm install @trap_stevo/star-vault
Basic Usage
const StarVault = require("@trap_stevo/star-vault");
const vault = new StarVault(
"./data",
"./logs",
4,
"869MB",
"1w",
{
enableEncryption : true,
masterKey : "supersecretkey",
authHandler : (auth) => auth.token === "valid-token"
}
);
vault.create("users", { id : "001", name : "Nova" }, { source : "init" }, { token : "valid-token" });
π Querying
const results = vault.query("users")
.where({ role : "admin" })
.sort({ name : 1 })
.select(["id", "name"])
.limit(10)
.execute();
π§ Listening to Changes
vault.listen("create", "*", (path, data) => {
console.log("[CREATE - ANY] Path:", path, data);
});
vault.listen("create", "users/*", (path, data) => {
console.log("[CREATE - users] Path:", path, data);
});
vault.listen("update", "users/*", (path, data) => {
console.log("[UPDATE - users] Path:", path, data);
});
// Listen for updates to a specific user record (e.g., user ID '001')
vault.listen("update", "users/user-001", (path, data) => {
console.log("[UPDATE - users/user-001] Path:", path, data);
});
vault.listen("delete", "users/*", (path, data) => {
console.log("[DELETE - users] Path:", path, data);
});
vault.listen("delete", "logs/*/2025", (path, data) => {
console.log("[DELETE - logs/*/2025] Path:", path, data);
});
// Listen for a specific log record inside a structured path (e.g., logs/server1/2025/log-99)
vault.listen("create", "logs/server1/2025/log-99", (path, data) => {
console.log("[CREATE - logs/server1/2025/log-99] Path:", path, data);
});
// Listen to everything happening in 'auth-sessions'
vault.listen("create", "auth-sessions", (path, data) => {
console.log("[CREATE - auth-sessions] Path:", path, data);
});
vault.listen("update", "auth-sessions", (path, data) => {
console.log("[UPDATE - auth-sessions] Path:", path, data);
});
vault.listen("delete", "auth-sessions", (path, data) => {
console.log("[DELETE - auth-sessions] Path:", path, data);
});
π Wildcard Collection Queries
vault.query("logs/*/2025")
.recent("timestamp", "7d")
.execute();
π₯ Registering Users (Guest and Normal)
const StarVault = require("@trap_stevo/star-vault");
const vault = new StarVault(
"./data",
"./logs",
4,
"869MB",
"1w",
{
enableEncryption : true,
masterKey : "supersecretkey",
authHandler : (auth) => auth.token === "star-vault-demo",
authOptions : {
allowGuestSessions : true,
generateGuestID : () => "guest-" + Math.floor(Math.random() * 1000000)
}
}
);
// Register a full user
const userResult = await vault.registerUser("nova@example.com", "strongpassword123", { source : "site" }, { token : "star-vault-demo" });
console.log("Registered user:", userResult);
// Register a guest user
const guestResult = await vault.registerGuestUser({ ip : "127.0.0.1" }, { referrer : "home" }, { source : "guest-form" }, { token : "star-vault-demo" });
console.log("Registered guest:", guestResult);
π Listing Users and Sessions
const StarVault = require("@trap_stevo/star-vault");
const vault = new StarVault(
"./data",
"./logs",
4,
"869MB",
"1w",
{
enableEncryption : true,
masterKey : "supersecretkey",
authHandler : (auth) => auth.token === "star-vault-demo"
}
);
// List all users
const users = await vault.listUsers({}, { limit : 25 }, { token : "star-vault-demo" });
console.log("All users:", users);
// List all sessions (including inactive and deleted)
const sessions = await vault.listAllSessions({ includeDeleted : "only" }, true, { token : "star-vault-demo" });
console.log("All sessions:", sessions);
// List sessions for a specific user
const userSessions = await vault.listSessions("user-001", { device : "mobile" }, false, { token : "star-vault-demo" });
console.log("Sessions for user-001:", userSessions);
// List recent user activity (active and inactive)
const activity = await vault.listUserActivity({
includeInactive : true,
onlyMostRecent : true
}, { token : "star-vault-demo" });
console.log("User activity:", activity);
π Quick Starchive Examples
1. Store & Retrieve a File
await vault.starchive.putFile({
key: "uploads/photo.png",
path: "./photo.png",
target: "remote"
});
const exists = await vault.starchive.exists("uploads/photo.png");
console.log("Uploaded?", exists);
2. Write and Read JSON
await vault.starchive.writeJSON("configs/app.json", { theme: "dark" });
const cfg = await vault.starchive.readJSON("configs/app.json");
console.log("Loaded config:", cfg);
3. Batch Upload (Buffers + Files)
const results = await vault.starchive.putMany([
{ key: "docs/a.txt", buffer: Buffer.from("Alpha") },
{ key: "docs/b.txt", path: "./local-b.txt" }
], { target: "remote" });
console.log("Completed:", results.complete.length);
4. Presigned Upload (Client-Side)
const url = await vault.starchive.presign.put("uploads/user.txt", {
contentType: "text/plain",
ttlSeconds: 300
});
console.log("Upload directly to:", url);
5. Streaming Download
const stream = await vault.starchive.getStream("uploads/photo.png");
stream.pipe(fs.createWriteStream("./downloaded.png"));
6. Range Request (Video Streaming)
const part = await vault.starchive.getStreamRange("videos/movie.mp4", 0, 1024*1024);
part.stream.pipe(fs.createWriteStream("./clip.mp4"));
7. Directory Walk
for await (const node of vault.starchive.walk({ prefix: "reports/2025/" })) {
console.log(node.type, node.key);
}
8. Metadata & Stat
const info = await vault.starchive.stat("uploads/photo.png");
console.log(info.size, info.lastModified, info.contentType);
9. Record Management
const rec = await vault.starchive.records.getByID("file-123");
await vault.starchive.records.updateFields("file-123", { tags: ["archive"] });
await vault.starchive.records.deleteByID("file-123", { softDelete: true });
10. Copy & Move
await vault.starchive.copy("docs/a.txt", "docs/a-copy.txt");
await vault.starchive.move("docs/b.txt", "docs/b-archived.txt");
β¨ License
See License in LICENSE.md
π Transform Data into Action
Star-Vault transcends traditional data systemsβoffering a full-fledged database engine and cosmic foundation that propels secure, reactive, and intelligent data-driven architectures.