Compare commits

...

3 Commits

Author SHA1 Message Date
9cf86f4be1 Fixed path events
All checks were successful
Build / Publish Docs (push) Successful in 49s
Build / Build NPM Project (push) Successful in 1m4s
Build / Tag Version (push) Successful in 9s
2025-11-29 21:58:04 -05:00
2240c93db5 Fixed path events
All checks were successful
Build / Publish Docs (push) Successful in 48s
Build / Build NPM Project (push) Successful in 1m6s
Build / Tag Version (push) Successful in 9s
2025-11-29 20:03:45 -05:00
3e9052c4a7 Fixed path event has checks
All checks were successful
Build / Publish Docs (push) Successful in 1m1s
Build / Build NPM Project (push) Successful in 1m16s
Build / Tag Version (push) Successful in 8s
2025-11-29 11:27:47 -05:00
3 changed files with 92 additions and 155 deletions

View File

@@ -1,6 +1,6 @@
{ {
"name": "@ztimson/utils", "name": "@ztimson/utils",
"version": "0.27.12", "version": "0.27.15",
"description": "Utility library", "description": "Utility library",
"author": "Zak Timson", "author": "Zak Timson",
"license": "MIT", "license": "MIT",

View File

@@ -40,6 +40,7 @@ export function PE(str: TemplateStringsArray, ...args: any[]) {
* @param {TemplateStringsArray} str * @param {TemplateStringsArray} str
* @param {string} args * @param {string} args
* @return {string} * @return {string}
* @constructor
*/ */
export function PES(str: TemplateStringsArray, ...args: any[]) { export function PES(str: TemplateStringsArray, ...args: any[]) {
let combined = []; let combined = [];
@@ -108,35 +109,21 @@ export class PathEvent {
return; return;
} }
// Check cache first
if(PathEvent.pathEventCache.has(e)) { if(PathEvent.pathEventCache.has(e)) {
Object.assign(this, PathEvent.pathEventCache.get(e)!); Object.assign(this, PathEvent.pathEventCache.get(e)!);
return; return;
} }
let [p, method] = e.replaceAll(/\/{2,}/g, '/').split(':'); let [p, method] = e.replaceAll(/(^|\/)\*+\/?$/g, '').split(':');
if(!method) method = '*'; if(!method) method = '*';
// Handle special cases // Handle special cases
if(p === '' || p === undefined) { if(p === '' || p === undefined || p === '*') {
// 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.module = '';
this.path = ''; this.path = '';
this.fullPath = '**'; this.fullPath = '**';
this.name = ''; this.name = '';
this.methods = new ASet<Method>(['*']); this.methods = new ASet<Method>(p === '*' ? ['*'] : <any>method.split(''));
this.hasGlob = true; this.hasGlob = true;
PathEvent.pathEventCache.set(e, this); PathEvent.pathEventCache.set(e, this);
return; return;
@@ -147,17 +134,74 @@ export class PathEvent {
this.path = temp.join('/'); this.path = temp.join('/');
this.fullPath = `${this.module}${this.module && this.path ? '/' : ''}${this.path}`; this.fullPath = `${this.module}${this.module && this.path ? '/' : ''}${this.path}`;
this.name = temp.pop() || ''; 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.hasGlob = this.fullPath.includes('*');
this.methods = new ASet(<any>method.split('')); this.methods = new ASet(<any>method.split(''));
// Store in cache
PathEvent.pathEventCache.set(e, this); PathEvent.pathEventCache.set(e, this);
} }
/**
* Check if a filter pattern matches a target path
* @private
*/
private static matches(pattern: PathEvent, target: PathEvent): boolean {
const methodsMatch = pattern.all || target.all || pattern.methods.intersection(target.methods).length > 0;
if(!methodsMatch) return false;
if(!pattern.hasGlob && !target.hasGlob) {
const last = pattern.fullPath[target.fullPath.length];
return pattern.fullPath.startsWith(target.fullPath) && (last == null || last == '/');
}
if(pattern.hasGlob) return this.pathMatchesGlob(target.fullPath, pattern.fullPath);
return this.pathMatchesGlob(pattern.fullPath, target.fullPath);
}
/**
* Check if a path matches a glob pattern
* @private
*/
private static pathMatchesGlob(path: string, pattern: string): boolean {
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 === '**') {
if(patternIdx === patternParts.length - 1) return true;
while (pathIdx < pathParts.length) {
if(PathEvent.pathMatchesGlob(pathParts.slice(pathIdx).join('/'), patternParts.slice(patternIdx + 1).join('/'))) return true;
pathIdx++;
}
return false;
} else if(patternPart === '*') {
pathIdx++;
patternIdx++;
} else {
if(patternPart !== pathParts[pathIdx]) return false;
pathIdx++;
patternIdx++;
}
}
if(patternIdx < patternParts.length) return patternParts.slice(patternIdx).every(p => p === '**');
return pathIdx === pathParts.length;
}
/**
* 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;
const segments = path.split('/').filter(p => !!p);
let score = -segments.length;
segments.forEach(seg => {
if(seg === '**') score += 0.5;
else if(seg === '*') score += 0.25;
});
return score;
}
/** Clear the cache of all PathEvents */ /** Clear the cache of all PathEvents */
static clearCache(): void { static clearCache(): void {
PathEvent.pathEventCache.clear(); PathEvent.pathEventCache.clear();
@@ -168,82 +212,6 @@ export class PathEvent {
PathEvent.permissionCache.clear(); 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 * Combine multiple events into one parsed object. Longest path takes precedent, but all subsequent methods are
* combined until a "none" is reached * combined until a "none" is reached
@@ -253,32 +221,22 @@ export class PathEvent {
*/ */
static combine(...paths: (string | PathEvent)[]): PathEvent { static combine(...paths: (string | PathEvent)[]): PathEvent {
const parsed = paths.map(p => p instanceof PathEvent ? p : new PathEvent(p)); 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 sorted = parsed.toSorted((p1, p2) => {
const score1 = PathEvent.scoreSpecificity(p1.fullPath); const score1 = PathEvent.scoreSpecificity(p1.fullPath);
const score2 = PathEvent.scoreSpecificity(p2.fullPath); const score2 = PathEvent.scoreSpecificity(p2.fullPath);
return score1 - score2; return score1 - score2;
}); });
let result: PathEvent | null = null; let result: PathEvent | null = null;
for (const p of sorted) { for (const p of sorted) {
if(!result) { if(!result) {
result = p; result = p;
} else { } else {
// Only combine if current result's path starts with or matches the new permission's path
if(result.fullPath.startsWith(p.fullPath)) { if(result.fullPath.startsWith(p.fullPath)) {
// If we hit a none at a parent level, stop here if(p.none) break;
if (p.none) {
break;
}
// Combine methods for permissions in the same hierarchy
result.methods = new ASet([...result.methods, ...p.methods]); result.methods = new ASet([...result.methods, ...p.methods]);
} }
} }
} }
return result || new PathEvent(''); return result || new PathEvent('');
} }
@@ -292,39 +250,7 @@ export class PathEvent {
static filter(target: string | PathEvent | (string | PathEvent)[], ...filter: (string | PathEvent)[]): PathEvent[] { 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 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)); const parsedFilter = makeArray(filter).map(pe => pe instanceof PathEvent ? pe : new PathEvent(pe));
return parsedTarget.filter(t => !!parsedFilter.find(r => PathEvent.matches(r, t)));
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);
} }
/** /**
@@ -337,11 +263,7 @@ export class PathEvent {
static has(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): boolean { 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 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)); const parsedRequired = makeArray(has).map(pe => pe instanceof PathEvent ? pe : new PathEvent(pe));
return !!parsedRequired.find(r => !!parsedTarget.find(t => PathEvent.matches(r, t)));
// 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));
} }
/** /**

View File

@@ -48,10 +48,9 @@ describe('Path Events', () => {
expect(pe.hasAll('module:c', 'some/path:ud')).toBeTruthy(); expect(pe.hasAll('module:c', 'some/path:ud')).toBeTruthy();
}); });
it('parses empty string as none', () => { it('parses empty string as wildcard', () => {
const pe = new PathEvent(''); const pe = new PathEvent('');
expect(pe.none).toBe(true); expect(pe.has('any/path:c')).toBe(true);
expect(pe.fullPath).toBe('');
}); });
it('parses none method', () => { it('parses none method', () => {
@@ -61,6 +60,10 @@ describe('Path Events', () => {
expect(pe.none).toBe(false); expect(pe.none).toBe(false);
}); });
it('Test several wild card perms', () => {
expect(PathEvent.has(['actions:*', 'groups:*', 'users:*'], 'groups/AUTH:r')).toBe(true);
});
it('setters for methods', () => { it('setters for methods', () => {
const pe = new PathEvent('users/system:r'); const pe = new PathEvent('users/system:r');
pe.create = true; pe.create = true;
@@ -81,6 +84,7 @@ describe('Path Events', () => {
expect(c.methods.has('c')).toBe(true); expect(c.methods.has('c')).toBe(true);
expect(c.methods.has('r')).toBe(true); expect(c.methods.has('r')).toBe(true);
expect(c.methods.has('u')).toBe(true); expect(c.methods.has('u')).toBe(true);
expect(c.delete).toBe(false);
}); });
it('combine stops at none', () => { it('combine stops at none', () => {
@@ -95,6 +99,17 @@ describe('Path Events', () => {
expect(d.none).toBe(false); expect(d.none).toBe(false);
}); });
it('combine works with wildcards', () => {
expect(PathEvent.has([
'payments/anonymous:d',
'payments/anonymous:c',
'payments/system:cr',
'logs/Momentum:c',
'products:r',
'*'
], 'actions/692a92d18afa11e6722e9f2e:r')).toBe(true);
});
it('filter finds overlap by path and methods', () => { it('filter finds overlap by path and methods', () => {
const events = [ const events = [
new PathEvent('users/sys:cr'), new PathEvent('users/sys:cr'),