-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathaccess-groups.ts
More file actions
374 lines (345 loc) · 12.3 KB
/
access-groups.ts
File metadata and controls
374 lines (345 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/**
* Contains the [[AccessGroups]]
* and [[AccessGroupsOptions]] classes
* @packageDocumentation
*/
import { NamedNode, sym, Store } from 'rdflib'
import { ACLbyCombination, readACL } from './acl'
import * as widgets from '../widgets'
import ns from '../ns'
import { AccessController } from './access-controller'
import { AgentMapMap, ComboList, PartialAgentTriple } from './types'
import { AddAgentButtons } from './add-agent-buttons'
import * as debug from '../debug'
import { style } from '../style'
const ACL = ns.acl
const COLLOQUIAL = {
13: 'Owners',
9: 'Owners (write locked)',
5: 'Editors',
3: 'Posters',
2: 'Submitters',
1: 'Viewers'
}
const RECOMMENDED = {
13: true,
5: true,
3: true,
2: true,
1: true
}
const EXPLANATION = {
13: 'can read, write, and control sharing.',
9: 'can read and control sharing, currently write-locked.',
5: 'can read and change information',
3: 'can add new information, and read but not change existing information',
2: 'can add new information but not read any',
1: 'can read but not change information'
}
/**
* Type for the options parameter of [[AccessGroups]]
*/
export interface AccessGroupsOptions {
defaults?: boolean
}
/**
* Renders the table of Owners, Editors, Posters, Submitters, Viewers
* for https://github.com/solidos/userguide/blob/main/views/sharing/userguide.md
*/
export class AccessGroups {
private readonly defaults: boolean
public byCombo: ComboList
public aclMap: AgentMapMap
private readonly addAgentButton: AddAgentButtons
private readonly rootElement: HTMLElement
private _store: Store // @@ was LiveStore but does not need to be connected to web
constructor (
private doc: NamedNode,
private aclDoc: NamedNode,
public controller: AccessController,
store: Store, // @@ was LiveStore
private _options: AccessGroupsOptions = {}
) {
this.defaults = this._options.defaults || false
this._store = store
this.aclMap = readACL(doc, aclDoc, store, this.defaults)
this.byCombo = ACLbyCombination(this.aclMap)
this.addAgentButton = new AddAgentButtons(this)
this.rootElement = this.controller.dom.createElement('div')
this.rootElement.setAttribute('style', style.accessGroupList)
}
public get store () {
return this._store
}
public set store (store) {
this._store = store
this.aclMap = readACL(this.doc, this.aclDoc, store, this.defaults)
this.byCombo = ACLbyCombination(this.aclMap)
}
public render (): HTMLElement {
this.rootElement.innerHTML = ''
this.renderGroups().forEach(group => this.rootElement.appendChild(group))
if (this.controller.isEditable) {
this.rootElement.appendChild(this.addAgentButton.render())
}
return this.rootElement
}
private renderGroups (): HTMLElement[] {
const groupElements: HTMLElement[] = []
for (let comboIndex = 15; comboIndex > 0; comboIndex--) {
const combo = kToCombo(comboIndex)
if ((this.controller.isEditable && RECOMMENDED[comboIndex]) || this.byCombo[combo]) {
groupElements.push(this.renderGroup(comboIndex, combo))
}
}
return groupElements
}
private renderGroup (comboIndex: number, combo: string): HTMLElement {
const groupRow = this.controller.dom.createElement('div')
groupRow.setAttribute('style', style.accessGroupListItem)
widgets.makeDropTarget(groupRow, (uris) => this.handleDroppedUris(uris, combo)
.then(() => this.controller.render())
.catch(error => this.controller.renderStatus(error)))
const groupColumns = this.renderGroupElements(comboIndex, combo)
groupColumns.forEach(column => groupRow.appendChild(column))
return groupRow
}
private renderGroupElements (comboIndex, combo): HTMLElement[] {
const groupNameColumn = this.controller.dom.createElement('div')
groupNameColumn.setAttribute('style', style.group)
if (this.controller.isEditable) {
switch (comboIndex) {
case 1:
groupNameColumn.setAttribute('style', style.group1)
break
case 2:
groupNameColumn.setAttribute('style', style.group2)
break
case 3:
groupNameColumn.setAttribute('style', style.group3)
break
case 5:
groupNameColumn.setAttribute('style', style.group5)
break
case 9:
groupNameColumn.setAttribute('style', style.group9)
break
case 13:
groupNameColumn.setAttribute('style', style.group13)
break
default:
groupNameColumn.setAttribute('style', style.group)
}
}
groupNameColumn.innerText = COLLOQUIAL[comboIndex] || ktToList(comboIndex)
const groupAgentsColumn = this.controller.dom.createElement('div')
groupAgentsColumn.setAttribute('style', style.group)
if (this.controller.isEditable) {
switch (comboIndex) {
case 1:
groupAgentsColumn.setAttribute('style', style.group1)
break
case 2:
groupAgentsColumn.setAttribute('style', style.group2)
break
case 3:
groupAgentsColumn.setAttribute('style', style.group3)
break
case 5:
groupAgentsColumn.setAttribute('style', style.group5)
break
case 9:
groupAgentsColumn.setAttribute('style', style.group9)
break
case 13:
groupAgentsColumn.setAttribute('style', style.group13)
break
default:
groupAgentsColumn.setAttribute('style', style.group)
}
}
const groupAgentsTable = groupAgentsColumn.appendChild(this.controller.dom.createElement('table'))
const combos = this.byCombo[combo] || []
combos
.map(([pred, obj]) => this.renderAgent(groupAgentsTable, combo, pred, obj))
.forEach(agentElement => groupAgentsTable.appendChild(agentElement))
const groupDescriptionElement = this.controller.dom.createElement('div')
groupDescriptionElement.setAttribute('style', style.group)
if (this.controller.isEditable) {
switch (comboIndex) {
case 1:
groupDescriptionElement.setAttribute('style', style.group1)
break
case 2:
groupDescriptionElement.setAttribute('style', style.group2)
break
case 3:
groupDescriptionElement.setAttribute('style', style.group3)
break
case 5:
groupDescriptionElement.setAttribute('style', style.group5)
break
case 9:
groupDescriptionElement.setAttribute('style', style.group9)
break
case 13:
groupDescriptionElement.setAttribute('style', style.group13)
break
default:
groupDescriptionElement.setAttribute('style', style.group)
}
}
groupDescriptionElement.innerText = EXPLANATION[comboIndex] || 'Unusual combination'
return [groupNameColumn, groupAgentsColumn, groupDescriptionElement]
}
private renderAgent (groupAgentsTable, combo, pred, obj): HTMLElement {
const personRow = widgets.personTR(this.controller.dom, ACL(pred), sym(obj), this.controller.isEditable
? {
deleteFunction: () => this.deleteAgent(combo, pred, obj)
.then(() => groupAgentsTable.removeChild(personRow))
.catch(error => this.controller.renderStatus(error))
}
: {})
return personRow
}
private async deleteAgent (combo, pred, obj): Promise<void> {
const combos = this.byCombo[combo] || []
const comboToRemove = combos.find(([comboPred, comboObj]) => comboPred === pred && comboObj === obj)
if (comboToRemove) {
combos.splice(combos.indexOf(comboToRemove), 1)
}
await this.controller.save()
}
public async addNewURI (uri: string): Promise<void> {
await this.handleDroppedUri(uri, kToCombo(1))
await this.controller.save()
}
private async handleDroppedUris (uris: string[], combo: string): Promise<void> {
try {
await Promise.all(uris.map(uri => this.handleDroppedUri(uri, combo)))
await this.controller.save()
} catch (error) {
return Promise.reject(error)
}
}
private async handleDroppedUri (uri: string, combo: string, secondAttempt: boolean = false): Promise<void> {
const agent = findAgent(uri, this.store) // eg 'agent', 'origin', agentClass'
const thing = sym(uri)
if (!agent && !secondAttempt) {
debug.log(` Not obvious: looking up dropped thing ${thing}`)
try {
await this._store?.fetcher?.load(thing.doc())
} catch (error) {
const message = `Ignore error looking up dropped thing: ${error}`
debug.error(message)
return Promise.reject(new Error(message))
}
return this.handleDroppedUri(uri, combo, true)
} else if (!agent) {
const detectedTypes = Object.keys(this.store.findTypeURIs(thing))
const typeDetails = detectedTypes.length > 0
? `Detected RDF types: ${detectedTypes.join(', ')}`
: 'No RDF type was detected for this URI.'
const error =
`Error: Failed to add access target: ${uri} is not a recognized ACL target type.` +
' Expected one of: vcard:WebID, vcard:Group, foaf:Person, foaf:Agent, solid:AppProvider, solid:AppProviderClass, or recognized ACL classes.' +
' Hint: try dropping a WebID profile URI, a vcard:Group URI, or a web app origin.' +
typeDetails
debug.error(error)
return Promise.reject(new Error(error))
}
this.setACLCombo(combo, uri, agent, this.controller.subject)
}
private setACLCombo (combo: string, uri: string, res: PartialAgentTriple, subject: NamedNode): void {
if (!(combo in this.byCombo)) {
this.byCombo[combo] = []
}
this.removeAgentFromCombos(uri) // Combos are mutually distinct
this.byCombo[combo].push([res.pred, res.obj.uri])
debug.log(`ACL: setting access to ${subject} by ${res.pred}: ${res.obj}`)
}
private removeAgentFromCombos (uri: string): void {
for (let k = 0; k < 16; k++) {
const combos = this.byCombo[kToCombo(k)]
if (combos) {
for (let i = 0; i < combos.length; i++) {
while (i < combos.length && combos[i][1] === uri) {
combos.splice(i, 1)
}
}
}
}
}
}
function kToCombo (k: number): string {
const y = ['Read', 'Append', 'Write', 'Control']
const combo: string[] = []
for (let i = 0; i < 4; i++) {
if (k & (1 << i)) {
combo.push('http://www.w3.org/ns/auth/acl#' + y[i])
}
}
combo.sort()
return combo.join('\n')
}
function ktToList (k: number): string {
let list = ''
const y = ['Read', 'Append', 'Write', 'Control']
for (let i = 0; i < 4; i++) {
if (k & (1 << i)) {
list += y[i]
}
}
return list
}
function findAgent (uri, kb): PartialAgentTriple | null {
const obj = sym(uri)
const types = kb.findTypeURIs(obj)
for (const ty in types) {
debug.log(' drop object type includes: ' + ty)
}
// An Origin URI is one like https://fred.github.io eith no trailing slash
if (uri.startsWith('http') && uri.split('/').length === 3) {
// there is no third slash
return { pred: 'origin', obj } // The only way to know an origin alas
}
// @@ This is an almighty kludge needed because drag and drop adds extra slashes to origins
if (
uri.startsWith('http') &&
uri.split('/').length === 4 &&
uri.endsWith('/')
) {
// there IS third slash
debug.log('Assuming final slash on dragged origin URI was unintended!')
return { pred: 'origin', obj: sym(uri.slice(0, -1)) } // Fix a URI where the drag and drop system has added a spurious slash
}
if (ns.vcard('WebID').uri in types) return { pred: 'agent', obj }
if (ns.vcard('Group').uri in types) {
return { pred: 'agentGroup', obj } // @@ note vcard membership not RDFs
}
if (
obj.sameTerm(ns.foaf('Agent')) ||
obj.sameTerm(ns.acl('AuthenticatedAgent')) || // AuthenticatedAgent
obj.sameTerm(ns.rdf('Resource')) ||
obj.sameTerm(ns.owl('Thing'))
) {
return { pred: 'agentClass', obj }
}
if (
ns.vcard('Individual').uri in types ||
ns.foaf('Person').uri in types ||
ns.foaf('Agent').uri in types
) {
const pref = kb.any(obj, ns.foaf('preferredURI'))
if (pref) return { pred: 'agent', obj: sym(pref) }
return { pred: 'agent', obj }
}
if (ns.solid('AppProvider').uri in types) {
return { pred: 'origin', obj }
}
if (ns.solid('AppProviderClass').uri in types) {
return { pred: 'originClass', obj }
}
debug.log(' Triage fails for ' + uri)
return null
}