Skip to content

Commit 918c145

Browse files
committed
directory logic
1 parent b0c6e2c commit 918c145

16 files changed

Lines changed: 1033 additions & 10 deletions

‎package-lock.json‎

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "solid-logic",
3-
"version": "6.0.0",
3+
"version": "6.0.0-1",
44
"description": "Core business logic of SolidOS",
55
"main": "dist/index.cjs.js",
66
"module": "dist/index.esm.js",

‎src/acl/accessControlSubjects.ts‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ export type AccessControlSubject = {
1111
const ACCESS_CONTROL_SUBJECT_GROUPS = {
1212
agentClass: [ns.foaf('Agent'), ns.acl('AuthenticatedAgent'), ns.rdf('Resource'), ns.owl('Thing')],
1313
agent: [ns.vcard('WebID'), ns.vcard('Individual'), ns.foaf('Person'), ns.foaf('Agent')],
14-
group: [ns.vcard('Group')],
14+
agentGroup: [ns.vcard('Group')],
1515
origin: [ns.solid('AppProvider'), ns.solid('AppProviderClass')]
1616
} as const
1717

@@ -26,7 +26,10 @@ function isHttpUrl (value: string): boolean {
2626
function isBareOriginUrl (value: string): boolean {
2727
try {
2828
const parsed = new URL(value)
29-
return parsed.pathname === '/' && !parsed.hash
29+
return (parsed.protocol === 'http:' || parsed.protocol === 'https:') &&
30+
parsed.pathname === '/' &&
31+
!parsed.search &&
32+
!parsed.hash
3033
} catch (_error) {
3134
return false
3235
}
@@ -35,7 +38,12 @@ function isBareOriginUrl (value: string): boolean {
3538
function normalizeOriginUrl (value: string): string {
3639
try {
3740
const parsed = new URL(value)
38-
if (parsed.pathname === '/' && !parsed.hash) {
41+
if (
42+
(parsed.protocol === 'http:' || parsed.protocol === 'https:') &&
43+
parsed.pathname === '/' &&
44+
!parsed.search &&
45+
!parsed.hash
46+
) {
3947
return `${parsed.protocol}//${parsed.host}`
4048
}
4149
} catch (_error) {
@@ -75,7 +83,7 @@ export async function classifyAccessControlSubject (store: LiveStore, principle:
7583
}
7684
}
7785

78-
if (ACCESS_CONTROL_SUBJECT_GROUPS.group.some(term => term.uri in types)) {
86+
if (ACCESS_CONTROL_SUBJECT_GROUPS.agentGroup.some(term => term.uri in types)) {
7987
return { kind: 'agentGroup', subjectValue: principle }
8088
}
8189

‎src/acl/aclLogic.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import type { AclLogic } from '../types'
44
import { ns as namespace } from '../util/ns'
55
import * as accessControlSubjects from './accessControlSubjects'
66

7+
// Will remove the below comment when i'm done with the manage access work
78
// Helpers available from @dokieli/web-access-control:
89
// - Discovery: findEffectiveACL, parentContainer
910
// - ACL context and parsing: buildACLContext, authorizationsFromDataset, parseTurtle
@@ -13,6 +14,9 @@ import * as accessControlSubjects from './accessControlSubjects'
1314
// - Link and allow parsing: allows, parseWacAllow, linkTargets, parseLinkHeader
1415
// - Terms and constants: ACCESS_MODES, ACL, Authenticated, FOAF, modeFromIRI, modeIRI, namedNode, Public, quad, RDF_TYPE, variable
1516

17+
export const ACCESS_ROLES = ['Owner', 'Editor', 'No Access', 'Viewer', 'Poster', 'Submitter'] as const
18+
19+
export type AccessRole = typeof ACCESS_ROLES[number]
1620

1721
export const ACL_LINK = sym(
1822
'http://www.iana.org/assignments/link-relations/acl'
@@ -21,6 +25,25 @@ export const ACL_LINK = sym(
2125
export function createAclLogic(store): AclLogic {
2226

2327
const ns = namespace
28+
const ACCESS_ROLE_RULES: Array<{ label: AccessRole, modes: AccessMode[] }> = [
29+
{ label: 'Owner', modes: ['Read', 'Write', 'Control'] },
30+
{ label: 'Editor', modes: ['Read', 'Write'] },
31+
{ label: 'Poster', modes: ['Append', 'Read'] },
32+
{ label: 'Submitter', modes: ['Append'] },
33+
{ label: 'Viewer', modes: ['Read'] },
34+
{ label: 'No Access', modes: [] }
35+
]
36+
37+
function roleFromModes (modes: Iterable<AccessMode>): AccessRole {
38+
const modeSet = new Set(modes)
39+
const matchingRule = ACCESS_ROLE_RULES.find(rule => rule.label !== 'No Access' && rule.modes.every(mode => modeSet.has(mode)))
40+
41+
return matchingRule?.label ?? 'No Access'
42+
}
43+
44+
function modesFromRole (role: AccessRole): AccessMode[] {
45+
return [...(ACCESS_ROLE_RULES.find(rule => rule.label === role)?.modes ?? [])]
46+
}
2447

2548
function getFetch() {
2649
const fetcher = store.fetcher as {
@@ -207,6 +230,8 @@ export function createAclLogic(store): AclLogic {
207230
findAclDocUrl,
208231
findEffectiveAcl,
209232
findAccessGrants,
233+
roleFromModes,
234+
modesFromRole,
210235
planGrant,
211236
planRevoke,
212237
planPublicRead,

‎src/directory/catalogDirectory.ts‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import { type DirectoryEntry } from '../types'
2+
import { graph, type LiveStore, NamedNode, parse } from 'rdflib'
3+
import { ns } from '../util/ns'
4+
import * as debug from '../util/debug'
5+
import { isHttpUri } from './directoryHelpers'
6+
7+
const CATALOG_VOCAB = 'http://example.org#'
8+
9+
export function createCatalogDirectoryDiscovery () {
10+
const catalogEntriesCache = new Map<string, Promise<DirectoryEntry[]>>()
11+
12+
async function discoverCatalogEntries (
13+
catalogUrl: string,
14+
onEntry: (entry: DirectoryEntry) => void | Promise<void>
15+
): Promise<void> {
16+
const entries = await fetchCatalogEntries(catalogUrl)
17+
for (const entry of entries) {
18+
await onEntry(entry)
19+
}
20+
}
21+
22+
async function fetchCatalogEntries (catalogUrl: string): Promise<DirectoryEntry[]> {
23+
const cached = catalogEntriesCache.get(catalogUrl)
24+
if (cached) {
25+
return cached
26+
}
27+
28+
const promise = loadCatalogEntries(catalogUrl).catch(error => {
29+
catalogEntriesCache.delete(catalogUrl)
30+
throw error
31+
})
32+
33+
catalogEntriesCache.set(catalogUrl, promise)
34+
try {
35+
return await promise
36+
} catch (error) {
37+
debug.warn('[Directory] Error fetching directory catalog:', error)
38+
return []
39+
}
40+
}
41+
42+
async function loadCatalogEntries (catalogUrl: string): Promise<DirectoryEntry[]> {
43+
if (typeof fetch !== 'function') {
44+
throw new Error('Fetch API is unavailable')
45+
}
46+
47+
const response = await fetch(catalogUrl, {
48+
headers: { accept: 'text/turtle' }
49+
})
50+
51+
if (!response.ok) {
52+
throw new Error(`Failed to fetch ${catalogUrl}: ${response.status}`)
53+
}
54+
55+
const turtle = await response.text()
56+
const catalogStore = graph() as LiveStore
57+
parse(turtle, catalogStore, catalogUrl, 'text/turtle')
58+
59+
const personType = new NamedNode(`${CATALOG_VOCAB}Person`)
60+
const webIdPredicate = new NamedNode(`${CATALOG_VOCAB}webid`)
61+
const namePredicate = new NamedNode(`${CATALOG_VOCAB}name`)
62+
const catalogPeople = new Map<string, DirectoryEntry>()
63+
64+
const statements = catalogStore.statementsMatching(undefined, ns.rdf('type'), personType)
65+
for (const statement of statements) {
66+
const subject = statement.subject
67+
const webIdNode = catalogStore.any(subject, webIdPredicate)
68+
if (webIdNode && webIdNode.termType === 'NamedNode') {
69+
const webId = webIdNode.value
70+
const personName = catalogStore.anyValue(subject, namePredicate)
71+
if (isHttpUri(webId) && personName) {
72+
catalogPeople.set(webId, {
73+
kind: 'person',
74+
uri: webId,
75+
label: personName,
76+
subjectType: 'agent',
77+
relationshipLabel: 'People',
78+
sources: ['catalog']
79+
})
80+
}
81+
}
82+
}
83+
84+
return Array.from(catalogPeople.values())
85+
}
86+
87+
return {
88+
discoverCatalogEntries
89+
}
90+
}

‎src/directory/contactsDirectory.ts‎

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
import { type DirectoryEntry, type DirectorySource, type TypeIndexLogic } from '../types'
2+
import { type LiveStore, NamedNode } from 'rdflib'
3+
import { ns } from '../util/ns'
4+
import { isHttpUri, labelForNode, loadDocumentSilently, uniqueNamedNodes } from './directoryHelpers'
5+
6+
const CONTACT_CARD_CONCURRENCY = 8
7+
8+
export function createContactsDirectoryDiscovery (
9+
store: LiveStore,
10+
typeIndexLogic: TypeIndexLogic
11+
) {
12+
const personalAddressBooksCache = new Map<string, Promise<NamedNode[]>>()
13+
const contactWebIdCache = new Map<string, Promise<string | null>>()
14+
15+
async function loadPersonalAddressBooks (user: NamedNode): Promise<NamedNode[]> {
16+
const cached = personalAddressBooksCache.get(user.value)
17+
if (cached) {
18+
return cached
19+
}
20+
21+
const promise = (async () => {
22+
const scopes = await typeIndexLogic.loadTypeIndexesFor(user)
23+
let scopedApps = [] as Awaited<ReturnType<TypeIndexLogic['getScopedAppsFromIndex']>>
24+
25+
for (const scope of scopes) {
26+
const apps = await typeIndexLogic.getScopedAppsFromIndex(scope, ns.vcard('AddressBook'))
27+
scopedApps = scopedApps.concat(apps)
28+
}
29+
30+
return uniqueNamedNodes(scopedApps.map(app => app.instance))
31+
})().catch(error => {
32+
personalAddressBooksCache.delete(user.value)
33+
throw error
34+
})
35+
36+
personalAddressBooksCache.set(user.value, promise)
37+
return promise
38+
}
39+
40+
async function webIdForAddressBookContact (contact: NamedNode): Promise<string | null> {
41+
const cached = contactWebIdCache.get(contact.value)
42+
if (cached) {
43+
return cached
44+
}
45+
46+
const promise = (async () => {
47+
if (!await loadDocumentSilently(store, contact)) {
48+
return null
49+
}
50+
51+
const urlNodes = store.each(contact, ns.vcard('url'), null, contact.doc()) as NamedNode[]
52+
for (const urlNode of urlNodes) {
53+
const webId = resolveWebIdFromAddressBookUrlNode(urlNode, contact.doc())
54+
if (webId) {
55+
return webId
56+
}
57+
}
58+
59+
return null
60+
})().catch(error => {
61+
contactWebIdCache.delete(contact.value)
62+
throw error
63+
})
64+
65+
contactWebIdCache.set(contact.value, promise)
66+
return promise
67+
}
68+
69+
function resolveWebIdFromAddressBookUrlNode (urlNode: NamedNode, doc: NamedNode): string | null {
70+
if (!store.holds(urlNode, ns.rdf('type'), ns.vcard('WebID'), doc)) {
71+
return null
72+
}
73+
74+
const valueNode = store.any(urlNode, ns.vcard('value'), null, doc)
75+
const webId = valueNode?.value || ''
76+
return isHttpUri(webId) ? webId : null
77+
}
78+
79+
async function discoverAddressBookContacts (
80+
user: NamedNode,
81+
onEntry: (entry: DirectoryEntry) => void | Promise<void>
82+
): Promise<void> {
83+
const books = await loadPersonalAddressBooks(user)
84+
85+
for (const book of books) {
86+
if (await loadDocumentSilently(store, book)) {
87+
const nameEmailIndex = store.any(book, ns.vcard('nameEmailIndex'), null, book.doc()) as NamedNode | null
88+
if (nameEmailIndex) {
89+
if (await loadDocumentSilently(store, nameEmailIndex)) {
90+
const contacts = store.each(undefined, ns.vcard('inAddressBook'), book, nameEmailIndex) as NamedNode[]
91+
for (let index = 0; index < contacts.length; index += CONTACT_CARD_CONCURRENCY) {
92+
const batch = contacts.slice(index, index + CONTACT_CARD_CONCURRENCY)
93+
const entries = await Promise.all(batch.map(async contact => {
94+
const webId = await webIdForAddressBookContact(contact)
95+
if (!webId) {
96+
return null
97+
}
98+
99+
return {
100+
kind: 'person' as const,
101+
uri: webId,
102+
label: store.anyValue(contact, ns.vcard('fn'), null, nameEmailIndex) || labelForNode(store, contact),
103+
subjectType: 'agent' as const,
104+
relationshipLabel: 'Contact' as const,
105+
sources: ['contacts'] as DirectorySource[]
106+
}
107+
}))
108+
109+
for (const entry of entries.filter((entry): entry is NonNullable<typeof entry> => Boolean(entry))) {
110+
await onEntry(entry)
111+
}
112+
}
113+
}
114+
}
115+
}
116+
}
117+
}
118+
119+
async function discoverAddressBookGroups (
120+
user: NamedNode,
121+
onEntry: (entry: DirectoryEntry) => void | Promise<void>
122+
): Promise<void> {
123+
const books = await loadPersonalAddressBooks(user)
124+
125+
for (const book of books) {
126+
if (await loadDocumentSilently(store, book)) {
127+
const groupIndex = store.any(book, ns.vcard('groupIndex'), null, book.doc()) as NamedNode | null
128+
if (groupIndex) {
129+
if (await loadDocumentSilently(store, groupIndex)) {
130+
const groups = uniqueNamedNodes([
131+
...(store.each(book, ns.vcard('includesGroup'), null, groupIndex) as NamedNode[]),
132+
...(store.each(book, ns.vcard('includesGroup'), null, book.doc()) as NamedNode[])
133+
])
134+
135+
for (const group of groups) {
136+
await loadDocumentSilently(store, group)
137+
138+
await onEntry({
139+
kind: 'group',
140+
uri: group.value,
141+
label: labelForNode(store, group),
142+
subjectType: 'agentGroup',
143+
relationshipLabel: 'Group',
144+
sources: ['groups']
145+
})
146+
}
147+
}
148+
}
149+
}
150+
}
151+
}
152+
153+
return {
154+
discoverAddressBookContacts,
155+
discoverAddressBookGroups
156+
}
157+
}

0 commit comments

Comments
 (0)