|
|
|
|
@@ -56,8 +56,9 @@ export class PathError extends Error { }
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* A event broken down into its core components for easy processing
|
|
|
|
|
* Event Structure: `module/path/name:property:method`
|
|
|
|
|
* Event Structure: `module/path/name:method`
|
|
|
|
|
* Example: `users/system:crud` or `storage/some/path/file.txt:r`
|
|
|
|
|
* Supports glob patterns: `users/*:r` or `storage/**:rw`
|
|
|
|
|
*/
|
|
|
|
|
export class PathEvent {
|
|
|
|
|
/** First directory in path */
|
|
|
|
|
@@ -66,13 +67,19 @@ export class PathEvent {
|
|
|
|
|
fullPath!: string;
|
|
|
|
|
/** Path including the name, excluding the module */
|
|
|
|
|
path!: string;
|
|
|
|
|
/** Last sagment of path */
|
|
|
|
|
/** Last segment of path */
|
|
|
|
|
name!: string;
|
|
|
|
|
/** List of methods */
|
|
|
|
|
methods!: ASet<Method>;
|
|
|
|
|
/** Whether this path contains glob patterns */
|
|
|
|
|
hasGlob!: boolean;
|
|
|
|
|
|
|
|
|
|
/** Internal cache for PathEvent instances to avoid redundant parsing */
|
|
|
|
|
private static pathEventCache: Map<string, PathEvent> = new Map();
|
|
|
|
|
/** Cache for compiled permissions (path + required permissions → result) */
|
|
|
|
|
private static permissionCache: Map<string, PathEvent> = new Map();
|
|
|
|
|
/** Max size for permission cache before LRU eviction */
|
|
|
|
|
private static readonly MAX_PERMISSION_CACHE_SIZE = 1000;
|
|
|
|
|
|
|
|
|
|
/** All/Wildcard specified */
|
|
|
|
|
get all(): boolean { return this.methods.has('*') }
|
|
|
|
|
@@ -83,6 +90,9 @@ export class PathEvent {
|
|
|
|
|
/** Create method specified */
|
|
|
|
|
get create(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('c')) }
|
|
|
|
|
set create(v: boolean) { v ? this.methods.delete('n').delete('*').add('c') : this.methods.delete('c'); }
|
|
|
|
|
/** Execute method specified */
|
|
|
|
|
get execute(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('x')) }
|
|
|
|
|
set execute(v: boolean) { v ? this.methods.delete('n').delete('*').add('x') : this.methods.delete('x'); }
|
|
|
|
|
/** Read method specified */
|
|
|
|
|
get read(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('r')) }
|
|
|
|
|
set read(v: boolean) { v ? this.methods.delete('n').delete('*').add('r') : this.methods.delete('r'); }
|
|
|
|
|
@@ -105,17 +115,44 @@ export class PathEvent {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let [p, scope, method] = e.replaceAll(/\/{2,}/g, '/').split(':');
|
|
|
|
|
if(!method) method = scope || '*';
|
|
|
|
|
if(p == '*' || (!p && method == '*')) {
|
|
|
|
|
p = '';
|
|
|
|
|
method = '*';
|
|
|
|
|
let [p, method] = e.replaceAll(/\/{2,}/g, '/').split(':');
|
|
|
|
|
if(!method) method = '*';
|
|
|
|
|
|
|
|
|
|
// Handle special cases
|
|
|
|
|
if(p === '' || p === undefined) {
|
|
|
|
|
// Empty string matches nothing
|
|
|
|
|
this.module = '';
|
|
|
|
|
this.path = '';
|
|
|
|
|
this.fullPath = '';
|
|
|
|
|
this.name = '';
|
|
|
|
|
this.methods = new ASet<Method>(['n']);
|
|
|
|
|
this.hasGlob = false;
|
|
|
|
|
PathEvent.pathEventCache.set(e, this);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if(p === '*') {
|
|
|
|
|
// Wildcard means any path any event
|
|
|
|
|
this.module = '';
|
|
|
|
|
this.path = '';
|
|
|
|
|
this.fullPath = '**';
|
|
|
|
|
this.name = '';
|
|
|
|
|
this.methods = new ASet<Method>(['*']);
|
|
|
|
|
this.hasGlob = true;
|
|
|
|
|
PathEvent.pathEventCache.set(e, this);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let temp = p.split('/').filter(p => !!p);
|
|
|
|
|
this.module = temp.splice(0, 1)[0] || '';
|
|
|
|
|
this.path = temp.join('/');
|
|
|
|
|
this.fullPath = `${this.module}${this.module && this.path ? '/' : ''}${this.path}`;
|
|
|
|
|
this.name = temp.pop() || '';
|
|
|
|
|
|
|
|
|
|
// Don't trim /** - it's needed for glob matching to work properly
|
|
|
|
|
// Only trim if there's something after it which won't happen with our parsing
|
|
|
|
|
|
|
|
|
|
this.hasGlob = this.fullPath.includes('*');
|
|
|
|
|
this.methods = new ASet(<any>method.split(''));
|
|
|
|
|
|
|
|
|
|
// Store in cache
|
|
|
|
|
@@ -127,6 +164,87 @@ export class PathEvent {
|
|
|
|
|
PathEvent.pathEventCache.clear();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Clear the permission cache */
|
|
|
|
|
static clearPermissionCache(): void {
|
|
|
|
|
PathEvent.permissionCache.clear();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Score a path for specificity ranking (lower = more specific = higher priority)
|
|
|
|
|
* @private
|
|
|
|
|
*/
|
|
|
|
|
private static scoreSpecificity(path: string): number {
|
|
|
|
|
if (path === '**' || path === '') return Number.MAX_SAFE_INTEGER; // Least specific
|
|
|
|
|
|
|
|
|
|
const segments = path.split('/').filter(p => !!p);
|
|
|
|
|
// Base score: number of segments (more segments = more specific = lower score)
|
|
|
|
|
let score = -segments.length;
|
|
|
|
|
|
|
|
|
|
// Penalty for wildcards (makes them less specific than exact matches)
|
|
|
|
|
// ADD to score to make it HIGHER/WORSE
|
|
|
|
|
segments.forEach(seg => {
|
|
|
|
|
if (seg === '**') score += 0.5;
|
|
|
|
|
else if (seg === '*') score += 0.25;
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return score;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Check if a path matches a glob pattern
|
|
|
|
|
* @private
|
|
|
|
|
*/
|
|
|
|
|
private static pathMatchesGlob(path: string, pattern: string): boolean {
|
|
|
|
|
// Handle exact match
|
|
|
|
|
if (pattern === path) return true;
|
|
|
|
|
|
|
|
|
|
const pathParts = path.split('/').filter(p => !!p);
|
|
|
|
|
const patternParts = pattern.split('/').filter(p => !!p);
|
|
|
|
|
|
|
|
|
|
let pathIdx = 0;
|
|
|
|
|
let patternIdx = 0;
|
|
|
|
|
|
|
|
|
|
while (patternIdx < patternParts.length && pathIdx < pathParts.length) {
|
|
|
|
|
const patternPart = patternParts[patternIdx];
|
|
|
|
|
|
|
|
|
|
if (patternPart === '**') {
|
|
|
|
|
// ** matches zero or more path segments
|
|
|
|
|
if (patternIdx === patternParts.length - 1) {
|
|
|
|
|
// ** at the end matches everything
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
// Try matching from next pattern part onwards
|
|
|
|
|
const nextPattern = patternParts[patternIdx + 1];
|
|
|
|
|
while (pathIdx < pathParts.length) {
|
|
|
|
|
if (PathEvent.pathMatchesGlob(pathParts.slice(pathIdx).join('/'), patternParts.slice(patternIdx + 1).join('/'))) {
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
pathIdx++;
|
|
|
|
|
}
|
|
|
|
|
return false;
|
|
|
|
|
} else if (patternPart === '*') {
|
|
|
|
|
// * matches exactly one segment
|
|
|
|
|
pathIdx++;
|
|
|
|
|
patternIdx++;
|
|
|
|
|
} else {
|
|
|
|
|
// Exact match required
|
|
|
|
|
if (patternPart !== pathParts[pathIdx]) {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
pathIdx++;
|
|
|
|
|
patternIdx++;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Check if we've consumed all pattern parts
|
|
|
|
|
if (patternIdx < patternParts.length) {
|
|
|
|
|
// Remaining pattern parts must all be ** to match
|
|
|
|
|
return patternParts.slice(patternIdx).every(p => p === '**');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return pathIdx === pathParts.length;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Combine multiple events into one parsed object. Longest path takes precedent, but all subsequent methods are
|
|
|
|
|
* combined until a "none" is reached
|
|
|
|
|
@@ -135,40 +253,79 @@ export class PathEvent {
|
|
|
|
|
* @return {PathEvent} Final combined permission
|
|
|
|
|
*/
|
|
|
|
|
static combine(...paths: (string | PathEvent)[]): PathEvent {
|
|
|
|
|
let hitNone = false;
|
|
|
|
|
const combined = paths.map(p => p instanceof PathEvent ? p : new PathEvent(p))
|
|
|
|
|
.toSorted((p1, p2) => {
|
|
|
|
|
const l1 = p1.fullPath.length, l2 = p2.fullPath.length;
|
|
|
|
|
return l1 < l2 ? 1 : (l1 > l2 ? -1 : 0);
|
|
|
|
|
}).reduce((acc, p) => {
|
|
|
|
|
if(acc && !acc.fullPath.startsWith(p.fullPath)) return acc;
|
|
|
|
|
if(p.none) hitNone = true;
|
|
|
|
|
if(!acc) return p;
|
|
|
|
|
if(hitNone) return acc;
|
|
|
|
|
acc.methods = new ASet([...acc.methods, ...p.methods]);
|
|
|
|
|
return acc;
|
|
|
|
|
}, <any>null);
|
|
|
|
|
return combined;
|
|
|
|
|
const parsed = paths.map(p => p instanceof PathEvent ? p : new PathEvent(p));
|
|
|
|
|
|
|
|
|
|
// Sort by specificity: lower score = more specific = higher priority
|
|
|
|
|
const sorted = parsed.toSorted((p1, p2) => {
|
|
|
|
|
const score1 = PathEvent.scoreSpecificity(p1.fullPath);
|
|
|
|
|
const score2 = PathEvent.scoreSpecificity(p2.fullPath);
|
|
|
|
|
return score1 - score2;
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
let result: PathEvent | null = null;
|
|
|
|
|
|
|
|
|
|
for (const p of sorted) {
|
|
|
|
|
if (!result) {
|
|
|
|
|
result = p;
|
|
|
|
|
} else {
|
|
|
|
|
// Only combine if current result's path starts with or matches the new permission's path
|
|
|
|
|
if (result.fullPath.startsWith(p.fullPath)) {
|
|
|
|
|
// If we hit a none at a parent level, stop here
|
|
|
|
|
if (p.none) {
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
// Combine methods for permissions in the same hierarchy
|
|
|
|
|
result.methods = new ASet([...result.methods, ...p.methods]);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return result || new PathEvent('');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Filter a set of paths based on the target
|
|
|
|
|
*
|
|
|
|
|
* @param {string | PathEvent | (string | PathEvent)[]} target Array of events that will filtered
|
|
|
|
|
* @param filter {...PathEvent} Must container one of
|
|
|
|
|
* @return {boolean} Whether there is any overlap
|
|
|
|
|
* @param filter {...PathEvent} Must contain one of
|
|
|
|
|
* @return {PathEvent[]} Filtered results
|
|
|
|
|
*/
|
|
|
|
|
static filter(target: string | PathEvent | (string | PathEvent)[], ...filter: (string | PathEvent)[]): PathEvent[] {
|
|
|
|
|
const parsedTarget = makeArray(target).map(pe => pe instanceof PathEvent ? pe : new PathEvent(pe));
|
|
|
|
|
const parsedFilter = makeArray(filter).map(pe => pe instanceof PathEvent ? pe : new PathEvent(pe));
|
|
|
|
|
return parsedTarget.filter(t => !!parsedFilter.find(r => {
|
|
|
|
|
const wildcard = r.fullPath == '*' || t.fullPath == '*';
|
|
|
|
|
const p1 = r.fullPath.includes('*') ? r.fullPath.slice(0, r.fullPath.indexOf('*')) : r.fullPath;
|
|
|
|
|
const p2 = t.fullPath.includes('*') ? t.fullPath.slice(0, t.fullPath.indexOf('*')) : t.fullPath;
|
|
|
|
|
const scope = p1.startsWith(p2) || p2.startsWith(p1);
|
|
|
|
|
const methods = r.all || t.all || r.methods.intersection(t.methods).length;
|
|
|
|
|
return (wildcard || scope) && methods;
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
return parsedTarget.filter(t => {
|
|
|
|
|
const combined = PathEvent.combine(t);
|
|
|
|
|
return !!parsedFilter.find(r => PathEvent.matches(r, combined));
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Check if a filter pattern matches a target path
|
|
|
|
|
* @private
|
|
|
|
|
*/
|
|
|
|
|
private static matches(pattern: PathEvent, target: PathEvent): boolean {
|
|
|
|
|
// Handle special cases
|
|
|
|
|
if (pattern.fullPath === '' || target.fullPath === '') return false;
|
|
|
|
|
if (pattern.fullPath === '*' || target.fullPath === '*') return pattern.methods.has('*') || target.methods.has('*') || pattern.methods.intersection(target.methods).length > 0;
|
|
|
|
|
|
|
|
|
|
// Check methods
|
|
|
|
|
const methodsMatch = pattern.all || target.all || pattern.methods.intersection(target.methods).length > 0;
|
|
|
|
|
if (!methodsMatch) return false;
|
|
|
|
|
|
|
|
|
|
// Check paths
|
|
|
|
|
if (!pattern.hasGlob && !target.hasGlob) {
|
|
|
|
|
// Fast path: no globs, use string comparison
|
|
|
|
|
return pattern.fullPath === target.fullPath;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (pattern.hasGlob) {
|
|
|
|
|
// Pattern has glob, match target against it
|
|
|
|
|
return this.pathMatchesGlob(target.fullPath, pattern.fullPath);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Target has glob but pattern doesn't - pattern must match within target's glob range
|
|
|
|
|
return this.pathMatchesGlob(pattern.fullPath, target.fullPath);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
@@ -181,14 +338,11 @@ export class PathEvent {
|
|
|
|
|
static has(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): boolean {
|
|
|
|
|
const parsedTarget = makeArray(target).map(pe => pe instanceof PathEvent ? pe : new PathEvent(pe));
|
|
|
|
|
const parsedRequired = makeArray(has).map(pe => pe instanceof PathEvent ? pe : new PathEvent(pe));
|
|
|
|
|
return !!parsedRequired.find(r => !!parsedTarget.find(t => {
|
|
|
|
|
const wildcard = r.fullPath == '*' || t.fullPath == '*';
|
|
|
|
|
const p1 = r.fullPath.includes('*') ? r.fullPath.slice(0, r.fullPath.indexOf('*')) : r.fullPath;
|
|
|
|
|
const p2 = t.fullPath.includes('*') ? t.fullPath.slice(0, t.fullPath.indexOf('*')) : t.fullPath;
|
|
|
|
|
const scope = p1.startsWith(p2); // Note: Original had || p2.startsWith(p1) here, but has implies target has required.
|
|
|
|
|
const methods = r.all || t.all || r.methods.intersection(t.methods).length;
|
|
|
|
|
return (wildcard || scope) && methods;
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
// If target is a single item, check directly; if multiple, combine first
|
|
|
|
|
const effectiveTarget = parsedTarget.length === 1 ? parsedTarget[0] : PathEvent.combine(...parsedTarget);
|
|
|
|
|
|
|
|
|
|
return !!parsedRequired.find(r => PathEvent.matches(r, effectiveTarget));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
@@ -196,7 +350,7 @@ export class PathEvent {
|
|
|
|
|
*
|
|
|
|
|
* @param {string | PathEvent | (string | PathEvent)[]} target Array of Events as strings or pre-parsed
|
|
|
|
|
* @param has Target must have all these paths
|
|
|
|
|
* @return {boolean} Whether there is any overlap
|
|
|
|
|
* @return {boolean} Whether all are present
|
|
|
|
|
*/
|
|
|
|
|
static hasAll(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): boolean {
|
|
|
|
|
return has.filter(h => PathEvent.has(target, h)).length == has.length;
|
|
|
|
|
@@ -205,7 +359,7 @@ export class PathEvent {
|
|
|
|
|
/**
|
|
|
|
|
* Same as `has` but raises an error if there is no overlap
|
|
|
|
|
*
|
|
|
|
|
* @param {string | string[]} target Array of Events as strings or pre-parsed
|
|
|
|
|
* @param {string | PathEvent | (string | PathEvent)[]} target Array of Events as strings or pre-parsed
|
|
|
|
|
* @param has Target must have at least one of these path
|
|
|
|
|
*/
|
|
|
|
|
static hasFatal(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): void {
|
|
|
|
|
@@ -215,7 +369,7 @@ export class PathEvent {
|
|
|
|
|
/**
|
|
|
|
|
* Same as `hasAll` but raises an error if the target is missing any paths
|
|
|
|
|
*
|
|
|
|
|
* @param {string | string[]} target Array of Events as strings or pre-parsed
|
|
|
|
|
* @param {string | PathEvent | (string | PathEvent)[]} target Array of Events as strings or pre-parsed
|
|
|
|
|
* @param has Target must have all these paths
|
|
|
|
|
*/
|
|
|
|
|
static hasAllFatal(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): void {
|
|
|
|
|
@@ -250,7 +404,7 @@ export class PathEvent {
|
|
|
|
|
* Squash 2 sets of paths & return true if the target has all paths
|
|
|
|
|
*
|
|
|
|
|
* @param has Target must have all these paths
|
|
|
|
|
* @return {boolean} Whether there is any overlap
|
|
|
|
|
* @return {boolean} Whether all are present
|
|
|
|
|
*/
|
|
|
|
|
hasAll(...has: (string | PathEvent)[]): boolean {
|
|
|
|
|
return PathEvent.hasAll(this, ...has);
|
|
|
|
|
@@ -278,7 +432,7 @@ export class PathEvent {
|
|
|
|
|
* Filter a set of paths based on this event
|
|
|
|
|
*
|
|
|
|
|
* @param {string | PathEvent | (string | PathEvent)[]} target Array of events that will filtered
|
|
|
|
|
* @return {boolean} Whether there is any overlap
|
|
|
|
|
* @return {PathEvent[]} Filtered results
|
|
|
|
|
*/
|
|
|
|
|
filter(target: string | PathEvent | (string | PathEvent)[]): PathEvent[] {
|
|
|
|
|
return PathEvent.filter(target, this);
|
|
|
|
|
@@ -317,7 +471,7 @@ export class PathEventEmitter implements IPathEventEmitter{
|
|
|
|
|
emit(event: Event, ...args: any[]) {
|
|
|
|
|
const parsed = event instanceof PathEvent ? event : new PathEvent(`${this.prefix}/${event}`);
|
|
|
|
|
this.listeners.filter(l => PathEvent.has(l[0], parsed))
|
|
|
|
|
.forEach(async l => l[1](parsed, ...args));
|
|
|
|
|
.forEach(l => l[1](parsed, ...args));
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
off(listener: PathListener) {
|
|
|
|
|
@@ -326,9 +480,21 @@ export class PathEventEmitter implements IPathEventEmitter{
|
|
|
|
|
|
|
|
|
|
on(event: Event | Event[], listener: PathListener): PathUnsubscribe {
|
|
|
|
|
makeArray(event).forEach(e => {
|
|
|
|
|
if(typeof e == 'string' && e[0] == '*' && this.prefix) e = e.slice(1);
|
|
|
|
|
let fullEvent: string;
|
|
|
|
|
if(typeof e === 'string') {
|
|
|
|
|
// If event starts with ':', it's a scope specifier - prepend prefix
|
|
|
|
|
if(e[0] === ':' && this.prefix) {
|
|
|
|
|
fullEvent = `${this.prefix}${e}`;
|
|
|
|
|
} else if(this.prefix) {
|
|
|
|
|
fullEvent = `${this.prefix}/${e}`;
|
|
|
|
|
} else {
|
|
|
|
|
fullEvent = e;
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
fullEvent = e instanceof PathEvent ? PathEvent.toString(e.fullPath, e.methods) : (e as string);
|
|
|
|
|
}
|
|
|
|
|
this.listeners.push([
|
|
|
|
|
e instanceof PathEvent ? e : new PathEvent(`${this.prefix}/${e}`),
|
|
|
|
|
new PathEvent(fullEvent),
|
|
|
|
|
listener
|
|
|
|
|
])
|
|
|
|
|
});
|
|
|
|
|
@@ -346,6 +512,6 @@ export class PathEventEmitter implements IPathEventEmitter{
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
relayEvents(emitter: IPathEventEmitter) {
|
|
|
|
|
emitter.on('*', (event, ...args) => this.emit(event, ...args));
|
|
|
|
|
emitter.on('**', (event, ...args) => this.emit(event, ...args));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|