typescript / expert
Snippet
Object Capability Enforcement using Private Fields and Brand Tokens
This snippet demonstrates the Object Capability pattern using ECMAScript hard private fields (#field). By guaranteeing that tokens cannot be fabricated or inspected outside their declaring class, security checks remain unforgeable at both compile-time and runtime.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class AccessToken {#scope: string;constructor(scope: string) {this.#scope = scope;}static grant(scope: string): AccessToken {return new AccessToken(scope);}}class SecureVault<T> {#data: T;constructor(data: T) {this.#data = data;}public read(token: AccessToken): T {if (!(token instanceof AccessToken)) {throw new TypeError("Unauthorized access attempt");}return this.#data;}}
Breakdown
1
#scope: string;
Declares an ES hard-private field inaccessible outside the AccessToken class body.
2
static grant(scope: string): AccessToken
Factory method serving as the sole controlled vector for instantiating access capabilities.
3
if (!(token instanceof AccessToken))
Runtime guard validating the structural capability credential before revealing encapsulated state.