Web3User Permission Lab is an early-stage off-chain transaction authorization and policy-governance SDK for Node.js (>=22.13.0) with zero third-party runtime dependencies.
Designed for transaction relayers, wallet middleware, and dApp backends, Web3User provides pre-execution governance:
- Evaluates candidate transaction proposals against authoritative in-database governance policies.
- Generates versioned, tamper-evident authorization artifacts using Ed25519 digital signatures.
- Enforces persistent, single-use replay prevention backed by SQLite Write-Ahead Logging (WAL) and monotonic timekeeping.
Important
Off-Chain Scope & Boundaries: Web3User is an off-chain decision engine, not an on-chain smart contract, blockchain validator, or transaction broadcaster.
- The SDK validates candidate transaction parameters against declarative rules and records persistent single-use reservations in local SQLite storage.
- The SDK does not sign Ethereum transactions with wallet keys (secp256k1), submit RPC requests to nodes, manage mempool broadcasts, estimate gas, manage nonces, or custody assets.
- An
ALLOWdecision indicates off-chain policy compliance; it does not constitute blockchain execution or funds movement. The integrating relayer or application remains responsible for separate wallet-signing and RPC broadcast. - Durable Consumption: Authorization consumption is durable and permanent in SQLite (
state = 'consumed'). It is not automatically reversed or restored if downstream blockchain broadcasting fails, reverts on-chain, or is dropped from the mempool. - Spending Limits & Cumulative Budgets:
maxAmountis strictly an inclusive per-action ceiling for a single transaction. In addition, policies can optionally configure a stateful cumulative spending budget (budget: { window: "HOURLY" | "DAILY", maxCumulativeAmount: string }) enforced atomically within SQLite write transactions.
Development-stage preview and release candidate (v0.1.0-rc.1). This software is a local-first reference implementation intended for evaluation, integration testing, and research. It has not undergone an independent external security audit and makes no claim of formal verification or production readiness.
- Node.js 22.13.0 or later. The persistent SQLite store uses the built-in
node:sqlitemodule, which was added in Node.js 22.5.0 and is available without an experimental flag starting in 22.13.0. - npm (the repository baseline is npm 11.20.0).
The repository pins its baseline development runtime in .nvmrc (Node.js 26.11.1) and declares the baseline package manager in package.json (npm@11.20.0). These are the project's reproducible local baseline; the supported Node.js range remains >=22.13.0, as declared by the package and exercised by the CI compatibility matrix.
With nvm installed, select the pinned Node.js version with nvm install and nvm use. On Windows, use nvm-windows; run nvm install 26.11.1 and nvm use 26.11.1 because its command behavior differs from nvm on Unix-like systems. Confirm the active versions before installing dependencies:
node --version
npm --versionFrom a fresh checkout, install exactly the dependency versions recorded in package-lock.json:
npm ciDo not use npm install for a routine clean recovery install; use it only when intentionally changing dependencies and the lockfile.
The repository provides a containerized reproducibility and verification harness for the Web3User SDK on Linux containers. The verification image installs all dependencies from package-lock.json under Node.js 26.11.1 and npm 11.20.0 with OpenSSL CLI tooling, builds the SDK distribution, validates TypeScript types, runs the Linux-compatible test suite against an isolated PostgreSQL instance, executes example workflows, verifies persistent replay prevention, and performs an npm packaging dry-run.
Note
This container image is strictly a verification harness for the SDK library, not a long-running service or daemon. It exposes no public network ports.
- Docker Engine / Docker Desktop (Linux container mode)
- Docker Compose v2.0+
-
Build verification image:
docker build --tag web3user-permission-lab:verify . -
Run full automated verification with isolated PostgreSQL:
docker compose up --build --abort-on-container-exit --exit-code-from tester
-
Clean up temporary verification resources:
docker compose down -v
The Compose configuration launches an ephemeral postgres:16-alpine service with data stored entirely in memory via tmpfs (/var/lib/postgresql/data). No host port is published or bound to host network interfaces for the Compose PostgreSQL service. The tester container discovers and communicates with the database using Compose service DNS (PGHOST=postgres) across the user-defined Docker bridge network (web3user_default).
Because internal: true is not configured, the default Docker bridge network permits outbound connectivity to external networks and the host gateway. The absence of published host ports protects host-native PostgreSQL instances (such as port 5432) from port collisions and external inbound network access, but it does not constitute guaranteed network-layer isolation from host services. When running multiple independent concurrent Compose verification runs on the same Docker daemon, assign unique Compose project names (docker compose -p <project-name> ...) to prevent naming and resource conflicts.
- Linux-Compatible Suites (32 files, 655 tests): Executed automatically within the container. Covers all core unit tests, SQLite persistence, OpenSSL mTLS certificate generation and validation (
test/witness/unit-d2.test.ts,grpc-mtls-transport.test.ts), in-process etcd mock adapter tests (test/witness/etcd-client-adapter.test.ts), and PostgreSQL integration suites (test/witness/postgres-store.test.ts,test/witness/migration-003.test.ts). - Windows-Specific Suite (1 file, 26 tests):
test/witness/etcd-client-adapter.real.test.tstests against a live, official etcd v3.5.18 Windows binary located in.tmp/etcd-bin/v3.5.18/etcd.exe. Because.tmp/is strictly excluded from the Docker build context by.dockerignoreto preserve local binaries and prevent secret leakage, this suite runs natively on Windows hosts.
The .dockerignore excludes local dependencies, build artifacts, transient data (.tmp/, .demo-data/), environment files, and private keys/certificates from the build context. Do not add secrets to the Docker build context.
npm run build
npx tsc --noEmit
npm test
npx tsx examples/basic-authorization.ts
npm run demo:persistent-replay -- --verify
npm pack --dry-run --jsonThe SDK provides an off-chain authorization and policy governance engine backed by SQLite persistence with WAL journaling, cryptographic key management, and atomic single-use replay prevention.
Build and package the SDK locally into a .tgz tarball without publishing to a remote registry:
# In the Web3User repository:
npm run build
npm pack
# In your consumer project:
npm install /path/to/web3user-permission-lab-0.1.0-rc.1.tgzimport { Web3UserEngine, type DemoPolicy, type TransactionRequest } from "web3user-permission-lab";
// 1. Open the engine
const engine = Web3UserEngine.open({
databasePath: "./data/authorization.sqlite",
durability: {
synchronous: "FULL", // Default: fsync commits for OS crash safety
busyTimeoutMs: 5000, // Bounded retry under write lock contention
},
});
// 2. Register an Ed25519 issuer key
const keypair = engine.keys.generate();
engine.keys.register({
keyId: "issuer-01",
publicKey: keypair.publicKey,
status: "active",
});
// 3. Register a policy (with optional cumulative hourly/daily budget)
const policy: DemoPolicy = {
version: 1,
policyId: "transfer-limit-policy",
allowedTarget: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
allowedRecipient: "0x2222222222222222222222222222222222222222",
allowedSelector: "0xa9059cbb",
maxAmount: "1000000000",
validFrom: 0,
expiresAt: 2_000_000_000,
revoked: false,
budget: {
window: "HOURLY", // "HOURLY" or "DAILY" (fixed UTC windows)
maxCumulativeAmount: "2500000000", // uint256 decimal string
},
};
engine.policies.register(policy);
// 4. Issue a V3 signed authorization artifact
const request: TransactionRequest = {
chainId: "1",
sender: "0x1111111111111111111111111111111111111111",
target: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
calldata: "0xa9059cbb" + "22".repeat(20).padStart(64, "0") + (500n).toString(16).padStart(64, "0"),
value: "0",
};
const issueResult = engine.issue({
authorizationId: "auth-001",
policyId: "transfer-limit-policy",
request,
signer: { keyId: "issuer-01", privateKey: keypair.privateKey },
ttlSeconds: 300,
});
if (issueResult.decision === "ALLOW") {
// 5. Relayer / Consumer consumes the artifact atomically before execution
const consumeResult = engine.consume({
artifact: issueResult.artifact,
request,
});
if (consumeResult.decision === "ALLOW") {
// Note: ALLOW confirms policy compliance and marks the authorization consumed
// in SQLite. This reservation is durable and is not automatically reversed if
// downstream blockchain execution fails, reverts on-chain, or is dropped from the mempool.
// The external caller / relayer remains responsible for signing the EVM transaction with
// an Ethereum wallet key (secp256k1) and broadcasting to an RPC node.
console.log("Authorization granted off-chain. Ready for wallet signing and RPC broadcast.");
}
// 6. Any duplicate consumption attempt is strictly denied
const replayResult = engine.consume({
artifact: issueResult.artifact,
request,
});
console.log(replayResult.decision); // "DENY" (Replay prevented)
}
// 7. Clean teardown
engine.close();The engine strictly returns one of three decisions:
ALLOW: The transaction request satisfies authoritative policy rules, signing key validity intervals, and timestamp guardrails. A persistent single-use reservation was recorded atomically in SQLite. This represents an off-chain authorization outcome, not an on-chain execution or transaction broadcast. Consumption is durable and irreversible: once consumed in SQLite, the authorization cannot be reused and is not automatically restored or reversed if downstream blockchain execution fails, reverts, or is dropped from the mempool.DENY: The request violates policy bounds (e.g. transfer limit exceeded, disallowed target/selector), references a revoked/retired key or policy, has expired, or has already been consumed (replay attack).UNKNOWN: The candidate calldata or request structure is malformed or cannot be safely parsed into a valid transaction envelope.
- Policy Denials are normal business outcomes: Returned as structured objects
{ decision: "DENY", reasons: string[] }. They do not throw exceptions and do not corrupt engine health. - Operational Failures throw typed
Web3UserErrorsubclasses:ValidationError: Invalid parameter types, blank IDs, or strings exceeding maximum length limits (128 chars).EngineClosedError: Invoking operations on an engine afterengine.close()has been called.ContentionError: SQLite write lock acquisition failed after exhausting the contention retry budget.ClockGuardError: Clock rollback, forward drift exceeding safety bounds, or startup forward gap violation.StoreTaintedError: The database connection was quarantined due to an uncertainCOMMIT;outcome or unrecoverable disk error. Never automatically retry an operation when a store is tainted.
- Local Storage Requirement: SQLite WAL mode requires shared memory (
-shm) and POSIX byte-range file locking. Network filesystems (such as NFS, SMB/CIFS, AWS EFS, Azure Files, or GlusterFS) do not reliably implement these primitives and can cause silent corruption, locking deadlocks, orSQLITE_BUSYerrors. The database must reside on direct, locally attached block storage (e.g. local NVMe/SSD or dedicated cloud block storage like AWS EBS / GCP Persistent Disk mounted locally). - WAL & Synchronous FULL: Every owned connection configures
PRAGMA journal_mode = WAL;andPRAGMA synchronous = FULL;by default. - Checkpointing & WAL Management:
- The SDK exposes
engine.storage.checkpoint(mode?: CheckpointMode): CheckpointResult. - Supported modes:
"PASSIVE"(default),"FULL","RESTART", and"TRUNCATE". - Return structure:
{ busy: boolean, logFrames: number, checkpointedFrames: number }. - Checkpointing transfers write-ahead log frames back into the main database file.
- Active or long-running read transactions hold shared locks on earlier WAL frames, preventing them from being checkpointed or truncated, which causes
result.busyto betrue. - Operational practice: Avoid calling
checkpoint("TRUNCATE")unconditionally on latency-sensitive request paths. Run checkpointing as a periodic background maintenance task or during low-concurrency intervals, and always inspectresult.busyto verify whether the log was fully truncated.
- The SDK exposes
- Durability Model & Hardware Recommendations:
- Process Crash: Protected by WAL atomic commits and automatic rollback upon database reopen.
- OS Crash / Kernel Panic: Protected by
synchronous = FULLissuing OS-level flush requests (fsync/FlushFileBuffers) on every commit. - Power Loss Durability: Disk controllers with volatile write caches may acknowledge writes before data is permanently committed to non-volatile NAND cells. For mission-critical deployments requiring physical power-loss durability, enterprise host storage controllers with hardware Power Loss Protection (PLP) capacitors are recommended.
- Off-Chain Scope: Web3User is an off-chain decision engine. It does not sign Ethereum transactions, connect to RPC nodes, or broadcast to mempools.
- Dual-Key Architecture (Issuer Ed25519 vs. Wallet secp256k1):
- Issuer Keys (Ed25519): Managed within the SDK (
SQLiteKeyStore) to sign and verify off-chain V3 authorization artifacts. - Wallet Keys (secp256k1): Ethereum private keys used on-chain to sign EVM transactions. The Web3User SDK never handles, stores, or accesses wallet private keys.
- Issuer Keys (Ed25519): Managed within the SDK (
- Private Key Safety: Never hardcode private keys in source code. Load private keys from secure environment variables, KMS, or HSMs. The SDK never logs, serializes, or echoes private key material in error messages.
- Host Clock Synchronization for Multi-Process Deployments: When multiple worker processes share an SQLite database,
ClockGuardchecks candidate timestamps against the shared SQLitehigh_water_seconds. Any backward step relative to that mark is rejected as a rollback. Host servers should run continuous NTP daemons (chronyorsystemd-timesyncd). While minimizing drift (e.g. keeping clock drift within an operational target of ~100ms) reduces the likelihood of interleaving collisions between distributed workers, no sub-second offset is a universally guaranteed safe threshold under arbitrary scheduling, network latency, or process interleaving. - Per-Action Ceilings vs. Cumulative Budgets:
maxAmountdefines an inclusive per-action ceiling for any single transaction. To enforce aggregate spending limits across transactions, policies can optionally configurebudget: { window: "HOURLY" | "DAILY", maxCumulativeAmount: string }. Cumulative budgets are enforced atomically inside SQLite write locks during consumption, preventing race-condition overruns even across multiple processes. Unbudgeted policies operate purely on per-action limits. - Durable Consumption & Downstream Broadcast Failures: Authorization consumption transitions the database state to
consumedpermanently. If the subsequent blockchain transaction reverts on-chain, fails to broadcast, or is dropped from the mempool, Web3User does not automatically roll back or reverse the consumption. Relayers must manage transaction failures by requesting a fresh authorization under a new authorization ID. - Privileged Store Access:
engine.getStore()is provided strictly for administrative maintenance and diagnostics. Executing raw SQL directly on the underlying connection bypasses engine validations and ClockGuard safeguards.
The demo demonstrates persistent replay protection using bound authorization artifacts and an additive two-phase (issued → consumed) state model in SQLite. It uses a fixed local policy, transfer request, trusted demonstration time, and authorization ID (bound-replay-demo-authorization-001).
- First run: Issues the bound authorization artifact (inserting a record in state
issuedwith canonical SHA-256 binding digest), then revalidates and atomically consumes the artifact (transitioning state toconsumed). PrintsDecision: ALLOW. - Subsequent runs: Reopens the persistent database, reconstructs the bound artifact, and attempts to consume it again. Because the database record is already in state
consumed, the consumption fails closed and printsDecision: DENYwith reasonBound transaction authorization is unknown, consumed, or mismatched.. A denial is the expected successful replay-protection result. - Verification mode: Run
npm run demo:persistent-replay -- --verifyto run an automated, end-to-end verification against an isolated temporary database, demonstrating both fresh issuance/consumption and replay rejection across database reopen.
The demo database is stored at .demo-data/bound-authorization-replay.sqlite in the repository. It is separate from application data and is ignored by Git. The legacy demo database (.demo-data/authorization-replay.sqlite) is preserved. The demo never removes or resets databases automatically.
This is a local authorization demonstration only. An ALLOW result does not mean a transaction was signed, submitted, or executed. The demo does not connect to a wallet, interact with a blockchain, move funds, or provide a production deployment.
- Supported Transaction Format: Currently restricted to the standard ERC-20
transfer(address,uint256)function selector (0xa9059cbb) with exactly 68 bytes of calldata (4-byte selector and two 32-byte ABI arguments). Other selectors, arbitrary contract calls, or malformed encodings returnUNKNOWNorDENY. - Policy Allowlisting: Enforces case-insensitive address allowlists for the ERC-20 token contract (
allowedTarget) and the recipient (allowedRecipient). - Spending Limits Boundary: Enforces an inclusive per-action maximum transfer amount (
maxAmount), with optional support for stateful cumulative budgets (HOURLYorDAILY) enforced atomically in SQLite. - Authority and Invalidation: V3 authorizations bind the authoritative policy revision and issuer key state in SQLite. Restoring or modifying a policy increments its revision and permanently invalidates prior authorizations.
- Not an On-Chain Enforcer: Web3User operates strictly off-chain. It does not monitor mempools, intercept RPC traffic, or communicate directly with blockchain consensus. Callers must fail closed on
DENYorUNKNOWNand must verify authorization before requesting user wallet signatures. - Durable Local Storage Required: SQLite WAL mode requires shared memory (
-shm) and POSIX byte-range file locking. Network filesystems (NFS, SMB/CIFS, AWS EFS, Azure Files, GlusterFS) are strictly unsupported and risk database corruption, locking deadlocks, orSQLITE_BUSYerrors. The database must reside on directly attached local block storage. - Durable Consumption Without Automatic Reversal: An
ALLOWconsumption reservation is durable and permanent in SQLite (state = 'consumed'). It is not automatically reversed if downstream on-chain broadcasting fails, times out, reverts, or is dropped from the mempool. - Dual Spending Controls:
maxAmountbounds each individual action; optionalbudgetlimits cumulative spending across transactions within fixed UTC hourly or daily windows. - Pre-Release Audit Notice: This release candidate is not audited for production deployment. Do not use it as the sole security control for high-value mainnet treasuries or unmonitored autonomous execution.
If this project is useful to you, consider sponsoring its development: https://github.com/sponsors/syedsenterprises