ReadonlySet Seals Shared Allowlists

Expose ReadonlySet views across module boundaries to hide add, delete, and clear from callers while preserving lookup, iteration, and element covariance.

TypescriptSecurity Boundaries

Code

snippet
type Scope = 'read' | 'write' | 'export';

function createScopeStore(initial: readonly Scope[]) {
  const backing = new Set<Scope>(initial);
  return {
    grant(scope: Scope): void {
      backing.add(scope);
    },
    // Callers receive ReadonlySet<Scope>: add/delete/clear are absent on the type
    view(): ReadonlySet<Scope> {
      return backing;
    },
  };
}

// ReadonlySet<T> is covariant in T, so ReadonlySet<Scope> fits ReadonlySet<string>
function hasAllRequired(granted: ReadonlySet<string>, required: readonly string[]): boolean {
  return required.every((item) => granted.has(item));
}

const store = createScopeStore(['read']);
const snapshot = store.view();
console.log('before grant:', [...snapshot].join(','), 'can write:', hasAllRequired(snapshot, ['read', 'write']));

store.grant('write');
console.log('after grant:', snapshot.size, 'can write:', hasAllRequired(snapshot, ['read', 'write']));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

before grant: read can write: false
after grant: 2 can write: true

How it works

Key operational steps happen within the callables createScopeStore and hasAllRequired.

The return value is newly constructed — inputs are never handed back.

What to watch for

  • The only prerequisite is the language toolchain itself.

Putting it to use

Essential subroutine signature reads function createScopeStore(initial: readonly Scope[])

Expect labeled output — before grant:, after grant: — when the file runs.

Core lines

return required.every((item) => granted.has(item));
const backing = new Set<Scope>(initial);

Interactive Tools for This Topic

FAQ

Does `createScopeStore` modify its input?
No mutation happens — the function reads its input and returns a new value.
Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. The file defines `createScopeStore`, `hasAllRequired` at load time.