ldap-rest 0.4.6 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/bin/sync-james.mjs +6 -2
  2. package/dist/bin/index.js +1 -1
  3. package/dist/config/args.js +1 -1
  4. package/dist/lib/auth/base.js +1 -1
  5. package/dist/lib/ldapSchema.js +1 -0
  6. package/dist/plugins/auth/authzPerRoute.js +1 -1
  7. package/dist/plugins/auth/rateLimit.js +1 -1
  8. package/dist/plugins/ldap/organizations.js +1 -1
  9. package/dist/plugins/ldap/raw.js +1 -0
  10. package/dist/plugins/twake/appAccountsApi.js +1 -1
  11. package/dist/plugins/weblogs.js +1 -1
  12. package/dist/src/bin/index.d.ts +112 -0
  13. package/dist/src/browser/ldap-browser/LdapBrowser.d.ts +52 -0
  14. package/dist/src/browser/ldap-browser/api/RawApiClient.d.ts +64 -0
  15. package/dist/src/browser/ldap-browser/components/EntryTree.d.ts +75 -0
  16. package/dist/src/browser/ldap-browser/components/EntryView.d.ts +56 -0
  17. package/dist/src/browser/ldap-browser/index.d.ts +9 -0
  18. package/dist/src/browser/ldap-browser/schema.d.ts +62 -0
  19. package/dist/src/browser/ldap-browser/types.d.ts +96 -0
  20. package/dist/src/config/args.d.ts +6 -0
  21. package/dist/src/lib/auth/base.d.ts +82 -1
  22. package/dist/src/lib/ldapSchema.d.ts +159 -0
  23. package/dist/src/plugins/ldap/raw.d.ts +251 -0
  24. package/dist/src/plugins/weblogs.d.ts +7 -0
  25. package/docs/client-development/browser/libraries.md +142 -1
  26. package/docs/usage/configuration.md +20 -0
  27. package/docs/usage/plugins/README.md +10 -9
  28. package/docs/usage/plugins/auth/README.md +57 -0
  29. package/docs/usage/plugins/auth/rate-limit.md +9 -0
  30. package/docs/usage/plugins/integrations/app-accounts.md +32 -0
  31. package/docs/usage/plugins/ldap/README.md +12 -0
  32. package/docs/usage/plugins/ldap/raw.md +226 -0
  33. package/docs/usage/plugins/utilities/weblogs.md +47 -0
  34. package/examples/web/README.md +18 -0
  35. package/examples/web/ldap-browser.html +94 -0
  36. package/package.json +37 -1
  37. package/static/browser/ldap-browser/LdapBrowser.js +199 -0
  38. package/static/browser/ldap-browser/LdapBrowser.js.map +1 -0
  39. package/static/browser/ldap-browser/api/RawApiClient.js +103 -0
  40. package/static/browser/ldap-browser/api/RawApiClient.js.map +1 -0
  41. package/static/browser/ldap-browser/components/EntryTree.js +235 -0
  42. package/static/browser/ldap-browser/components/EntryTree.js.map +1 -0
  43. package/static/browser/ldap-browser/components/EntryView.js +183 -0
  44. package/static/browser/ldap-browser/components/EntryView.js.map +1 -0
  45. package/static/browser/ldap-browser/index.js +4 -0
  46. package/static/browser/ldap-browser/index.js.map +1 -0
  47. package/static/browser/ldap-browser/schema.js +135 -0
  48. package/static/browser/ldap-browser/schema.js.map +1 -0
  49. package/static/browser/ldap-browser/types.js +2 -0
  50. package/static/browser/ldap-browser/types.js.map +1 -0
  51. package/static/browser/ldap-browser.css +2 -0
  52. package/static/browser/ldap-browser.css.map +1 -0
  53. package/static/browser/ldap-browser.esm.js +915 -0
  54. package/static/browser/ldap-browser.esm.js.map +1 -0
  55. package/static/browser/ldap-browser.js +925 -0
  56. package/static/browser/ldap-browser.js.map +1 -0
  57. package/static/browser/ldap-browser.min.js +2 -0
  58. package/static/browser/ldap-browser.min.js.map +1 -0
  59. package/static/browser/ldap-unit-editor/components/UnitTree.js +0 -1
  60. package/static/browser/ldap-unit-editor/components/UnitTree.js.map +1 -1
  61. package/static/browser/ldap-unit-editor.esm.js +0 -1
  62. package/static/browser/ldap-unit-editor.esm.js.map +1 -1
  63. package/static/browser/ldap-unit-editor.js +0 -1
  64. package/static/browser/ldap-unit-editor.js.map +1 -1
  65. package/static/browser/ldap-unit-editor.min.js.map +1 -1
