Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: CI

on:
push:
branches: [master, modernize-typescript]
pull_request:

jobs:
build:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
node: [18, 20, 22]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
cache: npm
- run: npm ci
- run: npm run lint
- run: npm run typecheck
- run: npm run build
# testcontainers needs Docker, available on ubuntu-latest runners.
- run: npm test
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
node_modules/*
dist/
coverage/
*.tsbuildinfo
.DS_Store
*~
.idea/
.vscode/
.tags*
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
20
63 changes: 63 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## What this is

`acl-next` is a modern TypeScript Access Control List (ACL / RBAC) library — a maintained fork of optimalbits/node_acl. It models authorization as **users → roles → resources → permissions**, with role hierarchies (parents). It ships three storage backends (Redis, MongoDB, in-memory) and a framework-agnostic Express-style middleware.

The codebase is **promise-native**, **TypeScript strict**, and has **zero runtime dependencies** (`redis` and `mongodb` are optional peer deps — install only what you use).

## Commands

```bash
npm run build # tsup → dist/ (ESM + CJS + .d.ts)
npm run typecheck # tsc --noEmit (strict)
npm run lint # biome check
npm run format # biome format --write
npm test # vitest run (all suites)
npx vitest run test/memory-acl.test.ts # single backend suite
npx vitest run test/unit # fast unit tests, no Docker
npx vitest run -t "isAllowed" # filter by test name
```

**Test infrastructure:** the Redis and MongoDB suites use [testcontainers](https://testcontainers.com/) to spin up real databases in Docker — **Docker must be running** for them. The Memory suite and `test/unit/*` run without Docker (use these for the fast inner loop). First run pulls `redis:7-alpine` / `mongo:6` images (slow; `hookTimeout` in [vitest.config.ts](vitest.config.ts) is sized for it).

## Architecture

- **[src/index.ts](src/index.ts)** — public entry point; re-exports everything. Default export is `Acl`.
- **[src/acl.ts](src/acl.ts)** — the `Acl<T>` class: all authorization logic (`allow`, `isAllowed`, `whatResources`, `allowedPermissions`, role/resource/user mutations, `middleware()`). This is the only file with business logic; backends are dumb storage.
- **[src/types.ts](src/types.ts)** — domain types and the generic `Backend<T>` storage interface.
- **[src/backends/{memory,redis,mongodb}.ts](src/backends/)** — the three storage implementations.
- **[src/middleware.ts](src/middleware.ts)** — `aclMiddleware`, `aclErrorHandler`, `HttpError`, and structural HTTP types.

### Backend abstraction (the key concept)

`acl.ts` never talks to a database directly — only to a `Backend<T>` (see [src/types.ts](src/types.ts)): a namespaced (bucketed) key → set-of-values store with **batched writes** via a transaction.

Pattern: `const t = backend.begin()` → queue mutations with `add`/`del`/`remove` (these push onto `t`, they do **not** write) → `await backend.end(t)` commits. Implementations map this onto their primitives:

- **Memory**: transaction is an array of closures run on `end`.
- **Redis**: transaction is a `multi()`; mutations queue `sAdd`/`sRem`/`del`, `end` calls `exec()`.
- **MongoDB**: transaction is an array of async thunks run in series; each (bucket,key) is a document whose field names are the set members.

Buckets: `meta`, `parents`, `permissions`, `resources`, `roles`, `users` (overridable via constructor options), plus dynamic `allows_<resource>` buckets for permissions. When adding/changing behavior, preserve the batch-then-commit pattern rather than writing eagerly.

`Backend.unions` is **optional**; when present (Memory, Redis) `allowedPermissions` uses the bulk-query fast path, otherwise it falls back to per-resource `union` calls (MongoDB).

### Decoupling from drivers

The Redis and MongoDB backends define **structural interfaces** (`RedisClientLike`, `MongoDbLike`, etc.) instead of importing driver types, so the package stays driver-agnostic and consumers without a given driver still type-check. tsup marks `redis`/`mongodb` as `external` so they're never bundled.

## Conventions

- TypeScript strict (`noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`, `verbatimModuleSyntax`). Use `import type` for type-only imports. Relative imports use the `.js` extension.
- **Promise-only** public API (the legacy callback dual-API was intentionally dropped).
- IDs (`UserId`) are coerced to **strings** in stored/returned values.
- `'*'` is the wildcard meaning "all permissions"; ids/role/resource names are case-sensitive.
- Lint/format is **Biome** (config in [biome.json](biome.json)); run `npm run lint` before committing.
- **Tests run once per backend** via the shared, ordered, stateful suite in [test/shared/acl-suite.ts](test/shared/acl-suite.ts). Add a behavioral feature there so it's exercised against all backends; put storage-specific cases in `test/unit/`.

## History

[MODERNIZATION.md](MODERNIZATION.md) is the rewrite plan; [TEST-BASELINE.md](TEST-BASELINE.md) records the legacy suite result (394 passing) that the rewrite preserves.
23 changes: 23 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
The MIT License (MIT)

Copyright (c) 2011-2013 Manuel Astudillo <manuel@optimalbits.com> (original node_acl)
Copyright (c) 2026 acl-next contributors

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
105 changes: 105 additions & 0 deletions MODERNIZATION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# Modernization Plan

Plan to rewrite `node_acl` as a modern, TypeScript, promise-native ACL library published under a new name (e.g. `acl-next` or `@you/acl`).

The original architecture is sound — keep the **users → roles → resources → permissions** model, the **backend abstraction**, the **transaction `begin`/`end`** pattern, and the **bucket** namespacing. Everything else is replaceable.

---

## Target stack

| Concern | Now | Target | Notes |
| --- | --- | --- | --- |
| Language | ES5, `var`, prototypes | **TypeScript** (strict), classes, ESM | Ship dual ESM + CJS |
| Promises | `bluebird` | **native** Promises / `async`/`await` | Delete bluebird |
| Utilities | `lodash@4`, `async@2` | **native** (`Set`, `Array.flat`, spread) | Delete both |
| Arg validation | `contract.js` (runtime) | **TS types** (compile-time) | Delete contract.js entirely |
| API style | dual callback + promise | **promise-only** | Breaking → justifies new major/name |
| Redis driver | `redis@2` | `redis@4+` (promise-native) | API changed significantly |
| Mongo driver | `mongodb@2` | `mongodb@6+` (promise-native) | API changed significantly |
| Tests | mocha + chai, needs local DBs | **vitest** + **testcontainers** | Spins up Redis/Mongo in Docker per run |
| Lint/format | none | **Biome** (or ESLint + Prettier) | Biome = one fast tool |
| CI | Travis (Node 0.10–stable) | **GitHub Actions**, Node 18/20/22 LTS | Matrix |
| Build | none | **tsup** (esbuild) | Emits ESM, CJS, and `.d.ts` |
| Docs | hand-written README | README + **typedoc** | Generated API reference |
| Node support | `>= 0.10` | `>= 18` | |

---

## Phase 0 — Foundation (no logic changes)

Goal: a buildable, lintable, empty TS project skeleton.

1. New repo / package name; update `package.json` (`name`, `type: "module"`, `exports` map, `engines`, `files`).
2. Add `LICENSE` keeping the original MIT notice (`Copyright (c) 2011-2013 Manuel Astudillo`) **plus** your own line. Note "fork of optimalbits/node_acl" in README.
3. `tsconfig.json` with `strict: true`, `noUncheckedIndexedAccess`, `target: ES2022`, `moduleResolution: bundler`.
4. tsup config → dual ESM/CJS + declarations.
5. Biome (or ESLint+Prettier) config.
6. GitHub Actions: lint + typecheck + test matrix on Node 18/20/22.
7. `src/` layout: `src/index.ts`, `src/acl.ts`, `src/types.ts`, `src/backends/{memory,redis,mongodb}.ts`.

**Risk:** low. **Output:** green CI on an empty shell.

## Phase 1 — Test harness first (safety net)

Goal: port the existing test suite *before* touching logic, so the rewrite is verified against known-good behavior.

1. Port [test/tests.js](test/tests.js) + [test/backendtests.js](test/backendtests.js) to vitest, keeping the "run the same suite against every backend" structure from [test/runner.js](test/runner.js).
2. Replace the "requires local Redis/Mongo" assumption with **testcontainers** — tests start ephemeral DB containers, so `npm test` works on any machine with Docker and in CI without service config.
3. Keep the Memory backend suite able to run without Docker (fast inner loop).

**Risk:** medium (testcontainers + Docker in CI). **Output:** the full behavioral spec, runnable.

## Phase 2 — Types & backend interface

1. Define `src/types.ts`: `UserId = string | number`, `Role`, `Resource`, `Permission`, and the `Backend` interface (typed version of [lib/backend.js](lib/backend.js)): `get`, `union`, `unions`, `add`, `del`, `remove`, `clean`, `begin`, `end`.
2. Decide the transaction type. Recommended: keep it opaque (`type Transaction = unknown` per backend, or a generic `Backend<T>`), preserving the queue-then-commit model.
3. Make backend methods **return Promises** instead of taking callbacks — this is what lets `acl.ts` drop bluebird's `promisify`.

## Phase 3 — Port backends (memory → redis → mongo)

1. **Memory** first (no external dep, pure logic). Replace lodash with `Set`/`Array.flat`. This validates the test harness end-to-end.
2. **Redis** on `redis@4`: rewrite using native promise API and `multi()` for the transaction commit. Map `begin`→start a command queue, `end`→`exec()`.
3. **MongoDB** on `mongodb@6`: rewrite with the modern collection API; preserve the `useSingle` option (one collection vs per-resource).

**Risk:** medium-high — redis/mongo driver APIs changed a lot between v2 and current. The ported test suite is your guardrail.

## Phase 4 — Port core (`acl.ts`)

1. Translate [lib/acl.js](lib/acl.js) public API to a `class Acl`, **promise-only** (drop the `nodeify`/callback dual path).
2. Replace bluebird chains with `async`/`await`.
3. Replace all lodash/async calls with native equivalents.
4. **Delete `contract.js`** — runtime `params(...)` checks become TS parameter types. (Optionally add light runtime guards only at the public boundary if you want JS-consumer safety.)
5. Keep `'*'` wildcard semantics and case-sensitivity behavior intact (tests enforce this).

## Phase 5 — Express middleware

1. Type `acl.middleware(numPathComponents?, userId?, permissions?)`.
2. Consider decoupling from Express's exact types (accept a minimal `{ url, method, session }`-shaped request) so it works with Express 5, Fastify adapters, etc. — or ship `@types/express` as a peer/optional dep.

## Phase 6 — Packaging, docs, release

1. Verify the `exports` map resolves for both `import` and `require`; test with `arethetypeswrong` and `publint`.
2. Rewrite README for the new name + promise-only API; add a **migration guide** from `node_acl` (callbacks→promises, dropped bluebird-specific behavior).
3. Generate API docs with typedoc.
4. `npm publish` as `1.0.0` (it's a clean break). Add a CHANGELOG and semantic-release if you want automation.

---

## Other suggestions / nice-to-haves

- **Make the package zero-dependency at runtime.** After dropping bluebird/lodash/async, the core needs no deps; the redis/mongo drivers become `peerDependencies` (the consumer brings their own client) so you don't pin their versions. This is the single biggest modernization win.
- **`exactOptionalPropertyTypes` + generics on `Backend<TTransaction>`** for full type safety across backends.
- **Add a `deny`/explicit-denial feature** — listed as "Future work" in the original README and never built. A clean differentiator for the fork.
- **Batch/typed query helpers** and an `isAllowedAny` / `isAllowedAll` distinction for clearer multi-permission semantics.
- **Benchmarks** (e.g. `tinybench`) so dependency changes don't regress performance.
- **`provenance` on publish** (npm `--provenance` via GitHub Actions) for supply-chain trust.
- **Drop Docker requirement for unit tests** by keeping memory-backend tests as the fast path; gate container tests behind a separate `test:integration` script.

---

## Suggested order of attack

Phase 0 → 1 → 3a (memory) → 4 → 5 → 3b/3c (redis/mongo) → 2 is woven through 2–4 → 6.

Rationale: get a buildable shell + ported tests + the memory backend working with the new core **first** (no Docker, no driver upgrades) to prove the whole design, then tackle the higher-risk redis/mongo driver upgrades against a passing suite.
Loading