@@ -0,0 +1,915 @@
1
+ /**
2
+ * DOM utility functions
3
+ * @module browser/shared/utils/dom
4
+ */
5
+ /**
6
+ * Escape HTML special characters to prevent XSS attacks
7
+ * Reference: https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html
8
+ */
9
+ function escapeHtml(text) {
10
+ if (text == null)
11
+ return '';
12
+ const map = {
13
+ '&': '&',
14
+ '<': '&lt;',
15
+ '>': '&gt;',
16
+ '"': '&quot;',
17
+ "'": '&#x27;',
18
+ '/': '&#x2F;',
19
+ };
20
+ return String(text).replace(/[&<>"'/]/g, m => map[m]);
21
+ }
22
+
23
+ /**
24
+ * Client of the low-level LDAP API (`core/ldap/raw` plugin).
25
+ * @module browser/ldap-browser/api/RawApiClient
26
+ */
27
+ class RawApiClient {
28
+ constructor(baseUrl = '', authToken) {
29
+ this.baseUrl = baseUrl.replace(/\/$/, '');
30
+ this.authToken = authToken;
31
+ }
32
+ /**
33
+ * Issue a GET on the raw API and decode its JSON answer.
34
+ *
35
+ * @param path path below `/api/v1/ldap/raw`
36
+ * @returns decoded body
37
+ * @throws Error carrying the server message when the status is not 2xx
38
+ */
39
+ async get(path) {
40
+ const headers = { Accept: 'application/json' };
41
+ if (this.authToken)
42
+ headers.Authorization = `Bearer ${this.authToken}`;
43
+ const response = await fetch(`${this.baseUrl}/api/v1/ldap/raw${path}`, {
44
+ headers,
45
+ });
46
+ if (!response.ok) {
47
+ let message = response.statusText;
48
+ try {
49
+ const body = (await response.json());
50
+ if (body.error)
51
+ message = body.error;
52
+ }
53
+ catch {
54
+ // keep the status text
55
+ }
56
+ throw new Error(`${response.status}: ${message}`);
57
+ }
58
+ return (await response.json());
59
+ }
60
+ /**
61
+ * Subtrees the server exposes, used as roots of the tree.
62
+ *
63
+ * @returns list of base DNs
64
+ */
65
+ async getBases() {
66
+ const data = await this.get('/bases');
67
+ return data.bases;
68
+ }
69
+ /**
70
+ * Server capabilities.
71
+ *
72
+ * @returns root DSE
73
+ */
74
+ getRootDse() {
75
+ return this.get('/rootdse');
76
+ }
77
+ /**
78
+ * Directory schema.
79
+ *
80
+ * @returns object classes, attribute types, syntaxes and matching rules
81
+ */
82
+ getSchema() {
83
+ return this.get('/schema');
84
+ }
85
+ /**
86
+ * Read one entry.
87
+ *
88
+ * @param dn DN of the entry
89
+ * @returns the entry with all its attributes
90
+ */
91
+ getEntry(dn) {
92
+ return this.get(`/entry/${encodeURIComponent(dn)}`);
93
+ }
94
+ /**
95
+ * List the direct children of an entry.
96
+ *
97
+ * @param dn DN of the parent
98
+ * @param withChildrenFlag ask the server which children have children
99
+ * @returns children sorted by RDN, with the truncation flag
100
+ */
101
+ getChildren(dn, withChildrenFlag = true) {
102
+ return this.get(`/children/${encodeURIComponent(dn)}${withChildrenFlag ? '?children=1' : ''}`);
103
+ }
104
+ /**
105
+ * Run a search.
106
+ *
107
+ * @param params search base, scope, filter and limit
108
+ * @returns matching entries
109
+ */
110
+ search(params) {
111
+ const query = new URLSearchParams({ base: params.base });
112
+ if (params.scope)
113
+ query.set('scope', params.scope);
114
+ if (params.filter)
115
+ query.set('filter', params.filter);
116
+ if (params.attributes?.length)
117
+ query.set('attributes', params.attributes.join(','));
118
+ if (params.limit)
119
+ query.set('limit', String(params.limit));
120
+ return this.get(`/search?${query.toString()}`);
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Base class for browser components with proper lifecycle management
126
+ * Ensures all event listeners and intervals are cleaned up on destroy
127
+ * @module browser/shared/components/DisposableComponent
128
+ */
129
+ class DisposableComponent {
130
+ constructor() {
131
+ this._eventListeners = [];
132
+ this._intervals = [];
133
+ this._isDestroyed = false;
134
+ }
135
+ /**
136
+ * Register an event listener for automatic cleanup
137
+ * Use this instead of element.addEventListener directly
138
+ */
139
+ addManagedEventListener(target, type, listener, options) {
140
+ if (this._isDestroyed)
141
+ return;
142
+ target.addEventListener(type, listener, options);
143
+ this._eventListeners.push({ target, type, listener, options });
144
+ }
145
+ /**
146
+ * Register an interval for automatic cleanup
147
+ * Use this instead of setInterval directly
148
+ */
149
+ addManagedInterval(callback, ms) {
150
+ const id = setInterval(callback, ms);
151
+ this._intervals.push(id);
152
+ return id;
153
+ }
154
+ /**
155
+ * Check if the component has been destroyed
156
+ */
157
+ get isDestroyed() {
158
+ return this._isDestroyed;
159
+ }
160
+ /**
161
+ * Clean up all managed resources
162
+ * Override in subclasses but ALWAYS call super.destroy()
163
+ */
164
+ destroy() {
165
+ if (this._isDestroyed)
166
+ return;
167
+ this._isDestroyed = true;
168
+ // Remove all event listeners
169
+ for (const { target, type, listener, options } of this._eventListeners) {
170
+ target.removeEventListener(type, listener, options);
171
+ }
172
+ this._eventListeners = [];
173
+ // Clear all intervals
174
+ for (const id of this._intervals) {
175
+ clearInterval(id);
176
+ }
177
+ this._intervals = [];
178
+ }
179
+ }
180
+
181
+ /**
182
+ * Lazy directory tree: one root per exposed base, children fetched on expand.
183
+ * @module browser/ldap-browser/components/EntryTree
184
+ */
185
+ /** Icon picked from the object classes of an entry */
186
+ function iconFor(objectClass) {
187
+ const classes = objectClass.map(c => c.toLowerCase());
188
+ if (classes.includes('organizationalunit') ||
189
+ classes.includes('organization'))
190
+ return 'folder';
191
+ if (classes.includes('groupofnames') ||
192
+ classes.includes('groupofuniquenames') ||
193
+ classes.includes('posixgroup'))
194
+ return 'group';
195
+ if (classes.includes('inetorgperson') ||
196
+ classes.includes('person') ||
197
+ classes.includes('organizationalperson'))
198
+ return 'person';
199
+ if (classes.includes('domain') || classes.includes('dcobject'))
200
+ return 'dns';
201
+ return 'article';
202
+ }
203
+ class EntryTree extends DisposableComponent {
204
+ constructor(container, api, onSelect, onError) {
205
+ super();
206
+ this.roots = [];
207
+ this.children = new Map();
208
+ this.expanded = new Set();
209
+ this.loading = new Set();
210
+ this.selectedDn = null;
211
+ this.container = container;
212
+ this.api = api;
213
+ this.onSelect = onSelect;
214
+ this.onError = onError;
215
+ this.addManagedEventListener(this.container, 'click', event => {
216
+ const target = event.target.closest('[data-dn]');
217
+ if (!target)
218
+ return;
219
+ const dn = target.dataset.dn;
220
+ if (target.classList.contains('ldap-browser-tree__toggle')) {
221
+ void this.toggle(dn);
222
+ }
223
+ else {
224
+ void this.select(dn);
225
+ }
226
+ });
227
+ }
228
+ /**
229
+ * Load the exposed bases and draw them as roots.
230
+ *
231
+ * @param bases base DNs to use as roots
232
+ */
233
+ async init(bases) {
234
+ this.roots = bases;
235
+ // Open the first root so the tree is never empty on arrival
236
+ if (bases.length > 0)
237
+ await this.expand(bases[0]);
238
+ this.render();
239
+ }
240
+ /**
241
+ * DN currently highlighted in the tree.
242
+ *
243
+ * @returns selected DN, or null
244
+ */
245
+ getSelectedDn() {
246
+ return this.selectedDn;
247
+ }
248
+ /**
249
+ * Highlight an entry and notify the parent component.
250
+ *
251
+ * @param dn DN to select
252
+ * @returns whatever the selection handler returns, so callers can await
253
+ * the entry actually being displayed
254
+ */
255
+ select(dn) {
256
+ this.selectedDn = dn;
257
+ this.render();
258
+ return this.onSelect(dn);
259
+ }
260
+ /**
261
+ * Expand the tree down to a DN, loading every level on the way, then
262
+ * select it. Used to follow a search result or a DN typed by the user.
263
+ *
264
+ * @param dn DN to reveal
265
+ */
266
+ async revealAndSelect(dn) {
267
+ const root = this.roots.find(base => dn.toLowerCase() === base.toLowerCase() ||
268
+ dn.toLowerCase().endsWith(`,${base.toLowerCase()}`));
269
+ if (root) {
270
+ // Walk down from the root, expanding each ancestor
271
+ const relative = dn
272
+ .substring(0, dn.length - root.length)
273
+ .replace(/,$/, '');
274
+ const rdns = relative ? splitDn(relative) : [];
275
+ let current = root;
276
+ await this.expand(current);
277
+ // Expand the ancestors only: the target itself stays closed
278
+ for (let i = rdns.length - 1; i >= 1; i--) {
279
+ current = `${rdns[i]},${current}`;
280
+ await this.expand(current);
281
+ }
282
+ }
283
+ await this.select(dn);
284
+ }
285
+ /**
286
+ * Drop cached children so the next expand hits the server again.
287
+ *
288
+ * @param dn DN whose children must be reloaded, or undefined for all
289
+ */
290
+ invalidate(dn) {
291
+ if (dn)
292
+ this.children.delete(dn);
293
+ else
294
+ this.children.clear();
295
+ }
296
+ /**
297
+ * Expand a node, fetching its children the first time.
298
+ *
299
+ * @param dn DN of the node
300
+ */
301
+ async expand(dn) {
302
+ this.expanded.add(dn);
303
+ if (this.children.has(dn))
304
+ return;
305
+ this.loading.add(dn);
306
+ this.render();
307
+ try {
308
+ this.children.set(dn, await this.api.getChildren(dn));
309
+ }
310
+ catch (err) {
311
+ this.expanded.delete(dn);
312
+ this.onError(err);
313
+ }
314
+ finally {
315
+ this.loading.delete(dn);
316
+ this.render();
317
+ }
318
+ }
319
+ /**
320
+ * Expand or collapse a node.
321
+ *
322
+ * @param dn DN of the node
323
+ */
324
+ async toggle(dn) {
325
+ if (this.expanded.has(dn)) {
326
+ this.expanded.delete(dn);
327
+ this.render();
328
+ return;
329
+ }
330
+ await this.expand(dn);
331
+ }
332
+ /** Redraw the whole tree */
333
+ render() {
334
+ if (this.isDestroyed)
335
+ return;
336
+ this.container.innerHTML = `<ul class="ldap-browser-tree">${this.roots
337
+ .map(root => this.renderNode(root, root, ['dcObject'], true))
338
+ .join('')}</ul>`;
339
+ }
340
+ /**
341
+ * Render one node and, when expanded, its children.
342
+ *
343
+ * @param dn DN of the node
344
+ * @param label text shown for the node
345
+ * @param objectClass object classes, used to pick the icon
346
+ * @param expandable whether the node may have children
347
+ * @returns HTML of the node
348
+ */
349
+ renderNode(dn, label, objectClass, expandable) {
350
+ const isExpanded = this.expanded.has(dn);
351
+ const isLoading = this.loading.has(dn);
352
+ const isSelected = this.selectedDn === dn;
353
+ const children = this.children.get(dn);
354
+ const toggle = expandable
355
+ ? `<span class="ldap-browser-tree__toggle material-icons" data-dn="${escapeHtml(dn)}">${isLoading
356
+ ? 'hourglass_empty'
357
+ : isExpanded
358
+ ? 'expand_more'
359
+ : 'chevron_right'}</span>`
360
+ : '<span class="ldap-browser-tree__toggle ldap-browser-tree__toggle--leaf"></span>';
361
+ const sub = isExpanded && children
362
+ ? `<ul>${children.children.length === 0
363
+ ? '<li class="ldap-browser-tree__empty">(no child)</li>'
364
+ : children.children
365
+ .map(child => this.renderNode(child.dn, child.rdn, child.objectClass, child.hasChildren))
366
+ .join('')}${children.truncated
367
+ ? `<li class="ldap-browser-tree__truncated" title="Raise --ldap-raw-max-results to see more">
368
+ first ${children.children.length} entries only — use the search to find the others
369
+ </li>`
370
+ : ''}</ul>`
371
+ : '';
372
+ return `<li>
373
+ <div class="ldap-browser-tree__node${isSelected ? ' ldap-browser-tree__node--selected' : ''}">
374
+ ${toggle}
375
+ <span class="ldap-browser-tree__label" data-dn="${escapeHtml(dn)}" title="${escapeHtml(dn)}">
376
+ <span class="material-icons">${iconFor(objectClass)}</span>
377
+ <span class="ldap-browser-tree__name">${escapeHtml(label)}</span>
378
+ </span>
379
+ </div>
380
+ ${sub}
381
+ </li>`;
382
+ }
383
+ }
384
+ /**
385
+ * Split a DN into its components, honouring `\,` escapes.
386
+ *
387
+ * @param dn DN to split
388
+ * @returns RDN components, outermost first
389
+ */
390
+ function splitDn(dn) {
391
+ const parts = [];
392
+ let current = '';
393
+ for (let i = 0; i < dn.length; i++) {
394
+ if (dn[i] === '\\' && i + 1 < dn.length) {
395
+ current += dn[i] + dn[i + 1];
396
+ i++;
397
+ }
398
+ else if (dn[i] === ',') {
399
+ parts.push(current.trim());
400
+ current = '';
401
+ }
402
+ else {
403
+ current += dn[i];
404
+ }
405
+ }
406
+ if (current.trim())
407
+ parts.push(current.trim());
408
+ return parts;
409
+ }
410
+
411
+ /**
412
+ * Attribute table of one entry, annotated with the directory schema.
413
+ * @module browser/ldap-browser/components/EntryView
414
+ */
415
+ /** Operational attributes are shown apart from the ones the admin sets */
416
+ const OPERATIONAL_USAGE = new Set([
417
+ 'directoryOperation',
418
+ 'distributedOperation',
419
+ 'dSAOperation',
420
+ ]);
421
+ class EntryView {
422
+ constructor(container, schema) {
423
+ this.container = container;
424
+ this.schema = schema;
425
+ }
426
+ /** Draw the placeholder shown when nothing is selected */
427
+ renderEmpty() {
428
+ this.container.innerHTML = `
429
+ <div class="ldap-browser-entry__empty">
430
+ <span class="material-icons">description</span>
431
+ <p>Select an entry in the tree</p>
432
+ </div>`;
433
+ }
434
+ /**
435
+ * Draw an error in place of the entry.
436
+ *
437
+ * @param message message to display
438
+ */
439
+ renderError(message) {
440
+ this.container.innerHTML = `<div class="ldap-browser-entry__error">${escapeHtml(message)}</div>`;
441
+ }
442
+ /** Draw a loading indicator */
443
+ renderLoading() {
444
+ this.container.innerHTML =
445
+ '<div class="ldap-browser-entry__loading">Loading…</div>';
446
+ }
447
+ /**
448
+ * Draw an entry: its DN, its object classes with the attributes they allow,
449
+ * then the attribute table.
450
+ *
451
+ * @param entry entry to display
452
+ */
453
+ render(entry) {
454
+ const objectClasses = entry.attributes.objectClass?.values || [];
455
+ const resolved = this.schema?.resolveAttributes(objectClasses);
456
+ const mandatory = new Set((resolved?.must || []).map(name => name.toLowerCase()));
457
+ const present = new Set(Object.keys(entry.attributes).map(name => name.split(';')[0].toLowerCase()));
458
+ const names = Object.keys(entry.attributes).sort((a, b) => a.localeCompare(b));
459
+ const isOperational = (name) => {
460
+ const type = this.schema?.getAttributeType(name);
461
+ return type ? OPERATIONAL_USAGE.has(type.usage) : false;
462
+ };
463
+ const userAttributes = names.filter(name => !isOperational(name));
464
+ const operational = names.filter(isOperational);
465
+ // Mandatory attributes the entry does not carry: the directory should
466
+ // reject that, but a UI that hides it makes debugging harder
467
+ const missing = (resolved?.must || []).filter(name => !present.has(name.toLowerCase()));
468
+ this.container.innerHTML = `
469
+ <div class="ldap-browser-entry">
470
+ <h2 class="ldap-browser-entry__dn" title="${escapeHtml(entry.dn)}">
471
+ <span class="material-icons">description</span>
472
+ ${escapeHtml(entry.dn || '(root DSE)')}
473
+ </h2>
474
+
475
+ ${this.renderObjectClasses(objectClasses, resolved)}
476
+
477
+ ${missing.length
478
+ ? `<p class="ldap-browser-entry__warning">
479
+ Missing mandatory attribute(s): ${escapeHtml(missing.join(', '))}
480
+ </p>`
481
+ : ''}
482
+
483
+ ${this.renderTable(entry, mandatory, userAttributes, 'Attributes')}
484
+ ${operational.length
485
+ ? this.renderTable(entry, mandatory, operational, 'Operational attributes')
486
+ : ''}
487
+ </div>`;
488
+ }
489
+ /**
490
+ * Render the object class list and, when the schema is available, the
491
+ * attributes those classes allow.
492
+ *
493
+ * @param objectClasses object classes of the entry
494
+ * @param resolved mandatory and optional attributes they imply
495
+ * @returns HTML of the section
496
+ */
497
+ renderObjectClasses(objectClasses, resolved) {
498
+ if (objectClasses.length === 0)
499
+ return '';
500
+ const chips = objectClasses
501
+ .map(name => {
502
+ const definition = this.schema?.getObjectClass(name);
503
+ const title = definition
504
+ ? `${definition.kind}${definition.desc ? ` — ${definition.desc}` : ''}`
505
+ : 'unknown in schema';
506
+ return `<span class="ldap-browser-chip${definition ? '' : ' ldap-browser-chip--unknown'}" title="${escapeHtml(title)}">${escapeHtml(name)}</span>`;
507
+ })
508
+ .join('');
509
+ const allowed = resolved
510
+ ? `<div class="ldap-browser-entry__allowed">
511
+ <span><strong>Required:</strong> ${escapeHtml(resolved.must.join(', ') || '—')}</span>
512
+ <span><strong>Allowed:</strong> ${escapeHtml(resolved.may.join(', ') || '—')}</span>
513
+ </div>`
514
+ : '';
515
+ return `<div class="ldap-browser-entry__classes">${chips}</div>${allowed}`;
516
+ }
517
+ /**
518
+ * Render one attribute table.
519
+ *
520
+ * @param entry entry being displayed
521
+ * @param mandatory lowercase names of the mandatory attributes
522
+ * @param names attributes to include, in display order
523
+ * @param title heading of the table
524
+ * @returns HTML of the table
525
+ */
526
+ renderTable(entry, mandatory, names, title) {
527
+ if (names.length === 0)
528
+ return '';
529
+ const rows = names
530
+ .map(name => {
531
+ const attribute = entry.attributes[name];
532
+ const type = this.schema?.getAttributeType(name);
533
+ const isMandatory = mandatory.has(name.split(';')[0].toLowerCase());
534
+ const tooltip = type
535
+ ? [
536
+ type.desc,
537
+ type.syntax ? `syntax ${type.syntax}` : '',
538
+ type.singleValue ? 'single-valued' : '',
539
+ type.noUserModification ? 'read-only' : '',
540
+ ]
541
+ .filter(Boolean)
542
+ .join(' — ')
543
+ : 'unknown in schema';
544
+ return `<tr>
545
+ <th class="${isMandatory ? 'ldap-browser-attr--must' : ''}${type ? '' : ' ldap-browser-attr--unknown'}" title="${escapeHtml(tooltip)}">
546
+ ${escapeHtml(name)}${isMandatory ? ' *' : ''}
547
+ </th>
548
+ <td>${this.renderValues(name, attribute)}</td>
549
+ </tr>`;
550
+ })
551
+ .join('');
552
+ return `<h3 class="ldap-browser-entry__section">${escapeHtml(title)}</h3>
553
+ <table class="ldap-browser-entry__table"><tbody>${rows}</tbody></table>`;
554
+ }
555
+ /**
556
+ * Render the values of one attribute: images as thumbnails, other binary
557
+ * values as their size plus the base64 payload, text as text.
558
+ *
559
+ * @param name attribute name
560
+ * @param attribute values and binary flag
561
+ * @returns HTML of the value cell
562
+ */
563
+ renderValues(name, attribute) {
564
+ return attribute.values
565
+ .map(value => {
566
+ if (attribute.binary && this.schema?.isImageAttribute(name))
567
+ // Keep only base64 characters: the value ends up in an attribute
568
+ return `<img class="ldap-browser-entry__photo" alt="${escapeHtml(name)}" src="data:image/jpeg;base64,${value.replace(/[^A-Za-z0-9+/=]/g, '')}" />`;
569
+ if (attribute.binary)
570
+ return `<details class="ldap-browser-entry__binary">
571
+ <summary>${byteLength(value)} bytes (base64)</summary>
572
+ <code>${escapeHtml(value)}</code>
573
+ </details>`;
574
+ return `<div class="ldap-browser-entry__value">${escapeHtml(value)}</div>`;
575
+ })
576
+ .join('');
577
+ }
578
+ }
579
+ /**
580
+ * Decoded size of a base64 payload, without decoding it.
581
+ *
582
+ * @param base64 base64-encoded value
583
+ * @returns number of octets
584
+ */
585
+ function byteLength(base64) {
586
+ const padding = base64.endsWith('==') ? 2 : base64.endsWith('=') ? 1 : 0;
587
+ return Math.max(0, Math.floor((base64.length * 3) / 4) - padding);
588
+ }
589
+
590
+ /**
591
+ * Client-side view of the directory schema: the lookups the UI needs to
592
+ * annotate an entry (mandatory attributes, descriptions, binary values).
593
+ *
594
+ * This mirrors `src/lib/ldapSchema.ts` on the server, minus the parsing:
595
+ * the browser receives the schema already parsed.
596
+ *
597
+ * @module browser/ldap-browser/schema
598
+ */
599
+ /** Syntaxes whose values are octets rather than text */
600
+ const BINARY_SYNTAXES = new Set([
601
+ '1.3.6.1.4.1.1466.115.121.1.5',
602
+ '1.3.6.1.4.1.1466.115.121.1.8',
603
+ '1.3.6.1.4.1.1466.115.121.1.9',
604
+ '1.3.6.1.4.1.1466.115.121.1.10',
605
+ '1.3.6.1.4.1.1466.115.121.1.28',
606
+ '1.3.6.1.4.1.1466.115.121.1.40',
607
+ '1.3.6.1.4.1.1466.115.121.1.49',
608
+ ]);
609
+ /** Attributes whose values are images, previewed as such */
610
+ const IMAGE_ATTRIBUTES = new Set([
611
+ 'jpegphoto',
612
+ 'photo',
613
+ 'thumbnailphoto',
614
+ 'thumbnaillogo',
615
+ ]);
616
+ class SchemaView {
617
+ constructor(schema) {
618
+ this.objectClasses = new Map();
619
+ this.attributeTypes = new Map();
620
+ this.schema = schema;
621
+ for (const oc of schema.objectClasses) {
622
+ this.objectClasses.set(oc.oid.toLowerCase(), oc);
623
+ for (const name of oc.names)
624
+ this.objectClasses.set(name.toLowerCase(), oc);
625
+ }
626
+ for (const at of schema.attributeTypes) {
627
+ this.attributeTypes.set(at.oid.toLowerCase(), at);
628
+ for (const name of at.names)
629
+ this.attributeTypes.set(name.toLowerCase(), at);
630
+ }
631
+ }
632
+ /**
633
+ * Look up an object class by name or OID.
634
+ *
635
+ * @param name object class name or OID
636
+ * @returns the definition, or undefined when unknown
637
+ */
638
+ getObjectClass(name) {
639
+ return this.objectClasses.get(name.toLowerCase());
640
+ }
641
+ /**
642
+ * Look up an attribute type by name or OID, ignoring attribute options.
643
+ *
644
+ * @param name attribute name, `;binary` and friends included
645
+ * @returns the definition, or undefined when unknown
646
+ */
647
+ getAttributeType(name) {
648
+ return this.attributeTypes.get(name.split(';')[0].toLowerCase());
649
+ }
650
+ /**
651
+ * Resolve the syntax of an attribute through its `SUP` chain.
652
+ *
653
+ * @param name attribute name
654
+ * @returns syntax OID, or undefined
655
+ */
656
+ getAttributeSyntax(name) {
657
+ const seen = new Set();
658
+ let current = this.getAttributeType(name);
659
+ while (current && !seen.has(current.oid)) {
660
+ if (current.syntax)
661
+ return current.syntax;
662
+ seen.add(current.oid);
663
+ current = current.sup ? this.getAttributeType(current.sup) : undefined;
664
+ }
665
+ return undefined;
666
+ }
667
+ /**
668
+ * Tell whether an attribute is meant to be displayed as an image.
669
+ *
670
+ * @param name attribute name
671
+ * @returns true for photo-like attributes
672
+ */
673
+ isImageAttribute(name) {
674
+ return IMAGE_ATTRIBUTES.has(name.split(';')[0].toLowerCase());
675
+ }
676
+ /**
677
+ * Tell whether an attribute holds octets rather than text.
678
+ *
679
+ * @param name attribute name
680
+ * @returns true when values are binary
681
+ */
682
+ isBinaryAttribute(name) {
683
+ if (name
684
+ .split(';')
685
+ .slice(1)
686
+ .some(o => o.toLowerCase() === 'binary'))
687
+ return true;
688
+ const syntax = this.getAttributeSyntax(name);
689
+ return syntax ? BINARY_SYNTAXES.has(syntax) : false;
690
+ }
691
+ /**
692
+ * Collect the mandatory and optional attributes of a set of object
693
+ * classes, walking every `SUP` chain.
694
+ *
695
+ * @param objectClasses object class names carried by an entry
696
+ * @returns `must` and `may` attribute names, `may` excluding mandatory ones
697
+ */
698
+ resolveAttributes(objectClasses) {
699
+ const must = new Set();
700
+ const may = new Set();
701
+ const visited = new Set();
702
+ const walk = (name) => {
703
+ const key = name.toLowerCase();
704
+ if (visited.has(key))
705
+ return;
706
+ visited.add(key);
707
+ const oc = this.getObjectClass(name);
708
+ if (!oc)
709
+ return;
710
+ oc.must.forEach(a => must.add(a));
711
+ oc.may.forEach(a => may.add(a));
712
+ oc.sup.forEach(walk);
713
+ };
714
+ objectClasses.forEach(walk);
715
+ const mustLower = new Set([...must].map(a => a.toLowerCase()));
716
+ return {
717
+ must: [...must],
718
+ may: [...may].filter(a => !mustLower.has(a.toLowerCase())),
719
+ };
720
+ }
721
+ }
722
+
723
+ /**
724
+ * Low-level LDAP browser: a tree of the directory on the left, the raw
725
+ * content of the selected entry on the right, and a filter search on top.
726
+ *
727
+ * Read-only: it renders what the `core/ldap/raw` plugin serves.
728
+ *
729
+ * @module browser/ldap-browser/LdapBrowser
730
+ */
731
+ class LdapBrowser {
732
+ constructor(options) {
733
+ this.container = null;
734
+ this.tree = null;
735
+ this.entryView = null;
736
+ this.schema = null;
737
+ this.bases = [];
738
+ this.currentDn = null;
739
+ this.options = options;
740
+ this.api = new RawApiClient(options.apiBaseUrl || '', options.authToken);
741
+ }
742
+ /**
743
+ * Build the interface, load the schema and open the first base.
744
+ *
745
+ * @throws Error when the container does not exist or the API is unreachable
746
+ */
747
+ async init() {
748
+ const container = document.getElementById(this.options.containerId);
749
+ if (!container)
750
+ throw new Error(`Container element with id '${this.options.containerId}' not found`);
751
+ this.container = container;
752
+ this.bases = await this.api.getBases();
753
+ this.render();
754
+ // The schema only decorates the display: a directory that refuses it
755
+ // must not prevent browsing
756
+ try {
757
+ this.schema = new SchemaView(await this.api.getSchema());
758
+ }
759
+ catch (err) {
760
+ this.reportError(err);
761
+ }
762
+ const treeContainer = container.querySelector('.ldap-browser__tree');
763
+ const entryContainer = container.querySelector('.ldap-browser__entry');
764
+ if (!treeContainer || !entryContainer)
765
+ return;
766
+ this.entryView = new EntryView(entryContainer, this.schema);
767
+ this.entryView.renderEmpty();
768
+ this.tree = new EntryTree(treeContainer, this.api, dn => this.showEntry(dn), error => this.reportError(error));
769
+ await this.tree.init(this.bases);
770
+ this.bindToolbar();
771
+ const initial = this.options.initialDn || this.bases[0];
772
+ if (initial)
773
+ await this.tree.revealAndSelect(initial);
774
+ }
775
+ /** Release the listeners held by the tree */
776
+ destroy() {
777
+ this.tree?.destroy();
778
+ this.tree = null;
779
+ }
780
+ /**
781
+ * DN currently displayed.
782
+ *
783
+ * @returns selected DN, or null when none
784
+ */
785
+ getCurrentDn() {
786
+ return this.currentDn;
787
+ }
788
+ /** Draw the static layout */
789
+ render() {
790
+ if (!this.container)
791
+ return;
792
+ this.container.classList.add('ldap-browser-container');
793
+ this.container.innerHTML = `
794
+ <div class="ldap-browser">
795
+ <div class="ldap-browser__toolbar">
796
+ <input class="ldap-browser__filter" type="text"
797
+ placeholder="LDAP filter, e.g. (uid=alice)" />
798
+ <select class="ldap-browser__scope">
799
+ <option value="sub">sub</option>
800
+ <option value="one">one</option>
801
+ <option value="base">base</option>
802
+ </select>
803
+ <select class="ldap-browser__base">
804
+ ${this.bases
805
+ .map(base => `<option value="${escapeHtml(base)}">${escapeHtml(base)}</option>`)
806
+ .join('')}
807
+ </select>
808
+ <button class="ldap-browser__search" type="button">
809
+ <span class="material-icons">search</span> Search
810
+ </button>
811
+ <button class="ldap-browser__refresh" type="button" title="Reload">
812
+ <span class="material-icons">refresh</span>
813
+ </button>
814
+ </div>
815
+ <div class="ldap-browser__body">
816
+ <div class="ldap-browser__tree"></div>
817
+ <div class="ldap-browser__entry"></div>
818
+ </div>
819
+ <div class="ldap-browser__results" hidden></div>
820
+ </div>`;
821
+ }
822
+ /** Wire the search and refresh controls */
823
+ bindToolbar() {
824
+ const filter = this.container?.querySelector('.ldap-browser__filter');
825
+ const searchButton = this.container?.querySelector('.ldap-browser__search');
826
+ const refreshButton = this.container?.querySelector('.ldap-browser__refresh');
827
+ const results = this.container?.querySelector('.ldap-browser__results');
828
+ searchButton?.addEventListener('click', () => void this.runSearch());
829
+ filter?.addEventListener('keydown', event => {
830
+ if (event.key === 'Enter')
831
+ void this.runSearch();
832
+ });
833
+ refreshButton?.addEventListener('click', () => {
834
+ this.tree?.invalidate();
835
+ if (this.currentDn)
836
+ void this.showEntry(this.currentDn);
837
+ });
838
+ results?.addEventListener('click', event => {
839
+ const target = event.target.closest('[data-dn]');
840
+ if (target?.dataset.dn)
841
+ void this.tree?.revealAndSelect(target.dataset.dn);
842
+ });
843
+ }
844
+ /**
845
+ * Load an entry and display it.
846
+ *
847
+ * @param dn DN of the entry
848
+ */
849
+ async showEntry(dn) {
850
+ if (!this.entryView)
851
+ return;
852
+ this.currentDn = dn;
853
+ this.entryView.renderLoading();
854
+ try {
855
+ const entry = await this.api.getEntry(dn);
856
+ this.entryView.render(entry);
857
+ this.options.onEntrySelected?.(dn);
858
+ }
859
+ catch (err) {
860
+ this.entryView.renderError(err.message);
861
+ this.reportError(err);
862
+ }
863
+ }
864
+ /** Run the search typed in the toolbar and list the matching DNs */
865
+ async runSearch() {
866
+ const filter = this.container?.querySelector('.ldap-browser__filter')
867
+ ?.value || '';
868
+ const scope = this.container?.querySelector('.ldap-browser__scope')
869
+ ?.value || 'sub';
870
+ const base = this.container?.querySelector('.ldap-browser__base')
871
+ ?.value || this.bases[0];
872
+ const results = this.container?.querySelector('.ldap-browser__results');
873
+ if (!results)
874
+ return;
875
+ if (!filter.trim()) {
876
+ results.hidden = true;
877
+ results.innerHTML = '';
878
+ return;
879
+ }
880
+ results.hidden = false;
881
+ results.innerHTML = '<p>Searching…</p>';
882
+ try {
883
+ const found = await this.api.search({
884
+ base,
885
+ scope: scope,
886
+ filter,
887
+ attributes: ['dn'],
888
+ });
889
+ results.innerHTML = found.entries.length
890
+ ? `<p>${found.entries.length} result(s)${found.truncated ? ' (truncated)' : ''}</p>
891
+ <ul>${found.entries
892
+ .map(entry => `<li><a href="#" data-dn="${escapeHtml(entry.dn)}">${escapeHtml(entry.dn)}</a></li>`)
893
+ .join('')}</ul>`
894
+ : '<p>No result</p>';
895
+ }
896
+ catch (err) {
897
+ results.innerHTML = `<p class="ldap-browser__error">${escapeHtml(err.message)}</p>`;
898
+ this.reportError(err);
899
+ }
900
+ }
901
+ /**
902
+ * Forward an error to the host page, or log it when no handler was given.
903
+ *
904
+ * @param error error to report
905
+ */
906
+ reportError(error) {
907
+ if (this.options.onError)
908
+ this.options.onError(error);
909
+ else
910
+ console.error('[ldap-browser]', error);
911
+ }
912
+ }
913
+
914
+ export { LdapBrowser, RawApiClient, SchemaView };
915
+ //# sourceMappingURL=ldap-browser.esm.js.map