diff --git a/src/middleware/packages/activitypub/constants.js b/src/middleware/packages/activitypub/constants.js index 1e5cc73ea..143bc9b09 100644 --- a/src/middleware/packages/activitypub/constants.js +++ b/src/middleware/packages/activitypub/constants.js @@ -1,5 +1,4 @@ -const appendPrefix = (types) => - Object.fromEntries(Object.entries(types).map(([key, value]) => [key, AS_PREFIX + value])); +const appendPrefix = types => Object.fromEntries(Object.entries(types).map(([key, value]) => [key, AS_PREFIX + value])); const AS_PREFIX = 'https://www.w3.org/ns/activitystreams#'; @@ -33,7 +32,7 @@ const ACTIVITY_TYPES = { TRAVAL: 'Travel', UNDO: 'Undo', UPDATE: 'Update', - VIEW: 'View', + VIEW: 'View' }; const ACTOR_TYPES = { @@ -41,7 +40,7 @@ const ACTOR_TYPES = { GROUP: 'Group', ORGANIZATION: 'Organization', PERSON: 'Person', - SERVICE: 'Service', + SERVICE: 'Service' }; const OBJECT_TYPES = { @@ -56,7 +55,7 @@ const OBJECT_TYPES = { PROFILE: 'Profile', RELATIONSHIP: 'Relationship', TOMBSTONE: 'Tombstone', - VIDEO: 'Video', + VIDEO: 'Video' }; module.exports = { @@ -67,5 +66,5 @@ module.exports = { OBJECT_TYPES, FULL_ACTIVITY_TYPES: appendPrefix(ACTIVITY_TYPES), FULL_ACTOR_TYPES: appendPrefix(ACTOR_TYPES), - FULL_OBJECT_TYPES: appendPrefix(OBJECT_TYPES), + FULL_OBJECT_TYPES: appendPrefix(OBJECT_TYPES) }; diff --git a/src/middleware/packages/activitypub/mixins/activities-handler.js b/src/middleware/packages/activitypub/mixins/activities-handler.js index 774a72287..cb856accf 100644 --- a/src/middleware/packages/activitypub/mixins/activities-handler.js +++ b/src/middleware/packages/activitypub/mixins/activities-handler.js @@ -9,7 +9,7 @@ const ActivitiesHandlerMixin = { methods: { matchActivity(ctx, pattern, activityOrObject) { return matchActivity(ctx, pattern, activityOrObject); - }, + } }, events: { async 'activitypub.outbox.posted'(ctx) { @@ -73,8 +73,8 @@ const ActivitiesHandlerMixin = { } } } - }, - }, + } + } }; module.exports = ActivitiesHandlerMixin; diff --git a/src/middleware/packages/activitypub/mixins/controlled-collection.js b/src/middleware/packages/activitypub/mixins/controlled-collection.js index c1899508a..7994701f8 100644 --- a/src/middleware/packages/activitypub/mixins/controlled-collection.js +++ b/src/middleware/packages/activitypub/mixins/controlled-collection.js @@ -10,7 +10,7 @@ module.exports = { dereferenceItems: false, sort: { predicate: 'as:published', order: 'DESC' }, permissions: null, - controlledActions: {}, + controlledActions: {} }, dependencies: ['activitypub.registry'], async started() { @@ -27,8 +27,8 @@ module.exports = { controlledActions: { get: `${this.name}.get`, post: `${this.name}.post`, - ...this.settings.controlledActions, - }, + ...this.settings.controlledActions + } }); }, actions: { @@ -37,12 +37,12 @@ module.exports = { }, post() { throw new E.ForbiddenError(); - }, + } }, methods: { async getCollectionUri(webId) { // TODO make this work return this.broker.call('activitypub.registry.getUri', { path: this.settings.path, webId }); - }, - }, + } + } }; diff --git a/src/middleware/packages/activitypub/routes/getCollectionRoute.js b/src/middleware/packages/activitypub/routes/getCollectionRoute.js index ae18d3d9a..e4c75f20b 100644 --- a/src/middleware/packages/activitypub/routes/getCollectionRoute.js +++ b/src/middleware/packages/activitypub/routes/getCollectionRoute.js @@ -1,6 +1,6 @@ const { parseHeader, parseJson, saveDatasetMeta } = require('@semapps/middlewares'); -const addCollectionUriMiddleware = (collectionUri) => (req, res, next) => { +const addCollectionUriMiddleware = collectionUri => (req, res, next) => { let fullCollectionUri = collectionUri; // TODO find a tool to parse this automatically if (collectionUri.includes('/:username')) { @@ -25,8 +25,8 @@ const getCollectionRoute = (collectionUri, controlledActions) => { 'GET /': [ ...middlewares, addCollectionUriMiddleware(collectionUri), - (controlledActions && controlledActions.get) || 'activitypub.collection.get', - ], + (controlledActions && controlledActions.get) || 'activitypub.collection.get' + ] }; if (controlledActions && controlledActions.post) { aliases['POST /'] = [...middlewares, addCollectionUriMiddleware(collectionUri), controlledActions.post]; @@ -38,7 +38,7 @@ const getCollectionRoute = (collectionUri, controlledActions) => { authorization: false, authentication: true, bodyParsers: false, - aliases, + aliases }; }; diff --git a/src/middleware/packages/activitypub/services/activity-mapping.js b/src/middleware/packages/activitypub/services/activity-mapping.js index 90dcb237d..7801992a3 100644 --- a/src/middleware/packages/activitypub/services/activity-mapping.js +++ b/src/middleware/packages/activitypub/services/activity-mapping.js @@ -7,9 +7,9 @@ const ActivityMappingService = { settings: { mappers: [], handlebars: { - helpers: {}, + helpers: {} }, - matchAnnouncedActivities: false, + matchAnnouncedActivities: false }, async started() { this.mappers = []; @@ -36,7 +36,7 @@ const ActivityMappingService = { activity = { actor: activity.actor, // Ensure the actor is defined - ...announcedActivity, + ...announcedActivity }; } @@ -57,7 +57,7 @@ const ActivityMappingService = { : {}; } catch (e) { this.logger.warn( - `Could not get profile of actor ${activity.actor} (webId ${ctx.meta.webId} / dataset ${ctx.meta.dataset})`, + `Could not get profile of actor ${activity.actor} (webId ${ctx.meta.webId} / dataset ${ctx.meta.dataset})` ); } @@ -74,7 +74,7 @@ const ActivityMappingService = { return [key, value[locale](templateParams)]; } throw new Error(`No ${locale} locale found for key ${key}`); - }), + }) ); } } @@ -87,7 +87,7 @@ const ActivityMappingService = { this.mappers.push({ match, mapping: this.compileObject(mapping), - priority, + priority }); // Reorder cached mappings @@ -95,7 +95,7 @@ const ActivityMappingService = { }, getMappers() { return this.mappers; - }, + } }, methods: { matchActivity(ctx, pattern, activityOrObject) { @@ -113,11 +113,11 @@ const ActivityMappingService = { return [key, Handlebars.compile(value)]; } return [key, this.compileObject(value)]; - }), + }) ) ); - }, - }, + } + } }; module.exports = ActivityMappingService; diff --git a/src/middleware/packages/activitypub/services/activitypub/index.js b/src/middleware/packages/activitypub/services/activitypub/index.js index 25767ab91..feefdec82 100644 --- a/src/middleware/packages/activitypub/services/activitypub/index.js +++ b/src/middleware/packages/activitypub/services/activitypub/index.js @@ -21,14 +21,14 @@ const ActivityPubService = { queueServiceUrl: null, like: { attachToObjectTypes: null, - attachToActorTypes: null, + attachToActorTypes: null }, follow: { - attachToActorTypes: null, + attachToActorTypes: null }, reply: { - attachToObjectTypes: null, - }, + attachToObjectTypes: null + } }, dependencies: ['api'], created() { @@ -37,16 +37,16 @@ const ActivityPubService = { this.broker.createService(CollectionService, { settings: { jsonContext, - podProvider, - }, + podProvider + } }); this.broker.createService(RegistryService, { settings: { baseUri, jsonContext, - podProvider, - }, + podProvider + } }); this.broker.createService(ActorService, { @@ -54,51 +54,51 @@ const ActivityPubService = { baseUri, jsonContext, selectActorData, - podProvider, - }, + podProvider + } }); this.broker.createService(ObjectService, { settings: { baseUri, - podProvider, - }, + podProvider + } }); this.broker.createService(ActivityService, { settings: { baseUri, - jsonContext, - }, + jsonContext + } }); this.broker.createService(FollowService, { settings: { baseUri, - attachToActorTypes: follow.attachToActorTypes || Object.values(ACTOR_TYPES), - }, + attachToActorTypes: follow.attachToActorTypes || Object.values(ACTOR_TYPES) + } }); this.broker.createService(InboxService, { settings: { baseUri, - podProvider, - }, + podProvider + } }); this.broker.createService(LikeService, { settings: { baseUri, attachToObjectTypes: like.attachToObjectTypes || Object.values(OBJECT_TYPES), - attachToActorTypes: like.attachToActorTypes || Object.values(ACTOR_TYPES), - }, + attachToActorTypes: like.attachToActorTypes || Object.values(ACTOR_TYPES) + } }); this.broker.createService(ReplyService, { settings: { baseUri, - attachToObjectTypes: reply.attachToObjectTypes || Object.values(OBJECT_TYPES), - }, + attachToObjectTypes: reply.attachToObjectTypes || Object.values(OBJECT_TYPES) + } }); this.broker.createService(OutboxService, { @@ -106,10 +106,10 @@ const ActivityPubService = { settings: { baseUri, jsonContext, - podProvider, - }, + podProvider + } }); - }, + } }; module.exports = ActivityPubService; diff --git a/src/middleware/packages/activitypub/services/activitypub/subservices/activity.js b/src/middleware/packages/activitypub/services/activitypub/subservices/activity.js index 6c02be3b8..c25219ceb 100644 --- a/src/middleware/packages/activitypub/services/activitypub/subservices/activity.js +++ b/src/middleware/packages/activitypub/services/activitypub/subservices/activity.js @@ -22,8 +22,8 @@ const ActivityService = { // Activities shouldn't be handled manually patch: 'activitypub.activity.forbidden', put: 'activitypub.activity.forbidden', - delete: 'activitypub.activity.forbidden', - }, + delete: 'activitypub.activity.forbidden' + } }, dependencies: ['ldp.container'], actions: { @@ -53,7 +53,7 @@ const ActivityService = { if (recipient.startsWith(this.settings.baseUri)) { const collection = await ctx.call('activitypub.collection.get', { collectionUri: recipient, - webId: activity.actor, + webId: activity.actor }); if (collection && collection.items) output.push(...defaultToArray(collection.items)); } @@ -73,21 +73,21 @@ const ActivityService = { async getLocalRecipients(ctx) { const { activity } = ctx.params; const recipients = await this.actions.getRecipients({ activity }, { parentCtx: ctx }); - return recipients.filter((recipientUri) => this.isLocalActor(recipientUri)); + return recipients.filter(recipientUri => this.isLocalActor(recipientUri)); }, isPublic(ctx) { const { activity } = ctx.params; // We accept all three representations, as required by https://www.w3.org/TR/activitypub/#public-addressing const publicRepresentations = [PUBLIC_URI, 'Public', 'as:Public']; return defaultToArray(activity.to) - ? defaultToArray(activity.to).some((r) => publicRepresentations.includes(r)) + ? defaultToArray(activity.to).some(r => publicRepresentations.includes(r)) : false; - }, + } }, methods: { isLocalActor(uri) { return uri.startsWith(this.settings.baseUri); - }, + } }, hooks: { before: { @@ -98,14 +98,14 @@ const ActivityService = { }, create(ctx) { ctx.params.resource = objectIdToCurrent(ctx.params.resource); - }, + } }, after: { get(ctx, res) { return objectCurrentToId(res); - }, - }, - }, + } + } + } }; module.exports = ActivityService; diff --git a/src/middleware/packages/activitypub/services/activitypub/subservices/collection.js b/src/middleware/packages/activitypub/services/activitypub/subservices/collection.js index 084a6ece0..a4a62577e 100644 --- a/src/middleware/packages/activitypub/services/activitypub/subservices/collection.js +++ b/src/middleware/packages/activitypub/services/activitypub/subservices/collection.js @@ -4,7 +4,7 @@ const CollectionService = { name: 'activitypub.collection', settings: { jsonContext: ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1'], - podProvider: false, + podProvider: false }, dependencies: ['triplestore', 'ldp.resource'], actions: { @@ -17,17 +17,17 @@ const CollectionService = { const { collectionUri } = ctx.params; const { ordered, summary } = { ...(await ctx.call('activitypub.registry.getByUri', { collectionUri })), - ...ctx.params, + ...ctx.params }; await ctx.call('triplestore.insert', { resource: { '@context': 'https://www.w3.org/ns/activitystreams', id: collectionUri, type: ordered ? ['Collection', 'OrderedCollection'] : 'Collection', - summary, + summary }, contentType: MIME_TYPES.JSON, - webId: 'system', + webId: 'system' }); }, /* @@ -46,7 +46,7 @@ const CollectionService = { } `, accept: MIME_TYPES.JSON, - webId: 'system', + webId: 'system' }); }, /* @@ -66,7 +66,7 @@ const CollectionService = { } `, accept: MIME_TYPES.JSON, - webId: 'system', + webId: 'system' }); return Number(res[0].count.value) === 0; }, @@ -89,7 +89,7 @@ const CollectionService = { } `, accept: MIME_TYPES.JSON, - webId: 'system', + webId: 'system' }); }, /* @@ -113,7 +113,7 @@ const CollectionService = { await ctx.call('triplestore.insert', { resource: `<${collectionUri}> <${itemUri}>`, - webId: 'system', + webId: 'system' }); }, /* @@ -135,7 +135,7 @@ const CollectionService = { WHERE { <${collectionUri}> <${itemUri}> } `, - webId: 'system', + webId: 'system' }); }, /* @@ -151,7 +151,7 @@ const CollectionService = { const webId = ctx.params.webId || ctx.meta.webId || 'anon'; const { dereferenceItems, itemsPerPage, sort } = { ...(await ctx.call('activitypub.registry.getByUri', { collectionUri })), - ...ctx.params, + ...ctx.params }; const collection = await ctx.call('triplestore.query', { @@ -167,7 +167,7 @@ const CollectionService = { } `, accept: MIME_TYPES.JSON, - webId, + webId }); // No persisted collection found @@ -195,10 +195,10 @@ const CollectionService = { ${sort ? `ORDER BY ${sort.order}( ?order )` : ''} `, accept: MIME_TYPES.JSON, - webId, + webId }); - const allItems = result.filter((node) => node.itemUri).map((node) => node.itemUri.value); + const allItems = result.filter(node => node.itemUri).map(node => node.itemUri.value); const numPages = !itemsPerPage ? 1 : allItems.length > 0 ? Math.ceil(allItems.length / itemsPerPage) : 0; let returnData = null; @@ -217,7 +217,7 @@ const CollectionService = { summary: collection.summary, first: numPages > 0 ? `${collectionUri}?page=1` : undefined, last: numPages > 0 ? `${collectionUri}?page=${numPages}` : undefined, - totalItems: allItems ? allItems.length : 0, + totalItems: allItems ? allItems.length : 0 }; } else { let selectedItemsUris = allItems; @@ -237,8 +237,8 @@ const CollectionService = { await ctx.call('activitypub.object.get', { objectUri: itemUri, actorUri: webId, - jsonContext: this.settings.jsonContext, - }), + jsonContext: this.settings.jsonContext + }) ); } catch (e) { if (e.code === 404 || e.code === 403) { @@ -265,7 +265,7 @@ const CollectionService = { prev: page > 1 ? `${collectionUri}?page=${parseInt(page) - 1}` : undefined, next: page < numPages ? `${collectionUri}?page=${parseInt(page) + 1}` : undefined, [itemsProp]: selectedItems, - totalItems: allItems ? allItems.length : 0, + totalItems: allItems ? allItems.length : 0 }; } else { // No pagination, return the collection @@ -275,7 +275,7 @@ const CollectionService = { type: this.isOrderedCollection(collection) ? 'OrderedCollection' : 'Collection', summary: collection.summary, [itemsProp]: selectedItems, - totalItems: allItems ? allItems.length : 0, + totalItems: allItems ? allItems.length : 0 }; } } @@ -301,7 +301,7 @@ const CollectionService = { ?s1 ?p1 ?o1 . } `, - webId: 'system', + webId: 'system' }); }, /* @@ -322,7 +322,7 @@ const CollectionService = { ?s1 ?p1 ?o1 . } `, - webId: 'system', + webId: 'system' }); }, async getOwner(ctx) { @@ -341,11 +341,11 @@ const CollectionService = { } `, accept: MIME_TYPES.JSON, - webId: 'system', + webId: 'system' }); return results.length > 0 ? results[0].actorUri.value : null; - }, + } }, hooks: { before: { @@ -358,8 +358,8 @@ const CollectionService = { ctx.meta.dataset = parts[1]; } } - }, - }, + } + } }, methods: { isOrderedCollection(collection) { @@ -367,8 +367,8 @@ const CollectionService = { collection['@type'] === 'as:OrderedCollection' || (Array.isArray(collection['@type']) && collection['@type'].includes('as:OrderedCollection')) ); - }, - }, + } + } }; module.exports = CollectionService; diff --git a/src/middleware/packages/activitypub/services/activitypub/subservices/inbox.js b/src/middleware/packages/activitypub/services/activitypub/subservices/inbox.js index 1669812ae..85031a5b0 100644 --- a/src/middleware/packages/activitypub/services/activitypub/subservices/inbox.js +++ b/src/middleware/packages/activitypub/services/activitypub/subservices/inbox.js @@ -16,7 +16,7 @@ const InboxService = { dereferenceItems: true, sort: { predicate: 'as:published', order: 'DESC' }, permissions: collectionPermissionsWithAnonRead, - podProvider: false, + podProvider: false }, dependencies: ['activitypub.collection', 'triplestore'], actions: { @@ -45,13 +45,13 @@ const InboxService = { if (!ctx.meta.skipSignatureValidation) { const validDigest = await ctx.call('signature.verifyDigest', { body: ctx.meta.rawBody, // Stored by parseJson middleware - headers: ctx.meta.headers, + headers: ctx.meta.headers }); const { isValid: validSignature } = await ctx.call('signature.verifyHttpSignature', { url: collectionUri, method: 'POST', - headers: ctx.meta.headers, + headers: ctx.meta.headers }); if (!validDigest || !validSignature) { @@ -67,19 +67,19 @@ const InboxService = { resource: objectIdToCurrent(activity), mirrorGraph: false, // Store in default graph as activity may not be public keepInSync: false, // Activities are immutable - webId: actorUri, + webId: actorUri }); // Attach the activity to the activities container, in order to use the container options await ctx.call('activitypub.activity.attach', { resourceUri: activity.id, - webId: this.settings.podProvider ? actorUri : 'system', + webId: this.settings.podProvider ? actorUri : 'system' }); // Attach the activity to the inbox await ctx.call('activitypub.collection.attach', { collectionUri, - item: activity, + item: activity }); ctx.emit( @@ -87,9 +87,9 @@ const InboxService = { { activity, recipients: [actorUri], - local: false, + local: false }, - { meta: { webId: null, dataset: null } }, + { meta: { webId: null, dataset: null } } ); ctx.meta.$statusCode = 202; @@ -115,19 +115,19 @@ const InboxService = { ORDER BY ?published `, accept: MIME_TYPES.JSON, - webId: 'system', + webId: 'system' }); const activities = []; - for (const activityUri of results.filter((node) => node.activityUri).map((node) => node.activityUri.value)) { + for (const activityUri of results.filter(node => node.activityUri).map(node => node.activityUri.value)) { const activity = await ctx.call('activitypub.activity.get', { resourceUri: activityUri, webId: 'system' }); activities.push(activity); } return activities; - }, - }, + } + } }; module.exports = InboxService; diff --git a/src/middleware/packages/activitypub/services/activitypub/subservices/object.js b/src/middleware/packages/activitypub/services/activitypub/subservices/object.js index 5e05c59d7..821fec446 100644 --- a/src/middleware/packages/activitypub/services/activitypub/subservices/object.js +++ b/src/middleware/packages/activitypub/services/activitypub/subservices/object.js @@ -6,7 +6,7 @@ const ObjectService = { name: 'activitypub.object', settings: { baseUri: null, - podProvider: false, + podProvider: false }, dependencies: ['ldp.resource'], actions: { @@ -20,7 +20,7 @@ const ObjectService = { resourceUri: objectUri, webId: actorUri, ...rest, - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); }, async awaitCreateComplete(ctx) { @@ -33,11 +33,11 @@ const ObjectService = { { resourceUri: objectUri, accept: MIME_TYPES.JSON, - webId: 'system', + webId: 'system' }, - { meta: { $cache: false } }, + { meta: { $cache: false } } ); - } while (!predicates.every((p) => Object.keys(object).includes(p))); + } while (!predicates.every(p => Object.keys(object).includes(p))); return object; }, async process(ctx) { @@ -54,7 +54,7 @@ const ObjectService = { type: activityType, to, actor: object.attributedTo, - object, + object }; } @@ -64,14 +64,13 @@ const ObjectService = { if (typeof activity.object === 'string') break; const container = await ctx.call('ldp.registry.getByType', { - type: activity.object.type || activity.object['@type'], + type: activity.object.type || activity.object['@type'] }); if (!container) throw new Error( - `Cannot create resource of type "${ - activity.object.type || activity.object['@type'] - }", no matching containers were found!`, + `Cannot create resource of type "${activity.object.type || + activity.object['@type']}", no matching containers were found!` ); const containerUri = await ctx.call('ldp.registry.getUri', { path: container.path, webId: actorUri }); @@ -81,7 +80,7 @@ const ObjectService = { slug: ctx.meta.headers && ctx.meta.headers.slug, resource: activity.object, contentType: MIME_TYPES.JSON, - webId: actorUri, + webId: actorUri }); break; } @@ -93,7 +92,7 @@ const ObjectService = { await ctx.call('ldp.resource.put', { resource: activity.object, contentType: MIME_TYPES.JSON, - webId: actorUri, + webId: actorUri }); objectUri = activity.object['@id'] || activity.object.id; break; @@ -103,7 +102,7 @@ const ObjectService = { // TODO ensure that this is not an announcement (like for Update and Create) await ctx.call('ldp.resource.delete', { resourceUri: typeof activity.object === 'string' ? activity.object : activity.object.id, - webId: actorUri, + webId: actorUri }); break; } @@ -115,14 +114,14 @@ const ObjectService = { { resourceUri: objectUri, accept: MIME_TYPES.JSON, - webId: actorUri, + webId: actorUri }, - { meta: { $cache: false } }, + { meta: { $cache: false } } ); } return activity; - }, + } // TODO handle Tombstones, also when we post directly through the LDP protocol ? // async create(ctx) { // // If there is already a tombstone in the desired URI, @@ -164,8 +163,8 @@ const ObjectService = { methods: { isLocal(uri) { return uri.startsWith(this.settings.baseUri); - }, - }, + } + } }; module.exports = ObjectService; diff --git a/src/middleware/packages/activitypub/services/activitypub/subservices/outbox.js b/src/middleware/packages/activitypub/services/activitypub/subservices/outbox.js index a772508b7..f1649bc14 100644 --- a/src/middleware/packages/activitypub/services/activitypub/subservices/outbox.js +++ b/src/middleware/packages/activitypub/services/activitypub/subservices/outbox.js @@ -19,7 +19,7 @@ const OutboxService = { itemsPerPage: 10, dereferenceItems: true, sort: { predicate: 'as:published', order: 'DESC' }, - permissions: collectionPermissionsWithAnonRead, + permissions: collectionPermissionsWithAnonRead }, dependencies: ['activitypub.object', 'activitypub.collection'], actions: { @@ -37,7 +37,7 @@ const OutboxService = { throw new MoleculerError( `Forbidden to post to the outbox ${collectionUri} (webId ${ctx.meta.webId})`, 403, - 'FORBIDDEN', + 'FORBIDDEN' ); } @@ -62,14 +62,14 @@ const OutboxService = { activity.published = new Date().toISOString(); const activitiesContainerUri = await ctx.call('activitypub.activity.getContainerUri', { - webId: actorUri, + webId: actorUri }); const activityUri = await ctx.call('activitypub.activity.post', { containerUri: activitiesContainerUri, resource: activity, contentType: MIME_TYPES.JSON, - webId: 'system', // Post as system since there is no write permission to the activities container + webId: 'system' // Post as system since there is no write permission to the activities container }); activity = await ctx.call('activitypub.activity.get', { resourceUri: activityUri, webId: 'system' }); @@ -77,7 +77,7 @@ const OutboxService = { // Attach the newly-created activity to the outbox await ctx.call('activitypub.collection.attach', { collectionUri, - item: activity, + item: activity }); const localRecipients = []; @@ -116,14 +116,14 @@ const OutboxService = { // (They can enter into conflict with an usage of ctx.meta.$location) ctx.meta.$responseHeaders = { Location: activityUri, - 'Content-Length': 0, + 'Content-Length': 0 }; ctx.meta.$statusCode = 201; // TODO do not return activity when calling through API calls return activity; - }, + } }, methods: { isLocalActor(uri) { @@ -142,9 +142,9 @@ const OutboxService = { { actorUri: recipientUri, predicate: 'inbox', - webId: 'system', + webId: 'system' }, - { meta: { dataset } }, + { meta: { dataset } } ); // Attach activity to the inbox of the recipient @@ -152,9 +152,9 @@ const OutboxService = { 'activitypub.collection.attach', { collectionUri: recipientInbox, - item: activity, + item: activity }, - { meta: { dataset } }, + { meta: { dataset } } ); if (this.settings.podProvider) { @@ -164,16 +164,16 @@ const OutboxService = { mirrorGraph: false, // Store in default graph as activity may not be public keepInSync: false, // Activities are immutable webId: recipientUri, - dataset, + dataset }); await this.broker.call( 'activitypub.activity.attach', { resourceUri: activity.id, - webId: recipientUri, + webId: recipientUri }, - { meta: { dataset } }, + { meta: { dataset } } ); } @@ -196,7 +196,7 @@ const OutboxService = { const recipientInbox = await this.broker.call('activitypub.actor.getCollectionUri', { actorUri: recipientUri, predicate: 'inbox', - webId: 'system', + webId: 'system' }); if (!recipientInbox) { @@ -210,7 +210,7 @@ const OutboxService = { url: recipientInbox, method: 'POST', body, - actorUri: activity.actor, + actorUri: activity.actor }); // Post activity to the inbox of the remote actor @@ -218,9 +218,9 @@ const OutboxService = { method: 'POST', headers: { 'Content-Type': 'application/json', - ...signatureHeaders, + ...signatureHeaders }, - body, + body }); if (response.ok) { @@ -233,7 +233,7 @@ const OutboxService = { this.logger.warn(`Error when posting activity to remote actor ${recipientUri}: ${e.message}`); return false; } - }, + } }, queues: { remotePost: { @@ -249,7 +249,7 @@ const OutboxService = { } return { response }; - }, + } }, localPost: { name: '*', @@ -264,9 +264,9 @@ const OutboxService = { } return { success, failures }; - }, - }, - }, + } + } + } }; module.exports = OutboxService; diff --git a/src/middleware/packages/activitypub/services/activitypub/subservices/registry.js b/src/middleware/packages/activitypub/services/activitypub/subservices/registry.js index a7a302b82..7b1d1722e 100644 --- a/src/middleware/packages/activitypub/services/activitypub/subservices/registry.js +++ b/src/middleware/packages/activitypub/services/activitypub/subservices/registry.js @@ -17,8 +17,8 @@ const RegistryService = { ordered: false, itemsPerPage: null, dereferenceItems: false, - sort: { predicate: 'as:published', order: 'DESC' }, - }, + sort: { predicate: 'as:published', order: 'DESC' } + } }, dependencies: ['triplestore', 'ldp'], async started() { @@ -32,9 +32,7 @@ const RegistryService = { if (!name) name = path; // Ignore undefined options - Object.keys(options).forEach( - (key) => (options[key] === undefined || options[key] === null) && delete options[key], - ); + Object.keys(options).forEach(key => (options[key] === undefined || options[key] === null) && delete options[key]); // Save the collection locally this.registeredCollections.push({ path, name, attachToTypes, ...options }); @@ -58,7 +56,7 @@ const RegistryService = { // TODO ensure it's not a problem if the same route is added twice await this.broker.call('api.addRoute', { - route: getCollectionRoute(collectionUri, collection.controlledActions), + route: getCollectionRoute(collectionUri, collection.controlledActions) }); }, list() { @@ -79,7 +77,7 @@ const RegistryService = { return { ...this.settings.defaultCollectionOptions, - ...this.registeredCollections.find((collection) => collection.path === path), + ...this.registeredCollections.find(collection => collection.path === path) }; }, async createAndAttachCollection(ctx) { @@ -98,11 +96,11 @@ const RegistryService = { await ctx.call('ldp.resource.patch', { resourceUri: objectUri, triplesToAdd: [quad(namedNode(objectUri), namedNode(collection.attachPredicate), namedNode(collectionUri))], - webId: 'system', + webId: 'system' }); // Now the collection has been created, we can remove it (this way we don't use too much memory) - this.collectionsInCreation = this.collectionsInCreation.filter((c) => c !== collectionUri); + this.collectionsInCreation = this.collectionsInCreation.filter(c => c !== collectionUri); } }, async deleteCollection(ctx) { @@ -131,15 +129,15 @@ const RegistryService = { { objectUri: resourceUri, collection, - webId: 'system', + webId: 'system' }, - { parentCtx: ctx }, + { parentCtx: ctx } ); } } } } - }, + } // async getUri(ctx) { // const { path, webId } = ctx.params; // @@ -156,36 +154,36 @@ const RegistryService = { getCollectionsByType(types) { types = defaultToArray(types); return types - ? this.registeredCollections.filter((collection) => + ? this.registeredCollections.filter(collection => types - .map((type) => type.replace(AS_PREFIX, '')) // Remove AS prefix if it is set - .some((type) => + .map(type => type.replace(AS_PREFIX, '')) // Remove AS prefix if it is set + .some(type => Array.isArray(collection.attachToTypes) ? collection.attachToTypes.includes(type) - : collection.attachToTypes === type, - ), + : collection.attachToTypes === type + ) ) : []; }, // Get the containers with resources of the given type // Same action as ldp.registry.getByType, but search through locally registered containers to avoid race conditions getContainersByType(types) { - return Object.values(this.registeredContainers).filter((container) => - defaultToArray(types).some((type) => + return Object.values(this.registeredContainers).filter(container => + defaultToArray(types).some(type => Array.isArray(container.acceptedTypes) ? container.acceptedTypes.includes(type) - : container.acceptedTypes === type, - ), + : container.acceptedTypes === type + ) ); }, isActor(types) { - return defaultToArray(types).some((type) => - [...Object.values(ACTOR_TYPES), ...Object.values(FULL_ACTOR_TYPES)].includes(type), + return defaultToArray(types).some(type => + [...Object.values(ACTOR_TYPES), ...Object.values(FULL_ACTOR_TYPES)].includes(type) ); }, hasTypeChanged(oldData, newData) { return JSON.stringify(newData.type || newData['@type']) !== JSON.stringify(oldData.type || oldData['@type']); - }, + } }, events: { async 'ldp.resource.created'(ctx) { @@ -196,12 +194,12 @@ const RegistryService = { // If the resource is an actor, use the resource URI as the webId await this.actions.createAndAttachCollection( { objectUri: resourceUri, collection, webId: resourceUri }, - { parentCtx: ctx }, + { parentCtx: ctx } ); } else { await this.actions.createAndAttachCollection( { objectUri: resourceUri, collection, webId }, - { parentCtx: ctx }, + { parentCtx: ctx } ); } } @@ -216,12 +214,12 @@ const RegistryService = { // If the resource is an actor, use the resource URI as the webId await this.actions.createAndAttachCollection( { objectUri: resourceUri, collection, webId: resourceUri }, - { parentCtx: ctx }, + { parentCtx: ctx } ); } else { await this.actions.createAndAttachCollection( { objectUri: resourceUri, collection, webId }, - { parentCtx: ctx }, + { parentCtx: ctx } ); } } @@ -237,12 +235,12 @@ const RegistryService = { // If the resource is an actor, use the resource URI as the webId await this.actions.createAndAttachCollection( { objectUri: resourceUri, collection, webId: resourceUri }, - { parentCtx: ctx }, + { parentCtx: ctx } ); } else { await this.actions.createAndAttachCollection( { objectUri: resourceUri, collection, webId }, - { parentCtx: ctx }, + { parentCtx: ctx } ); } } @@ -255,7 +253,7 @@ const RegistryService = { for (const collection of collections) { await this.actions.deleteCollection( { objectUri: oldData.id || oldData['@id'], collection }, - { parentCtx: ctx }, + { parentCtx: ctx } ); } }, @@ -273,8 +271,8 @@ const RegistryService = { for (const collection of collections) { await this.actions.addApiRoute({ collection, container }, { parentCtx: ctx }); } - }, - }, + } + } }; module.exports = RegistryService; diff --git a/src/middleware/packages/activitypub/utils.js b/src/middleware/packages/activitypub/utils.js index 4e6b8790e..1d4c1508a 100644 --- a/src/middleware/packages/activitypub/utils.js +++ b/src/middleware/packages/activitypub/utils.js @@ -1,20 +1,20 @@ const { ACTIVITY_TYPES } = require('./constants'); -const objectCurrentToId = (activityJson) => { +const objectCurrentToId = activityJson => { if (activityJson.object && typeof activityJson.object === 'object' && activityJson.object.current) { const { current, ...object } = activityJson.object; return { ...activityJson, object: { id: current, - ...objectCurrentToId(object), - }, + ...objectCurrentToId(object) + } }; } return activityJson; }; -const objectIdToCurrent = (activityJson) => { +const objectIdToCurrent = activityJson => { // If the activity has an object predicate, and this object is not an activity if ( activityJson.object && @@ -26,18 +26,18 @@ const objectIdToCurrent = (activityJson) => { ...activityJson, object: { current: id || arobaseId, - ...objectIdToCurrent(object), - }, + ...objectIdToCurrent(object) + } }; } return activityJson; }; -const collectionPermissionsWithAnonRead = (webId) => { +const collectionPermissionsWithAnonRead = webId => { const permissions = { anon: { - read: true, - }, + read: true + } }; if (webId !== 'anon' && webId !== 'system') { @@ -45,7 +45,7 @@ const collectionPermissionsWithAnonRead = (webId) => { uri: webId, read: true, write: true, - control: true, + control: true }; } @@ -53,15 +53,15 @@ const collectionPermissionsWithAnonRead = (webId) => { }; // Items or recipients may be string or array, so default to array for easier handling -const defaultToArray = (value) => { +const defaultToArray = value => { return !value ? undefined : Array.isArray(value) ? value : [value]; }; -const getSlugFromUri = (str) => str.match(new RegExp(`.*/(.*)`))[1]; +const getSlugFromUri = str => str.match(new RegExp(`.*/(.*)`))[1]; -const getContainerFromUri = (str) => str.match(new RegExp(`(.*)/.*`))[1]; +const getContainerFromUri = str => str.match(new RegExp(`(.*)/.*`))[1]; -const delay = (t) => new Promise((resolve) => setTimeout(resolve, t)); +const delay = t => new Promise(resolve => setTimeout(resolve, t)); module.exports = { objectCurrentToId, @@ -70,5 +70,5 @@ module.exports = { defaultToArray, getSlugFromUri, getContainerFromUri, - delay, + delay }; diff --git a/src/middleware/packages/activitypub/utils/matchActivity.js b/src/middleware/packages/activitypub/utils/matchActivity.js index 2e9350532..0f288ee52 100644 --- a/src/middleware/packages/activitypub/utils/matchActivity.js +++ b/src/middleware/packages/activitypub/utils/matchActivity.js @@ -12,11 +12,11 @@ const matchActivity = async (ctx, pattern, activityOrObject) => { if (typeof activityOrObject === 'string') { if (pattern.type && Object.values(ACTIVITY_TYPES).includes(pattern.type)) { dereferencedActivityOrObject = await ctx.call('activitypub.activity.get', { - resourceUri: activityOrObject, + resourceUri: activityOrObject }); } else { dereferencedActivityOrObject = await ctx.call('activitypub.object.get', { - objectUri: activityOrObject, + objectUri: activityOrObject }); } } else { @@ -30,7 +30,7 @@ const matchActivity = async (ctx, pattern, activityOrObject) => { if (!dereferencedActivityOrObject[key]) return false; } else if ( !dereferencedActivityOrObject[key] || - !defaultToArray(dereferencedActivityOrObject[key]).some((v) => defaultToArray(pattern[key]).includes(v)) + !defaultToArray(dereferencedActivityOrObject[key]).some(v => defaultToArray(pattern[key]).includes(v)) ) return false; } diff --git a/src/middleware/packages/auth/mixins/auth.js b/src/middleware/packages/auth/mixins/auth.js index 68d4305ec..0ebbd9b85 100644 --- a/src/middleware/packages/auth/mixins/auth.js +++ b/src/middleware/packages/auth/mixins/auth.js @@ -12,19 +12,19 @@ const AuthMixin = { reservedUsernames: [], webIdSelection: [], accountSelection: [], - accountsDataset: 'settings', + accountsDataset: 'settings' }, dependencies: ['api', 'webid'], async created() { const { jwtPath, reservedUsernames, accountsDataset } = this.settings; await this.broker.createService(AuthJWTService, { - settings: { jwtPath }, + settings: { jwtPath } }); await this.broker.createService(AuthAccountService, { settings: { reservedUsernames }, - adapter: new TripleStoreAdapter({ type: 'AuthAccount', dataset: accountsDataset }), + adapter: new TripleStoreAdapter({ type: 'AuthAccount', dataset: accountsDataset }) }); }, async started() { @@ -90,10 +90,10 @@ const AuthMixin = { const { webId } = ctx.params; return await ctx.call('auth.jwt.generateToken', { payload: { - webId, - }, + webId + } }); - }, + } }, methods: { getStrategy() { @@ -104,21 +104,19 @@ const AuthMixin = { }, pickWebIdData(data) { if (this.settings.webIdSelection.length > 0) { - return Object.fromEntries( - this.settings.webIdSelection.filter((key) => key in data).map((key) => [key, data[key]]), - ); + return Object.fromEntries(this.settings.webIdSelection.filter(key => key in data).map(key => [key, data[key]])); } return data; }, pickAccountData(data) { if (this.settings.accountSelection.length > 0) { return Object.fromEntries( - this.settings.accountSelection.filter((key) => key in data).map((key) => [key, data[key]]), + this.settings.accountSelection.filter(key => key in data).map(key => [key, data[key]]) ); } return data || {}; - }, - }, + } + } }; module.exports = AuthMixin; diff --git a/src/middleware/packages/auth/mixins/auth.sso.js b/src/middleware/packages/auth/mixins/auth.sso.js index fec97b41b..db6eb7410 100644 --- a/src/middleware/packages/auth/mixins/auth.sso.js +++ b/src/middleware/packages/auth/mixins/auth.sso.js @@ -14,7 +14,7 @@ const AuthSSOMixin = { webIdSelection: [], // SSO-specific settings sessionSecret: 's€m@pps', - selectSsoData: null, + selectSsoData: null }, actions: { async loginOrSignup(ctx) { @@ -45,7 +45,7 @@ const AuthSSOMixin = { accountData = await ctx.call('auth.account.create', { uuid: profileData.uuid, email: profileData.email, - username: profileData.username, + username: profileData.username }); webId = await ctx.call('webid.create', this.pickWebIdData({ nick: accountData.username, ...profileData })); newUser = true; @@ -56,14 +56,14 @@ const AuthSSOMixin = { ctx.emit( 'auth.registered', { webId, profileData, accountData, ssoData }, - { meta: { webId: null, dataset: null } }, + { meta: { webId: null, dataset: null } } ); } const token = await ctx.call('auth.jwt.generateToken', { payload: { webId } }); return { token, newUser }; - }, + } }, methods: { getApiRoutes() { @@ -74,24 +74,20 @@ const AuthSSOMixin = { name: 'auth', use: [sessionMiddleware, this.passport.initialize(), this.passport.session()], aliases: { - 'GET /': [ - saveRedirectUrl, - this.passport.authenticate(this.passportId, { session: false }), - redirectToFront, - ], - }, + 'GET /': [saveRedirectUrl, this.passport.authenticate(this.passportId, { session: false }), redirectToFront] + } }, { path: '/auth/logout', name: 'auth-logout', use: [sessionMiddleware, this.passport.initialize(), this.passport.session()], aliases: { - 'GET /': [saveRedirectUrl, localLogout, redirectToFront], - }, - }, + 'GET /': [saveRedirectUrl, localLogout, redirectToFront] + } + } ]; - }, - }, + } + } }; module.exports = AuthSSOMixin; diff --git a/src/middleware/packages/auth/services/account.js b/src/middleware/packages/auth/services/account.js index f3eaad2ab..6b26c5865 100644 --- a/src/middleware/packages/auth/services/account.js +++ b/src/middleware/packages/auth/services/account.js @@ -10,7 +10,7 @@ module.exports = { adapter: new TripleStoreAdapter({ type: 'AuthAccount', dataset: 'settings' }), settings: { idField: '@id', - reservedUsernames: ['relay'], + reservedUsernames: ['relay'] }, dependencies: ['triplestore'], actions: { @@ -49,7 +49,7 @@ module.exports = { username, email, hashedPassword, - webId, + webId }); }, async attachWebId(ctx) { @@ -57,7 +57,7 @@ module.exports = { return await this._update(ctx, { '@id': accountUri, - webId, + webId }); }, async verify(ctx) { @@ -105,7 +105,7 @@ module.exports = { return await this._update(ctx, { '@id': account['@id'], - hashedPassword, + hashedPassword }); }, async setNewPassword(ctx) { @@ -120,7 +120,7 @@ module.exports = { return await this._update(ctx, { '@id': account['@id'], hashedPassword, - resetPasswordToken: undefined, + resetPasswordToken: undefined }); }, async generateResetPasswordToken(ctx) { @@ -130,7 +130,7 @@ module.exports = { await this._update(ctx, { '@id': account['@id'], - resetPasswordToken, + resetPasswordToken }); return resetPasswordToken; @@ -147,7 +147,7 @@ module.exports = { return { email: account.email, - preferredLocale: account.preferredLocale, + preferredLocale: account.preferredLocale }; }, async updateAccountSettings(ctx) { @@ -177,9 +177,9 @@ module.exports = { return await this._update(ctx, { '@id': account['@id'], - ...params, + ...params }); - }, + } }, methods: { async isValidUsername(ctx, username) { @@ -213,7 +213,7 @@ module.exports = { }); }, async comparePassword(password, hash) { - return new Promise((resolve) => { + return new Promise(resolve => { bcrypt.compare(password, hash, (err, res) => { if (res === true) { resolve(true); @@ -232,6 +232,6 @@ module.exports = { resolve(buf.toString('hex')); }); }); - }, - }, + } + } }; diff --git a/src/middleware/packages/auth/services/auth.cas.js b/src/middleware/packages/auth/services/auth.cas.js index 8654b9b21..9545b5acc 100644 --- a/src/middleware/packages/auth/services/auth.cas.js +++ b/src/middleware/packages/auth/services/auth.cas.js @@ -15,7 +15,7 @@ const AuthCASService = { sessionSecret: 's€m@pps', selectSsoData: null, // Cas-specific settings - casUrl: null, + casUrl: null }, async created() { this.passportId = 'cas'; @@ -25,21 +25,21 @@ const AuthCASService = { return new Strategy( { casURL: this.settings.casUrl, - passReqToCallback: true, + passReqToCallback: true }, (req, username, profile, done) => { req.$ctx .call('auth.loginOrSignup', { ssoData: { username, ...profile } }) - .then((loginData) => { + .then(loginData => { done(null, loginData); }) - .catch((e) => { + .catch(e => { done(new E.UnAuthorizedError(e.message), false); }); - }, + } ); - }, - }, + } + } }; module.exports = AuthCASService; diff --git a/src/middleware/packages/auth/services/auth.local.js b/src/middleware/packages/auth/services/auth.local.js index f42a69ff1..a6a5e0824 100644 --- a/src/middleware/packages/auth/services/auth.local.js +++ b/src/middleware/packages/auth/services/auth.local.js @@ -19,13 +19,13 @@ const AuthLocalService = { from: null, transport: { host: null, - port: null, + port: null }, defaults: { locale: null, - frontUrl: null, - }, - }, + frontUrl: null + } + } }, async created() { const { mail } = this.settings; @@ -34,8 +34,8 @@ const AuthLocalService = { await this.broker.createService(AuthMailService, { settings: { - ...mail, - }, + ...mail + } }); }, actions: { @@ -46,7 +46,7 @@ const AuthLocalService = { username, email, password, - ...this.pickAccountData(rest), + ...this.pickAccountData(rest) }); const profileData = { nick: username, email, ...rest }; @@ -103,7 +103,7 @@ const AuthLocalService = { await ctx.call('auth.mail.sendResetPasswordEmail', { account, - token, + token }); }, async setNewPassword(ctx) { @@ -116,7 +116,7 @@ const AuthLocalService = { } await ctx.call('auth.account.setNewPassword', { webId: account.webId, token, password }); - }, + } }, methods: { getStrategy() { @@ -124,19 +124,19 @@ const AuthLocalService = { { usernameField: 'username', passwordField: 'password', - passReqToCallback: true, // We want to have access to req below + passReqToCallback: true // We want to have access to req below }, (req, username, password, done) => { req.$ctx .call('auth.login', { username, password }) - .then((returnedData) => { + .then(returnedData => { done(null, returnedData); }) - .catch((e) => { + .catch(e => { console.error(e); done(new MoleculerError(e.message, 401), false); }); - }, + } ); }, getApiRoutes() { @@ -145,47 +145,47 @@ const AuthLocalService = { name: 'auth-login', use: [this.passport.initialize()], aliases: { - 'POST /': [this.passport.authenticate(this.passportId, { session: false }), sendToken], - }, + 'POST /': [this.passport.authenticate(this.passportId, { session: false }), sendToken] + } }; const logoutRoute = { path: '/auth/logout', name: 'auth-logout', aliases: { - 'GET /': 'auth.logout', - }, + 'GET /': 'auth.logout' + } }; const signupRoute = { path: '/auth/signup', name: 'auth-signup', aliases: { - 'POST /': 'auth.signup', - }, + 'POST /': 'auth.signup' + } }; const formRoute = { path: '/auth', name: 'auth', aliases: { - 'GET /': 'auth.redirectToForm', - }, + 'GET /': 'auth.redirectToForm' + } }; const resetPasswordRoute = { path: '/auth/reset_password', name: 'auth-reset-password', aliases: { - 'POST /': 'auth.resetPassword', - }, + 'POST /': 'auth.resetPassword' + } }; const setNewPasswordRoute = { path: '/auth/new_password', name: 'auth-new-password', aliases: { - 'POST /': 'auth.setNewPassword', - }, + 'POST /': 'auth.setNewPassword' + } }; const accountSettingsRoute = { @@ -193,9 +193,9 @@ const AuthLocalService = { name: 'auth-account', aliases: { 'GET /': 'auth.account.findSettingsByWebId', - 'POST /': 'auth.account.updateAccountSettings', + 'POST /': 'auth.account.updateAccountSettings' }, - authorization: true, + authorization: true }; const routes = [ @@ -204,7 +204,7 @@ const AuthLocalService = { formRoute, resetPasswordRoute, setNewPasswordRoute, - accountSettingsRoute, + accountSettingsRoute ]; if (this.settings.registrationAllowed) { @@ -212,8 +212,8 @@ const AuthLocalService = { } return routes; - }, - }, + } + } }; module.exports = AuthLocalService; diff --git a/src/middleware/packages/auth/services/auth.oidc.js b/src/middleware/packages/auth/services/auth.oidc.js index bee480ad4..afa76d62a 100644 --- a/src/middleware/packages/auth/services/auth.oidc.js +++ b/src/middleware/packages/auth/services/auth.oidc.js @@ -2,7 +2,7 @@ const urlJoin = require('url-join'); const { Issuer, Strategy, custom } = require('openid-client'); custom.setHttpOptionsDefaults({ - timeout: 10000, + timeout: 10000 }); const AuthSSOMixin = require('../mixins/auth.sso'); @@ -21,7 +21,7 @@ const AuthOIDCService = { // OIDC-specific settings issuer: null, clientId: null, - clientSecret: null, + clientSecret: null }, async created() { this.passportId = 'oidc'; @@ -34,7 +34,7 @@ const AuthOIDCService = { client_id: this.settings.clientId, client_secret: this.settings.clientSecret, redirect_uri: urlJoin(this.settings.baseUrl, 'auth'), - token_endpoint_auth_method: this.settings.clientSecret ? undefined : 'none', + token_endpoint_auth_method: this.settings.clientSecret ? undefined : 'none' }); const params = { @@ -49,22 +49,22 @@ const AuthOIDCService = { { client, params, - passReqToCallback: true, + passReqToCallback: true }, (req, tokenset, userinfo, done) => { req.$ctx .call('auth.loginOrSignup', { ssoData: userinfo }) - .then((loginData) => { + .then(loginData => { done(null, loginData); }) - .catch((e) => { + .catch(e => { console.error(e); done(null, false); }); - }, + } ); - }, - }, + } + } }; module.exports = AuthOIDCService; diff --git a/src/middleware/packages/auth/services/mail.js b/src/middleware/packages/auth/services/mail.js index d6419bd2e..3a94b2e29 100644 --- a/src/middleware/packages/auth/services/mail.js +++ b/src/middleware/packages/auth/services/mail.js @@ -8,11 +8,11 @@ module.exports = { settings: { defaults: { locale: 'en', - frontUrl: null, + frontUrl: null }, templateFolder: path.join(__dirname, '../templates'), from: null, - transport: null, + transport: null }, actions: { async sendResetPasswordEmail(ctx) { @@ -25,14 +25,14 @@ module.exports = { locale: this.getTemplateLocale(account.preferredLocale || this.settings.defaults.locale), data: { account, - resetUrl: `${urlJoin(this.settings.defaults.frontUrl, 'login')}?new_password=true&token=${token}`, - }, + resetUrl: `${urlJoin(this.settings.defaults.frontUrl, 'login')}?new_password=true&token=${token}` + } }, { - parentCtx: ctx, - }, + parentCtx: ctx + } ); - }, + } }, methods: { getTemplateLocale(userLocale) { @@ -44,6 +44,6 @@ module.exports = { default: return 'en-EN'; } - }, - }, + } + } }; diff --git a/src/middleware/packages/auth/services/migration.js b/src/middleware/packages/auth/services/migration.js index 22a996994..f37dfff67 100644 --- a/src/middleware/packages/auth/services/migration.js +++ b/src/middleware/packages/auth/services/migration.js @@ -15,7 +15,7 @@ module.exports = { await ctx.call('auth.account.create', { email: user[emailPredicate], username: usernamePredicate ? user[usernamePredicate] : getSlugFromUri(user.id), - webId: user.id, + webId: user.id }); } catch (e) { console.log(`Unable to create account for user ${user.id}. Error message: ${e.message}`); @@ -24,6 +24,6 @@ module.exports = { console.log(`No email found for user ${user.id}`); } } - }, - }, + } + } }; diff --git a/src/middleware/packages/backup/utils/ftpCopy.js b/src/middleware/packages/backup/utils/ftpCopy.js index 01d1c4973..c9b7b31e6 100644 --- a/src/middleware/packages/backup/utils/ftpCopy.js +++ b/src/middleware/packages/backup/utils/ftpCopy.js @@ -10,7 +10,7 @@ const ftpCopy = (path, subDir, remoteServer) => { host: remoteServer.host, port: remoteServer.port, username: remoteServer.user, - password: remoteServer.password, + password: remoteServer.password }) .then(() => { fs.readdir(path, async (err, files) => { @@ -18,7 +18,7 @@ const ftpCopy = (path, subDir, remoteServer) => { reject(`Unable to scan directory: ${err.message}`); } else { const now = Date.now(); - const newFiles = files.filter((f) => now - fs.statSync(`${path}/${f}`).mtime < 60000); + const newFiles = files.filter(f => now - fs.statSync(`${path}/${f}`).mtime < 60000); for (const filename of newFiles) { await sftp.put(pathJoin(path, filename), pathJoin(remoteServer.path, filename)); } @@ -26,7 +26,7 @@ const ftpCopy = (path, subDir, remoteServer) => { } }); }) - .catch((e) => reject(e)); + .catch(e => reject(e)); }); }; diff --git a/src/middleware/packages/backup/utils/rsyncCopy.js b/src/middleware/packages/backup/utils/rsyncCopy.js index 5248d65b1..d9ce46dc8 100644 --- a/src/middleware/packages/backup/utils/rsyncCopy.js +++ b/src/middleware/packages/backup/utils/rsyncCopy.js @@ -11,7 +11,7 @@ const rsyncCopy = (path, subDir, remoteServer) => { return new Promise((resolve, reject) => { console.log(`Rsync started with command: ${rsync.command()}`); - rsync.execute((error) => { + rsync.execute(error => { if (error) { reject(error); } else { diff --git a/src/middleware/packages/core/service.js b/src/middleware/packages/core/service.js index 2519910f9..05c4327b8 100644 --- a/src/middleware/packages/core/service.js +++ b/src/middleware/packages/core/service.js @@ -17,7 +17,7 @@ const botsContainer = { path: '/bots', acceptedTypes: ['Application'], dereference: ['sec:publicKey'], - readOnly: true, + readOnly: true }; /** @@ -36,7 +36,7 @@ const CoreService = { url: undefined, user: undefined, password: undefined, - mainDataset: undefined, + mainDataset: undefined }, // Optional containers: undefined, @@ -51,7 +51,7 @@ const CoreService = { sparqlEndpoint: {}, void: {}, webacl: {}, - webfinger: {}, + webfinger: {} }, created() { const { baseUrl, baseDir, triplestore, containers, jsonContext, ontologies } = this.settings; @@ -65,8 +65,8 @@ const CoreService = { settings: { baseUri: baseUrl, jsonContext: jsonContext || defaultJsonContext, - ...this.settings.activitypub, - }, + ...this.settings.activitypub + } }); } @@ -76,10 +76,10 @@ const CoreService = { cors: { origin: '*', methods: ['GET', 'PUT', 'PATCH', 'POST', 'DELETE', 'HEAD', 'OPTIONS'], - exposedHeaders: '*', + exposedHeaders: '*' }, httpServerTimeout: 300000, - ...this.settings.api, + ...this.settings.api }, methods: { authenticate(ctx, route, req, res) { @@ -101,8 +101,8 @@ const CoreService = { } ctx.meta.webId = 'anon'; return Promise.reject(new E.UnAuthorizedError(E.ERR_NO_TOKEN)); - }, - }, + } + } }); } @@ -115,17 +115,17 @@ const CoreService = { : [ { path: 'context.json', - file: path.resolve(__dirname, './config/context.json'), - }, + file: path.resolve(__dirname, './config/context.json') + } ], remoteContextFiles: [ { uri: 'https://www.w3.org/ns/activitystreams', - file: path.resolve(__dirname, './config/context-as.json'), - }, + file: path.resolve(__dirname, './config/context-as.json') + } ], - ...this.settings.jsonld, - }, + ...this.settings.jsonld + } }); } @@ -139,9 +139,9 @@ const CoreService = { ...this.settings.ldp, defaultContainerOptions: { jsonContext: jsonContext || defaultJsonContext, - ...this.settings.ldp.defaultContainerOptions, - }, - }, + ...this.settings.ldp.defaultContainerOptions + } + } }); } @@ -149,8 +149,8 @@ const CoreService = { this.broker.createService(SignatureService, { settings: { actorsKeyPairsDir: path.resolve(baseDir, './actors'), - ...this.settings.signature, - }, + ...this.settings.signature + } }); } @@ -158,8 +158,8 @@ const CoreService = { this.broker.createService(SparqlEndpointService, { settings: { defaultAccept: 'application/ld+json', - ...this.settings.sparqlEndpoint, - }, + ...this.settings.sparqlEndpoint + } }); } @@ -174,16 +174,16 @@ const CoreService = { user: triplestore.user, password: triplestore.password, mainDataset: triplestore.mainDataset, - ...this.settings.triplestore, + ...this.settings.triplestore }, async started() { if (triplestore.mainDataset) { await this.broker.call('triplestore.dataset.create', { dataset: triplestore.mainDataset, - secure, + secure }); } - }, + } }); } @@ -192,8 +192,8 @@ const CoreService = { settings: { baseUrl, ontologies: ontologies || defaultOntologies, - ...this.settings.void, - }, + ...this.settings.void + } }); } @@ -201,8 +201,8 @@ const CoreService = { this.broker.createService(WebAclService, { settings: { baseUrl, - ...this.settings.webacl, - }, + ...this.settings.webacl + } }); } @@ -210,11 +210,11 @@ const CoreService = { this.broker.createService(WebfingerService, { settings: { baseUrl, - ...this.settings.webfinger, - }, + ...this.settings.webfinger + } }); } - }, + } }; module.exports = CoreService; diff --git a/src/middleware/packages/importer/mixins/discourse.js b/src/middleware/packages/importer/mixins/discourse.js index 286b6e730..922cf81d5 100644 --- a/src/middleware/packages/importer/mixins/discourse.js +++ b/src/middleware/packages/importer/mixins/discourse.js @@ -7,21 +7,20 @@ module.exports = { source: { discourse: { baseUrl: null, - type: 'topics', + type: 'topics' }, fieldsMapping: { slug: 'slug', created: 'created_at', - updated: (data) => data.last_posted_at || data.created_at, - }, - }, + updated: data => data.last_posted_at || data.created_at + } + } }, created() { if (this.settings.source.discourse.type === 'topics') { this.settings.source.apiUrl = this.settings.source.discourse.baseUrl; this.settings.source.getAllCompact = urlJoin(this.settings.source.discourse.baseUrl, 'latest.json'); - this.settings.source.getOneFull = (data) => - urlJoin(this.settings.source.discourse.baseUrl, 't', `${data.id}.json`); + this.settings.source.getOneFull = data => urlJoin(this.settings.source.discourse.baseUrl, 't', `${data.id}.json`); } else { throw new Error('The DiscourseImporterMixin can only import topics for now'); } @@ -41,6 +40,6 @@ module.exports = { return topics; } - }, - }, + } + } }; diff --git a/src/middleware/packages/importer/mixins/drupal.js b/src/middleware/packages/importer/mixins/drupal.js index 103801ef3..366a1f350 100644 --- a/src/middleware/packages/importer/mixins/drupal.js +++ b/src/middleware/packages/importer/mixins/drupal.js @@ -10,23 +10,23 @@ module.exports = { getOneFull: null, basicAuth: { user: null, - password: null, + password: null }, fetchOptions: { - compress: false, // Solve bug in Drupal + compress: false // Solve bug in Drupal }, fieldsMapping: { slug: 'uuid', - created: (data) => convertToIsoString(data.published), - updated: (data) => convertToIsoString(data.updated), - }, - }, + created: data => convertToIsoString(data.published), + updated: data => convertToIsoString(data.updated) + } + } }, methods: { async list(url) { const data = await this.fetch(url); if (data && data.nodes) { - return data.nodes.map((n) => n.node); + return data.nodes.map(n => n.node); } return false; }, @@ -36,6 +36,6 @@ module.exports = { return data.nodes[0].node; } return false; - }, - }, + } + } }; diff --git a/src/middleware/packages/importer/mixins/gogocarto.js b/src/middleware/packages/importer/mixins/gogocarto.js index daa203c4d..f543e689d 100644 --- a/src/middleware/packages/importer/mixins/gogocarto.js +++ b/src/middleware/packages/importer/mixins/gogocarto.js @@ -7,14 +7,14 @@ module.exports = { source: { gogocarto: { baseUrl: null, - type: 'elements', + type: 'elements' }, fieldsMapping: { slug: 'name', created: 'createdAt', - updated: 'updatedAt', - }, - }, + updated: 'updatedAt' + } + } }, created() { if (this.settings.source.gogocarto.type === 'elements') { @@ -23,9 +23,9 @@ module.exports = { this.settings.source.getAllCompact = `${urlJoin( this.settings.source.gogocarto.baseUrl, 'api', - 'elements', + 'elements' )}?ontology=gogosync`; - this.settings.source.getOneFull = (data) => + this.settings.source.getOneFull = data => urlJoin(this.settings.source.gogocarto.baseUrl, 'api', 'elements', `${data.id}`); } else { throw new Error('The GoGoCartoMixin can only import elements for now'); @@ -39,6 +39,6 @@ module.exports = { async getOne(url) { const result = await this.fetch(url); return result.data; - }, - }, + } + } }; diff --git a/src/middleware/packages/importer/mixins/humhub.js b/src/middleware/packages/importer/mixins/humhub.js index b11d1b298..c3b6fe032 100644 --- a/src/middleware/packages/importer/mixins/humhub.js +++ b/src/middleware/packages/importer/mixins/humhub.js @@ -4,7 +4,7 @@ const { convertToIsoString } = require('../utils'); const allowedTypes = ['user', 'space', 'calendar', 'post']; -const getSlugByUrl = (url) => { +const getSlugByUrl = url => { if (url) { const splitUrl = url.split('/'); let slug = splitUrl.pop(); @@ -21,11 +21,11 @@ module.exports = { humhub: { baseUrl: null, jwtToken: null, - type: null, // 'user', 'space', 'calendar', 'post' + type: null // 'user', 'space', 'calendar', 'post' }, fieldsMapping: { // We don't use arrow function as we need to have access to this.settings - slug: function (data) { + slug: function(data) { switch (this.settings.source.humhub.type) { case 'user': case 'space': @@ -35,22 +35,22 @@ module.exports = { return data.content.metadata.guid; } }, - created: function (data) { + created: function(data) { switch (this.settings.source.humhub.type) { case 'calendar': case 'post': return convertToIsoString(data.content.metadata.created_at); } }, - updated: function (data) { + updated: function(data) { switch (this.settings.source.humhub.type) { case 'calendar': case 'post': return convertToIsoString(data.content.metadata.updated_at); } - }, - }, - }, + } + } + } }, created() { const { baseUrl, jwtToken, type } = this.settings.source.humhub; @@ -66,9 +66,9 @@ module.exports = { this.settings.source.getAllFull = this.settings.source.apiUrl; if (type === 'calendar') { - this.settings.source.getOneFull = (data) => `${this.settings.source.apiUrl}/entry/${data.id}`; + this.settings.source.getOneFull = data => `${this.settings.source.apiUrl}/entry/${data.id}`; } else { - this.settings.source.getOneFull = (data) => `${this.settings.source.apiUrl}/${data.id}`; + this.settings.source.getOneFull = data => `${this.settings.source.apiUrl}/${data.id}`; } }, methods: { @@ -107,6 +107,6 @@ module.exports = { } return results; - }, - }, + } + } }; diff --git a/src/middleware/packages/importer/mixins/importer.js b/src/middleware/packages/importer/mixins/importer.js index 878acc7af..5c53fa579 100644 --- a/src/middleware/packages/importer/mixins/importer.js +++ b/src/middleware/packages/importer/mixins/importer.js @@ -13,37 +13,37 @@ module.exports = { getOneFull: null, headers: { Accept: 'application/json', - 'User-Agent': 'SemAppsImporter', + 'User-Agent': 'SemAppsImporter' }, basicAuth: { user: '', - password: '', + password: '' }, fetchOptions: {}, fieldsMapping: { slug: null, created: null, - updated: null, - }, + updated: null + } }, dest: { containerUri: null, - predicatesToKeep: [], // Don't remove these predicates when updating data + predicatesToKeep: [] // Don't remove these predicates when updating data }, activitypub: { actorUri: null, - activities: [ACTIVITY_TYPES.CREATE, ACTIVITY_TYPES.UPDATE, ACTIVITY_TYPES.DELETE], + activities: [ACTIVITY_TYPES.CREATE, ACTIVITY_TYPES.UPDATE, ACTIVITY_TYPES.DELETE] }, cronJob: { time: null, - timeZone: 'Europe/Paris', - }, + timeZone: 'Europe/Paris' + } }, dependencies: ['triplestore'], created() { if (this.settings.source.basicAuth.user) { this.settings.source.headers.Authorization = `Basic ${Buffer.from( - `${this.settings.source.basicAuth.user}:${this.settings.source.basicAuth.password}`, + `${this.settings.source.basicAuth.user}:${this.settings.source.basicAuth.password}` ).toString('base64')}`; } @@ -51,8 +51,8 @@ module.exports = { this.schema.queues = { [this.name]: { name: 'synchronize', - process: this.processSynchronize, - }, + process: this.processSynchronize + } }; }, async started() { @@ -67,10 +67,10 @@ module.exports = { } `, accept: MIME_TYPES.JSON, - webId: 'system', + webId: 'system' }); - this.imported = Object.fromEntries(result.map((node) => [node.sourceUri.value, node.id.value])); + this.imported = Object.fromEntries(result.map(node => [node.sourceUri.value, node.id.value])); } else { this.imported = {}; } @@ -85,8 +85,8 @@ module.exports = { // Try again after 3 minutes and until 12 hours later attempts: 8, backoff: { type: 'exponential', delay: '180000' }, - repeat: { cron: this.settings.cronJob.time, tz: this.settings.cronJob.timeZone }, - }, + repeat: { cron: this.settings.cronJob.time, tz: this.settings.cronJob.timeZone } + } ); } }, @@ -111,7 +111,7 @@ module.exports = { typeof this.settings.source.getAllCompact === 'string' ? this.settings.source.getAllCompact : this.settings.source.getAllCompact.url - }...`, + }...` ); for (const data of compactResults) { @@ -125,7 +125,7 @@ module.exports = { typeof this.settings.source.getAllCompact === 'string' ? this.settings.source.getAllCompact : this.settings.source.getAllCompact.url - }...`, + }...` ); } } else if (this.settings.source.getAllFull) { @@ -139,7 +139,7 @@ module.exports = { typeof this.settings.source.getAllFull === 'string' ? this.settings.source.getAllFull : this.settings.source.getAllFull.url - }...`, + }...` ); for (const data of fullResults) { @@ -153,7 +153,7 @@ module.exports = { typeof this.settings.source.getAllFull === 'string' ? this.settings.source.getAllFull : this.settings.source.getAllFull.url - }...`, + }...` ); } } else { @@ -169,8 +169,8 @@ module.exports = { // If QueueMixin is not available, call method with fake job object return this.processSynchronize({ data: {}, - progress: (number) => this.logger.info(`Progress: ${number}%`), - log: (message) => this.logger.info(message), + progress: number => this.logger.info(`Progress: ${number}%`), + log: message => this.logger.info(message) }); } }, @@ -197,7 +197,7 @@ module.exports = { const oldData = await ctx.call('ldp.resource.get', { resourceUri: destUri, accept: MIME_TYPES.JSON, - webId: 'system', + webId: 'system' }); const oldUpdatedDate = oldData['dc:modified']; @@ -209,7 +209,7 @@ module.exports = { const oldDataToKeep = this.settings.dest.predicatesToKeep.length > 0 ? Object.fromEntries( - Object.entries(oldData).filter(([key]) => this.settings.dest.predicatesToKeep.includes(key)), + Object.entries(oldData).filter(([key]) => this.settings.dest.predicatesToKeep.includes(key)) ) : {}; @@ -221,10 +221,10 @@ module.exports = { 'dc:source': sourceUri, 'dc:created': resource['dc:created'] || this.getField('created', data), 'dc:modified': resource['dc:modified'] || this.getField('updated', data), - 'dc:creator': resource['dc:creator'] || this.settings.dest.actorUri, + 'dc:creator': resource['dc:creator'] || this.settings.dest.actorUri }, contentType: MIME_TYPES.JSON, - webId: 'system', + webId: 'system' }); } else { this.logger.info(`Skipping ${sourceUri} (not changed)...`); @@ -245,10 +245,10 @@ module.exports = { 'dc:source': sourceUri, 'dc:created': resource['dc:created'] || this.getField('created', data), 'dc:modified': resource['dc:modified'] || this.getField('updated', data), - 'dc:creator': resource['dc:creator'] || this.settings.dest.actorUri, + 'dc:creator': resource['dc:creator'] || this.settings.dest.actorUri }, contentType: MIME_TYPES.JSON, - webId: 'system', + webId: 'system' }); this.logger.info(`Done! Resource URL: ${destUri}`); @@ -263,7 +263,7 @@ module.exports = { // TODO also delete blank nodes attached to the resources await ctx.call('ldp.resource.delete', { resourceUri, - webId: 'system', + webId: 'system' }); } @@ -277,7 +277,7 @@ module.exports = { }, getImported() { return this.imported; - }, + } }, methods: { async prepare() { @@ -298,7 +298,7 @@ module.exports = { const headers = { ...this.settings.source.headers, ...this.settings.source.fetchOptions.headers, - ...fetchOptions.headers, + ...fetchOptions.headers }; const response = await fetch(url, { ...this.settings.source.fetchOptions, ...fetchOptions, headers }); if (response.ok) { @@ -328,11 +328,11 @@ module.exports = { if (this.settings.activitypub.actorUri && this.settings.activitypub.activities.includes(type)) { const outbox = await this.broker.call('activitypub.actor.getCollectionUri', { actorUri: this.settings.activitypub.actorUri, - predicate: 'outbox', + predicate: 'outbox' }); const followers = await this.broker.call('activitypub.actor.getCollectionUri', { actorUri: this.settings.activitypub.actorUri, - predicate: 'followers', + predicate: 'followers' }); await this.broker.call( @@ -341,9 +341,9 @@ module.exports = { collectionUri: outbox, type, object: resourceUri, - to: [followers, PUBLIC_URI], + to: [followers, PUBLIC_URI] }, - { meta: { webId: this.settings.dest.actorUri } }, + { meta: { webId: this.settings.dest.actorUri } } ); } }, @@ -362,7 +362,7 @@ module.exports = { if (this.settings.cronJob.time) { const interval = cronParser.parseExpression(this.settings.cronJob.time, { currentDate: new Date((job.opts && job.opts.timestamp) || undefined), - tz: this.settings.cronJob.timeZone, + tz: this.settings.cronJob.timeZone }); toDate = new Date(interval.next().toISOString()); fromDate = new Date(interval.prev().toISOString()); @@ -391,10 +391,10 @@ module.exports = { const oldSourceUris = Object.keys(this.imported); if (this.settings.source.getAllCompact) { - newSourceUris = results.map((data) => this.settings.source.getOneFull(data)); + newSourceUris = results.map(data => this.settings.source.getOneFull(data)); } else { // If we have no compact results, put the data in an object so that we can easily use it with importOne - mappedFullResults = Object.fromEntries(results.map((data) => [this.settings.source.getOneFull(data), data])); + mappedFullResults = Object.fromEntries(results.map(data => [this.settings.source.getOneFull(data), data])); newSourceUris = Object.keys(mappedFullResults); } @@ -404,13 +404,13 @@ module.exports = { // DELETED RESOURCES /// //////////////////////////////////////// - const urisToDelete = oldSourceUris.filter((uri) => !newSourceUris.includes(uri)); + const urisToDelete = oldSourceUris.filter(uri => !newSourceUris.includes(uri)); for (const sourceUri of urisToDelete) { this.logger.info(`Resource ${sourceUri} does not exist anymore, deleting it...`); await this.broker.call('ldp.resource.delete', { resourceUri: this.imported[sourceUri], - webId: 'system', + webId: 'system' }); await this.postActivity(ACTIVITY_TYPES.DELETE, this.imported[sourceUri]); @@ -427,7 +427,7 @@ module.exports = { // CREATED RESOURCES /// //////////////////////////////////////// - const urisToCreate = newSourceUris.filter((uri) => !oldSourceUris.includes(uri)); + const urisToCreate = newSourceUris.filter(uri => !oldSourceUris.includes(uri)); for (const sourceUri of urisToCreate) { this.logger.info(`Resource ${sourceUri} did not exist, importing it...`); @@ -450,25 +450,25 @@ module.exports = { /// //////////////////////////////////////// const urisToUpdate = results - .filter((data) => { + .filter(data => { // If an updated field is available in compact results, filter out items outside of the time frame const updated = this.getField('updated', data); return updated ? fromDate < new Date(updated) && new Date(updated) > toDate : true; }) - .map((data) => this.settings.source.getOneFull(data)) - .filter((uri) => !urisToCreate.includes(uri)); + .map(data => this.settings.source.getOneFull(data)) + .filter(uri => !urisToCreate.includes(uri)); for (const sourceUri of urisToUpdate) { const result = await this.actions.importOne({ sourceUri, destUri: this.imported[sourceUri], - data: mappedFullResults[sourceUri], + data: mappedFullResults[sourceUri] }); if (result === false) { await this.broker.call('ldp.resource.delete', { resourceUri: this.imported[sourceUri], - webId: 'system', + webId: 'system' }); await this.postActivity(ACTIVITY_TYPES.DELETE, this.imported[sourceUri]); @@ -491,8 +491,8 @@ module.exports = { return { deletedUris, createdUris, - updatedUris, + updatedUris }; - }, - }, + } + } }; diff --git a/src/middleware/packages/importer/mixins/jotform.js b/src/middleware/packages/importer/mixins/jotform.js index 2a3bcf1d0..823230ef0 100644 --- a/src/middleware/packages/importer/mixins/jotform.js +++ b/src/middleware/packages/importer/mixins/jotform.js @@ -7,21 +7,21 @@ module.exports = { source: { jotform: { apiKey: null, - type: 'submissions', + type: 'submissions' }, fieldsMapping: { slug: 'id', - created: (data) => convertToIsoString(data.created_at), - updated: (data) => convertToIsoString(data.updated_at), - }, - }, + created: data => convertToIsoString(data.created_at), + updated: data => convertToIsoString(data.updated_at) + } + } }, created() { if (this.settings.source.jotform.type === 'submissions') { this.settings.source.apiUrl = 'https://eu-api.jotform.com'; this.settings.source.headers = { apikey: this.settings.source.jotform.apiKey }; this.settings.source.getAllCompact = 'https://eu-api.jotform.com/user/forms'; - this.settings.source.getOneFull = (data) => `https://eu-api.jotform.com/submission/${data.id}`; + this.settings.source.getOneFull = data => `https://eu-api.jotform.com/submission/${data.id}`; } else { throw new Error('The JotformImporterMixin can only import submissions for now'); } @@ -48,6 +48,6 @@ module.exports = { return result.content; } return false; - }, - }, + } + } }; diff --git a/src/middleware/packages/importer/mixins/prestashop.js b/src/middleware/packages/importer/mixins/prestashop.js index f8f033e78..9097c1684 100644 --- a/src/middleware/packages/importer/mixins/prestashop.js +++ b/src/middleware/packages/importer/mixins/prestashop.js @@ -9,38 +9,38 @@ module.exports = { prestashop: { baseUrl: null, type: null, - wsKey: null, + wsKey: null }, headers: { - 'Output-Format': 'JSON', + 'Output-Format': 'JSON' }, fieldsMapping: { slug: 'link_rewrite', - created: (data) => convertToIsoString(data.date_add), - updated: (data) => convertToIsoString(data.date_upd), - }, - }, + created: data => convertToIsoString(data.date_add), + updated: data => convertToIsoString(data.date_upd) + } + } }, created() { this.settings.source.apiUrl = urlJoin( this.settings.source.prestashop.baseUrl, 'api', - this.settings.source.prestashop.type, + this.settings.source.prestashop.type ); this.settings.source.getAllFull = `${urlJoin( this.settings.source.prestashop.baseUrl, 'api', - this.settings.source.prestashop.type, + this.settings.source.prestashop.type )}?display=full`; this.settings.source.getAllCompact = `${urlJoin( this.settings.source.prestashop.baseUrl, 'api', - this.settings.source.prestashop.type, + this.settings.source.prestashop.type )}?display=[id,date_upd]`; - this.settings.source.getOneFull = (data) => + this.settings.source.getOneFull = data => urlJoin(this.settings.source.prestashop.baseUrl, 'api', this.settings.source.prestashop.type, `${data.id}`); this.settings.source.headers.Authorization = `Basic ${Buffer.from( - `${this.settings.source.prestashop.wsKey}:`, + `${this.settings.source.prestashop.wsKey}:` ).toString('base64')}`; }, methods: { @@ -53,10 +53,10 @@ module.exports = { if (result) { return { ...Object.values(result)[0], - type: Object.keys(result)[0], + type: Object.keys(result)[0] }; } return false; - }, - }, + } + } }; diff --git a/src/middleware/packages/importer/mixins/yeswiki.js b/src/middleware/packages/importer/mixins/yeswiki.js index e481accd7..ca0db328a 100644 --- a/src/middleware/packages/importer/mixins/yeswiki.js +++ b/src/middleware/packages/importer/mixins/yeswiki.js @@ -8,14 +8,14 @@ module.exports = { yeswiki: { baseUrl: null, oldApi: false, - formId: null, + formId: null }, fieldsMapping: { slug: 'id_fiche', - created: (data) => convertToIsoString(data.date_creation_fiche), - updated: (data) => convertToIsoString(data.date_maj_fiche), - }, - }, + created: data => convertToIsoString(data.date_creation_fiche), + updated: data => convertToIsoString(data.date_maj_fiche) + } + } }, created() { const { baseUrl, oldApi, formId } = this.settings.source.yeswiki; @@ -23,14 +23,14 @@ module.exports = { // Note: the form_id parameter is not used by YesWiki, but it allows to have a different base URL for each Bazar list this.settings.source.apiUrl = `${baseUrl}?BazaR/json&demand=entry&form_id=${formId}`; this.settings.source.getAllFull = `${baseUrl}?BazaR/json&demand=entries&id=${formId}`; - this.settings.source.getOneFull = (data) => + this.settings.source.getOneFull = data => `${baseUrl}?BazaR/json&demand=entry&form_id=${formId}&id_fiche=${data.id_fiche}`; } else { const apiPath = `api/forms/${formId}/entries/json`; this.settings.source.apiUrl = `${baseUrl}?${apiPath}`; this.settings.source.getAllFull = `${baseUrl}?${apiPath}`; this.settings.source.getAllCompact = `${baseUrl}?${apiPath}&fields=id_fiche,date_maj_fiche`; - this.settings.source.getOneFull = (data) => `${baseUrl}?${apiPath}/${data.id_fiche}`; + this.settings.source.getOneFull = data => `${baseUrl}?${apiPath}/${data.id_fiche}`; } }, methods: { @@ -44,6 +44,6 @@ module.exports = { return Object.values(data)[0]; } return false; - }, - }, + } + } }; diff --git a/src/middleware/packages/importer/utils.js b/src/middleware/packages/importer/utils.js index 8d6997b0d..77af7991a 100644 --- a/src/middleware/packages/importer/utils.js +++ b/src/middleware/packages/importer/utils.js @@ -2,7 +2,7 @@ const sanitizeHtml = require('sanitize-html'); const PNF = require('google-libphonenumber').PhoneNumberFormat; const phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance(); -const convertToIsoString = (str) => str && new Date(str).toISOString(); +const convertToIsoString = str => str && new Date(str).toISOString(); const formatPhoneNumber = (number, countryCode) => { if (number && countryCode) { @@ -16,7 +16,7 @@ const formatPhoneNumber = (number, countryCode) => { } }; -const frenchAddressSearch = async (query) => { +const frenchAddressSearch = async query => { const url = new URL('https://api-adresse.data.gouv.fr/search/'); url.searchParams.set('q', query); const response = await fetch(url.toString()); @@ -41,12 +41,12 @@ const frenchAddressReverseSearch = async (lat, lon) => { return false; }; -const removeHtmlTags = (text) => sanitizeHtml(text, { allowedTags: [] }).trim(); +const removeHtmlTags = text => sanitizeHtml(text, { allowedTags: [] }).trim(); module.exports = { convertToIsoString, formatPhoneNumber, frenchAddressSearch, frenchAddressReverseSearch, - removeHtmlTags, + removeHtmlTags }; diff --git a/src/middleware/packages/inference/service.js b/src/middleware/packages/inference/service.js index 94e873fb5..bcccd86d5 100644 --- a/src/middleware/packages/inference/service.js +++ b/src/middleware/packages/inference/service.js @@ -11,7 +11,7 @@ module.exports = { baseUrl: null, acceptFromRemoteServers: false, offerToRemoteServers: false, - ontologies: [], + ontologies: [] }, dependencies: ['triplestore', 'ldp', 'jsonld'], created() { @@ -21,8 +21,8 @@ module.exports = { settings: { baseUrl, acceptFromRemoteServers, - offerToRemoteServers, - }, + offerToRemoteServers + } }); } }, @@ -41,11 +41,11 @@ module.exports = { const parser = new N3.Parser({ format: 'Turtle' }); return new Promise((resolve, reject) => { fetch(owlFile) - .then((res) => { + .then(res => { if (!res.ok) throw new Error(`Unable to fetch ${owlFile}`); return res.text(); }) - .then((body) => { + .then(body => { const rel = {}; parser.parse(body, (err, quad) => { if (err) reject(err); @@ -65,7 +65,7 @@ module.exports = { } }); }) - .catch((err) => reject(err)); + .catch(err => reject(err)); }); }, generateInverseTriplesFromResource(resource) { @@ -76,7 +76,7 @@ module.exports = { // uri['@id'] can be undefined if context bad configuration ("@type": "@id" not configured for property) if (uri['@id']) { inverseTriples.push( - triple(namedNode(uri['@id']), namedNode(this.inverseRelations[property]), namedNode(resource['@id'])), + triple(namedNode(uri['@id']), namedNode(this.inverseRelations[property]), namedNode(resource['@id'])) ); } } @@ -93,8 +93,8 @@ module.exports = { triple( namedNode(t.object.value), namedNode(this.inverseRelations[t.predicate.value]), - namedNode(t.subject.value), - ), + namedNode(t.subject.value) + ) ); } } @@ -103,7 +103,7 @@ module.exports = { }, triplesToString(triples) { return triples - .map((triple) => `<${triple.subject.id}> <${triple.predicate.id}> <${triple.object.id}> .`) + .map(triple => `<${triple.subject.id}> <${triple.predicate.id}> <${triple.object.id}> .`) .join('\n'); }, generateInsertQuery(triples) { @@ -141,8 +141,8 @@ module.exports = { }, // Exclude from triples1 the triples which also exist in triples2 getTriplesDifference(triples1, triples2) { - return triples1.filter((t1) => !triples2.some((t2) => t1.equals(t2))); - }, + return triples1.filter(t1 => !triples2.some(t2 => t1.equals(t2))); + } }, events: { async 'ldp.resource.created'(ctx) { @@ -169,7 +169,7 @@ module.exports = { subject: triple.subject.id, predicate: triple.predicate.id, object: triple.object.id, - add: true, + add: true }); } } @@ -194,7 +194,7 @@ module.exports = { subject: triple.subject.id, predicate: triple.predicate.id, object: triple.object.id, - add: false, + add: false }); } } @@ -222,7 +222,7 @@ module.exports = { if (removeLocals.length > 0) { await ctx.call('triplestore.update', { query: this.generateDeleteQuery(removeLocals), - webId: 'system', + webId: 'system' }); this.cleanResourcesCache(ctx, removeLocals); } @@ -230,7 +230,7 @@ module.exports = { if (addLocals.length > 0) { await ctx.call('triplestore.update', { query: this.generateInsertQuery(addLocals), - webId: 'system', + webId: 'system' }); this.cleanResourcesCache(ctx, addLocals); } @@ -244,7 +244,7 @@ module.exports = { subject: triple.subject.id, predicate: triple.predicate.id, object: triple.object.id, - add: true, + add: true }); } for (const triple of removeRemotes) { @@ -252,7 +252,7 @@ module.exports = { subject: triple.subject.id, predicate: triple.predicate.id, object: triple.object.id, - add: false, + add: false }); } } @@ -274,7 +274,7 @@ module.exports = { if (removeLocals.length > 0) { await ctx.call('triplestore.update', { query: this.generateDeleteQuery(removeLocals), - webId: 'system', + webId: 'system' }); this.cleanResourcesCache(ctx, removeLocals); } @@ -282,7 +282,7 @@ module.exports = { if (addLocals.length > 0) { await ctx.call('triplestore.update', { query: this.generateInsertQuery(addLocals), - webId: 'system', + webId: 'system' }); this.cleanResourcesCache(ctx, addLocals); } @@ -296,7 +296,7 @@ module.exports = { subject: triple.subject.id, predicate: triple.predicate.id, object: triple.object.id, - add: true, + add: true }); } for (const triple of removeRemotes) { @@ -304,10 +304,10 @@ module.exports = { subject: triple.subject.id, predicate: triple.predicate.id, object: triple.object.id, - add: false, + add: false }); } } - }, - }, + } + } }; diff --git a/src/middleware/packages/inference/subservices/remote.js b/src/middleware/packages/inference/subservices/remote.js index 6a44e14c1..3a64092de 100644 --- a/src/middleware/packages/inference/subservices/remote.js +++ b/src/middleware/packages/inference/subservices/remote.js @@ -12,7 +12,7 @@ module.exports = { settings: { baseUrl: null, acceptFromRemoteServers: true, - offerToRemoteServers: true, + offerToRemoteServers: true }, dependencies: ['activitypub.relay'], async started() { @@ -25,13 +25,13 @@ module.exports = { subject: { type: 'string', optional: false }, predicate: { type: 'string', optional: false }, object: { type: 'string', optional: false }, - add: { type: 'boolean', optional: false }, + add: { type: 'boolean', optional: false } }, async handler(ctx) { if (this.settings.offerToRemoteServers) { const serverDomainName = new URL(ctx.params.subject).host; const remoteRelayActorUri = await ctx.call('webfinger.getRemoteUri', { - account: `relay@${serverDomainName}`, + account: `relay@${serverDomainName}` }); if (remoteRelayActorUri) { @@ -46,10 +46,10 @@ module.exports = { type: OBJECT_TYPES.RELATIONSHIP, subject: ctx.params.subject, relationship: ctx.params.predicate, - object: ctx.params.object, - }, + object: ctx.params.object + } }, - to: [remoteRelayActorUri], + to: [remoteRelayActorUri] }); } else { // no relay actor on the other side, let's try a PUT instead @@ -57,8 +57,8 @@ module.exports = { const response = await fetch(ctx.params.subject, { method: 'GET', headers: { - Accept: 'application/ld+json', - }, + Accept: 'application/ld+json' + } }); if (response.ok) { let json = await response.json(); @@ -73,25 +73,25 @@ module.exports = { await fetch(ctx.params.subject, { method: 'PUT', headers: { - 'Content-Type': 'application/ld+json', + 'Content-Type': 'application/ld+json' }, - body: JSON.stringify(json), + body: JSON.stringify(json) }); } } catch (e) { this.logger.warn( - `Error while connecting to remove server for offering inverse relationship: ${e.message}`, + `Error while connecting to remove server for offering inverse relationship: ${e.message}` ); } } } - }, - }, + } + } }, methods: { isRemoteUri(uri) { return !urlJoin(uri, '/').startsWith(this.settings.baseUrl); - }, + } }, activities: { offerInference: { @@ -104,11 +104,11 @@ module.exports = { object: { type: ACTIVITY_TYPES.ADD, object: { - type: OBJECT_TYPES.RELATIONSHIP, - }, - }, + type: OBJECT_TYPES.RELATIONSHIP + } + } }, - activity, + activity )) || (await this.matchActivity( ctx, @@ -117,11 +117,11 @@ module.exports = { object: { type: ACTIVITY_TYPES.REMOVE, object: { - type: OBJECT_TYPES.RELATIONSHIP, - }, - }, + type: OBJECT_TYPES.RELATIONSHIP + } + } }, - activity, + activity )) ); }, @@ -137,7 +137,7 @@ module.exports = { // Remove prefix from predicate if it exists relationship.relationship = await ctx.call('jsonld.expandPredicate', { predicate: relationship.relationship, - context: activity['@context'], + context: activity['@context'] }); // TODO ensure that the object exist and has a remote relationship @@ -146,15 +146,15 @@ module.exports = { triple( namedNode(relationship.subject), namedNode(relationship.relationship), - namedNode(relationship.object), - ), + namedNode(relationship.object) + ) ]; await ctx.call('ldp.resource.patch', { resourceUri: relationship.subject, triplesToAdd: activity.object.type === ACTIVITY_TYPES.ADD ? triples : [], triplesToRemove: activity.object.type === ACTIVITY_TYPES.REMOVE ? triples : [], - webId: 'system', + webId: 'system' }); if (this.broker.cacher) { @@ -162,7 +162,7 @@ module.exports = { } } } - }, - }, - }, + } + } + } }; diff --git a/src/middleware/packages/jsonld/service.js b/src/middleware/packages/jsonld/service.js index f96f14914..57a227d43 100644 --- a/src/middleware/packages/jsonld/service.js +++ b/src/middleware/packages/jsonld/service.js @@ -13,7 +13,7 @@ module.exports = { settings: { baseUri: null, localContextFiles: [], - remoteContextFiles: [], + remoteContextFiles: [] }, dependencies: ['api'], async started() { @@ -22,8 +22,8 @@ module.exports = { this.jsonLdParser = new JsonLdParser({ documentLoader: { - load: (url) => this.documentLoaderWithCache(url).then((context) => context.document), - }, + load: url => this.documentLoaderWithCache(url).then(context => context.document) + } }); for (const contextFile of this.settings.localContextFiles) { @@ -35,7 +35,7 @@ module.exports = { cache.set(contextUri, { contextUrl: null, documentUrl: contextUri, - document: contextJson, + document: contextJson }); this.broker.call('api.addRoute', { @@ -43,7 +43,7 @@ module.exports = { path: contextFile.path, name: `context-${contextFile.path.replace(new RegExp('/', 'g'), '-')}`, bodyParsers: { - json: true, + json: true }, aliases: { 'GET /': [ @@ -51,10 +51,10 @@ module.exports = { req.$params.uri = contextUri; next(); }, - 'jsonld.getCachedContext', - ], - }, - }, + 'jsonld.getCachedContext' + ] + } + } }); } @@ -64,7 +64,7 @@ module.exports = { cache.set(contextFile.uri, { contextUrl: null, documentUrl: contextFile.uri, - document: contextJson, + document: contextJson }); } }, @@ -117,8 +117,8 @@ module.exports = { const res = []; this.jsonLdParser .import(textStream) - .on('data', (quad) => res.push(quad)) - .on('error', (error) => reject(error)) + .on('data', quad => res.push(quad)) + .on('error', error => reject(error)) .on('end', () => resolve(res)); }); }, @@ -126,7 +126,7 @@ module.exports = { const { predicate, context } = ctx.params; const result = await this.actions.expand({ input: { '@context': context, [predicate]: '' } }, { parentCtx: ctx }); return Object.keys(result[0])[0]; - }, + } }, methods: { async documentLoaderWithCache(url, options) { @@ -139,6 +139,6 @@ module.exports = { } cache.set(url, context); return context; - }, - }, + } + } }; diff --git a/src/middleware/packages/ldp/adapter.js b/src/middleware/packages/ldp/adapter.js index 35a5734f1..b2b84644b 100644 --- a/src/middleware/packages/ldp/adapter.js +++ b/src/middleware/packages/ldp/adapter.js @@ -16,7 +16,7 @@ class LdpAdapter { async connect() { if (!this.service.schema.settings.containerUri) { throw new ServiceSchemaError( - `Missing \`containerUri\` definition in settings of service ${this.service.schema.name}`, + `Missing \`containerUri\` definition in settings of service ${this.service.schema.name}` ); } @@ -51,7 +51,7 @@ class LdpAdapter { containerUri: this.service.schema.settings.containerUri, filters: filters.query, jsonContext: this.service.schema.settings.context, - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); } @@ -72,7 +72,7 @@ class LdpAdapter { return this.broker.call(`${this.resourceService}.get`, { resourceUri: _id, jsonContext: this.service.schema.settings.context, - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); } @@ -80,7 +80,7 @@ class LdpAdapter { * Find all entities by IDs */ findByIds(ids) { - return Promise.all(ids.map((id) => this.findById(id))); + return Promise.all(ids.map(id => this.findById(id))); } /** @@ -92,7 +92,7 @@ class LdpAdapter { * - query */ count(filters = {}) { - return this.find(filters).then((result) => result['ldp:contains'].length); + return this.find(filters).then(result => result['ldp:contains'].length); } /** @@ -106,15 +106,15 @@ class LdpAdapter { containerUri: this.service.schema.settings.containerUri, resource: { '@context': this.service.schema.settings.context, - ...resource, + ...resource }, slug, - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }) - .then((resourceUri) => { + .then(resourceUri => { this.broker.call(`${this.containerService}.attach`, { containerUri: this.service.schema.settings.containerUri, - resourceUri, + resourceUri }); return this.findById(resourceUri); @@ -151,11 +151,11 @@ class LdpAdapter { resource: { '@context': this.service.schema.settings.context, '@id': _id, - ...resource, + ...resource }, - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }) - .then((resourceUri) => this.findById(resourceUri)); + .then(resourceUri => this.findById(resourceUri)); } /** @@ -171,7 +171,7 @@ class LdpAdapter { removeById(_id) { return this.broker .call(`${this.resourceService}.delete`, { - resourceUri: _id, + resourceUri: _id }) .then(() => { // We must return the number of deleted resource @@ -185,7 +185,7 @@ class LdpAdapter { */ clear() { return this.broker.call(`${this.containerService}.clear`, { - containerUri: this.service.schema.settings.containerUri, + containerUri: this.service.schema.settings.containerUri }); } diff --git a/src/middleware/packages/ldp/mixins/controlled-container.js b/src/middleware/packages/ldp/mixins/controlled-container.js index 1c02e75c9..590cd711d 100644 --- a/src/middleware/packages/ldp/mixins/controlled-container.js +++ b/src/middleware/packages/ldp/mixins/controlled-container.js @@ -12,7 +12,7 @@ module.exports = { newResourcesPermissions: null, controlledActions: {}, readOnly: false, - excludeFromMirror: false, + excludeFromMirror: false }, dependencies: ['ldp'], async started() { @@ -34,9 +34,9 @@ module.exports = { patch: `${this.name}.patch`, put: `${this.name}.put`, delete: `${this.name}.delete`, - ...this.settings.controlledActions, + ...this.settings.controlledActions }, - readOnly: this.settings.readOnly, + readOnly: this.settings.readOnly }); }, actions: { @@ -72,7 +72,7 @@ module.exports = { if (jsonContext) containerParams.jsonContext = jsonContext; return ctx.call('ldp.resource.get', { ...containerParams, - ...ctx.params, + ...ctx.params }); }, create(ctx) { @@ -103,7 +103,7 @@ module.exports = { const parentContainerUri = getContainerFromUri(containerUri); const parentContainerExist = await ctx.call('ldp.container.exist', { containerUri: parentContainerUri, - webId: 'system', + webId: 'system' }); // If a parent container exist, check that the child container has been attached @@ -114,10 +114,10 @@ module.exports = { containerAttached = await ctx.call('ldp.container.includes', { containerUri: parentContainerUri, resourceUri: containerUri, - webId: 'system', + webId: 'system' }); } while (!containerAttached); } - }, - }, + } + } }; diff --git a/src/middleware/packages/ldp/mixins/document-tagger.js b/src/middleware/packages/ldp/mixins/document-tagger.js index ab8db3a14..59a0ea97d 100644 --- a/src/middleware/packages/ldp/mixins/document-tagger.js +++ b/src/middleware/packages/ldp/mixins/document-tagger.js @@ -5,8 +5,8 @@ module.exports = { documentPredicates: { created: 'http://purl.org/dc/terms/created', updated: 'http://purl.org/dc/terms/modified', - creator: 'http://purl.org/dc/terms/creator', - }, + creator: 'http://purl.org/dc/terms/creator' + } }, actions: { async tagCreatedResource(ctx) { @@ -18,7 +18,7 @@ module.exports = { triples.push( `<${resourceUri}> <${ this.settings.documentPredicates.created - }> "${now.toISOString()}"^^ .`, + }> "${now.toISOString()}"^^ .` ); } @@ -26,7 +26,7 @@ module.exports = { triples.push( `<${resourceUri}> <${ this.settings.documentPredicates.updated - }> "${now.toISOString()}"^^ .`, + }> "${now.toISOString()}"^^ .` ); } @@ -37,7 +37,7 @@ module.exports = { if (triples.length > 0) { await ctx.call('triplestore.insert', { resource: triples.join('\n'), - webId: 'system', + webId: 'system' }); } }, @@ -48,13 +48,13 @@ module.exports = { query: ` DELETE { <${resourceUri}> <${this.settings.documentPredicates.updated}> ?updated } INSERT { <${resourceUri}> <${ - this.settings.documentPredicates.updated - }> "${now.toISOString()}"^^ } + this.settings.documentPredicates.updated + }> "${now.toISOString()}"^^ } WHERE { <${resourceUri}> <${this.settings.documentPredicates.updated}> ?updated } `, - webId: 'system', + webId: 'system' }); - }, + } }, events: { async 'ldp.resource.created'(ctx) { @@ -68,7 +68,7 @@ module.exports = { async 'ldp.resource.patched'(ctx) { const { resourceUri } = ctx.params; this.actions.tagUpdatedResource({ resourceUri }, { parentCtx: ctx }); - }, + } }, hooks: { before: { @@ -76,7 +76,7 @@ module.exports = { if (this.settings.podProvider && !ctx.meta.dataset) { ctx.meta.dataset = getDatasetFromUri(ctx.params.resourceUri); } - }, - }, - }, + } + } + } }; diff --git a/src/middleware/packages/ldp/mixins/image-processor.js b/src/middleware/packages/ldp/mixins/image-processor.js index 46e324dae..dd1b8ccd5 100644 --- a/src/middleware/packages/ldp/mixins/image-processor.js +++ b/src/middleware/packages/ldp/mixins/image-processor.js @@ -10,15 +10,15 @@ module.exports = { maxWidth: 1900, maxHeight: 1000, jpeg: { - quality: 85, + quality: 85 }, png: { - compressionLevel: 8, + compressionLevel: 8 }, webp: { - quality: 85, - }, - }, + quality: 85 + } + } }, actions: { async processImage(ctx) { @@ -29,7 +29,7 @@ module.exports = { jsonContext: { '@vocab': 'http://semapps.org/ns/core#' }, accept: MIME_TYPES.JSON, forceSemantic: true, - webId: 'system', + webId: 'system' }); try { @@ -75,23 +75,23 @@ module.exports = { } } this.logger.info('Finished !'); - }, + } }, methods: { getMaxSize(width, height) { const ratio = Math.min( this.settings.imageProcessor.maxWidth / width, - this.settings.imageProcessor.maxHeight / height, + this.settings.imageProcessor.maxHeight / height ); return { width: Math.round(width * ratio), height: Math.round(height * ratio) }; - }, + } }, hooks: { after: { async create(ctx, res) { await this.actions.processImage({ resourceUri: res.resourceUri }, { parentCtx: ctx }); return res; - }, - }, - }, + } + } + } }; diff --git a/src/middleware/packages/ldp/routes/getContainerRoute.js b/src/middleware/packages/ldp/routes/getContainerRoute.js index 4dc3b3060..4922b0a0e 100644 --- a/src/middleware/packages/ldp/routes/getContainerRoute.js +++ b/src/middleware/packages/ldp/routes/getContainerRoute.js @@ -7,7 +7,7 @@ const { parseTurtle, parseFile, addContainerUriMiddleware, - saveDatasetMeta, + saveDatasetMeta } = require('@semapps/middlewares'); function getContainerRoute(containerUri, readOnly = false) { @@ -22,20 +22,20 @@ function getContainerRoute(containerUri, readOnly = false) { parseTurtle, parseFile, addContainerUriMiddleware(containerUri), - saveDatasetMeta, + saveDatasetMeta ]; // Container aliases let aliases = { 'GET /': [...middlewares, 'ldp.container.api_get'], - 'HEAD /': [addContainerUriMiddleware(containerUri), 'ldp.container.api_head'], + 'HEAD /': [addContainerUriMiddleware(containerUri), 'ldp.container.api_head'] }; if (!readOnly) { aliases = { ...aliases, 'POST /': [...middlewares, 'ldp.container.api_post'], - 'PATCH /': [...middlewares, 'ldp.container.api_patch'], + 'PATCH /': [...middlewares, 'ldp.container.api_patch'] }; } @@ -44,7 +44,7 @@ function getContainerRoute(containerUri, readOnly = false) { aliases = { ...aliases, 'GET /:id': [...middlewares, 'ldp.resource.api_get'], - 'HEAD /:id': [addContainerUriMiddleware(containerUri), 'ldp.resource.api_head'], + 'HEAD /:id': [addContainerUriMiddleware(containerUri), 'ldp.resource.api_head'] }; if (!readOnly) { @@ -52,7 +52,7 @@ function getContainerRoute(containerUri, readOnly = false) { ...aliases, 'PUT /:id': [...middlewares, 'ldp.resource.api_put'], 'PATCH /:id': [...middlewares, 'ldp.resource.api_patch'], - 'DELETE /:id': [...middlewares, 'ldp.resource.api_delete'], + 'DELETE /:id': [...middlewares, 'ldp.resource.api_delete'] }; } } @@ -65,7 +65,7 @@ function getContainerRoute(containerUri, readOnly = false) { bodyParsers: false, authorization: false, authentication: true, - aliases, + aliases }; } diff --git a/src/middleware/packages/ldp/routes/getResourcesRoute.js b/src/middleware/packages/ldp/routes/getResourcesRoute.js index 671201053..5e8983a90 100644 --- a/src/middleware/packages/ldp/routes/getResourcesRoute.js +++ b/src/middleware/packages/ldp/routes/getResourcesRoute.js @@ -7,7 +7,7 @@ const { parseTurtle, parseFile, addContainerUriMiddleware, - saveDatasetMeta, + saveDatasetMeta } = require('@semapps/middlewares'); function getResourcesRoute(containerUri, readOnly = false) { @@ -22,12 +22,12 @@ function getResourcesRoute(containerUri, readOnly = false) { parseTurtle, parseFile, addContainerUriMiddleware(containerUri), - saveDatasetMeta, + saveDatasetMeta ]; let aliases = { 'GET /:id': [...middlewares, 'ldp.resource.api_get'], - 'HEAD /:id': [addContainerUriMiddleware(containerUri), 'ldp.resource.api_head'], + 'HEAD /:id': [addContainerUriMiddleware(containerUri), 'ldp.resource.api_head'] }; if (!readOnly) { @@ -35,7 +35,7 @@ function getResourcesRoute(containerUri, readOnly = false) { ...aliases, 'PUT /:id': [...middlewares, 'ldp.resource.api_put'], 'PATCH /:id': [...middlewares, 'ldp.resource.api_patch'], - 'DELETE /:id': [...middlewares, 'ldp.resource.api_delete'], + 'DELETE /:id': [...middlewares, 'ldp.resource.api_delete'] }; } @@ -47,7 +47,7 @@ function getResourcesRoute(containerUri, readOnly = false) { bodyParsers: false, authorization: false, authentication: true, - aliases, + aliases }; } diff --git a/src/middleware/packages/ldp/services/cache/index.js b/src/middleware/packages/ldp/services/cache/index.js index 10a5bdc4d..83b015c52 100644 --- a/src/middleware/packages/ldp/services/cache/index.js +++ b/src/middleware/packages/ldp/services/cache/index.js @@ -32,7 +32,7 @@ module.exports = { const { containerUri } = ctx.params; await this.broker.cacher.clean(`ldp.container.get:${containerUri}**`); } - }, + } }, events: { async 'ldp.resource.deleted'(ctx) { @@ -83,6 +83,6 @@ module.exports = { } else { await this.actions.invalidateResource({ resourceUri: uri }, { parentCtx: ctx }); } - }, - }, + } + } }; diff --git a/src/middleware/packages/ldp/services/container/actions/attach.js b/src/middleware/packages/ldp/services/container/actions/attach.js index c96d02280..8e96de68b 100644 --- a/src/middleware/packages/ldp/services/container/actions/attach.js +++ b/src/middleware/packages/ldp/services/container/actions/attach.js @@ -7,8 +7,8 @@ module.exports = { resourceUri: { type: 'string' }, webId: { type: 'string', - optional: true, - }, + optional: true + } }, async handler(ctx) { const { containerUri, resourceUri } = ctx.params; @@ -30,7 +30,7 @@ module.exports = { await ctx.call('triplestore.insert', { resource: `<${containerUri}> <${resourceUri}>`, webId, - graphName: isRemoteContainer ? this.settings.mirrorGraphName : undefined, + graphName: isRemoteContainer ? this.settings.mirrorGraphName : undefined }); if (!isRemoteContainer) @@ -38,15 +38,15 @@ module.exports = { 'ldp.container.attached', { containerUri, - resourceUri, + resourceUri }, - { meta: { webId: null } }, + { meta: { webId: null } } ); return { containerUri, resourceUri, - webId, + webId }; - }, + } }; diff --git a/src/middleware/packages/ldp/services/container/actions/clear.js b/src/middleware/packages/ldp/services/container/actions/clear.js index 0eb676e8b..52711891b 100644 --- a/src/middleware/packages/ldp/services/container/actions/clear.js +++ b/src/middleware/packages/ldp/services/container/actions/clear.js @@ -2,7 +2,7 @@ module.exports = { visibility: 'public', params: { containerUri: { type: 'string' }, - webId: { type: 'string', optional: true }, + webId: { type: 'string', optional: true } }, async handler(ctx) { let { containerUri, webId } = ctx.params; @@ -23,11 +23,11 @@ module.exports = { OPTIONAL { ?s1 ?p1 ?o1 . } } `, - webId, + webId }); // TODO: emit an event that will be handled by mirror service. ctx.call('triplestore.deleteOrphanBlankNodes'); - }, + } }; diff --git a/src/middleware/packages/ldp/services/container/actions/detach.js b/src/middleware/packages/ldp/services/container/actions/detach.js index 551327b2a..929a56f27 100644 --- a/src/middleware/packages/ldp/services/container/actions/detach.js +++ b/src/middleware/packages/ldp/services/container/actions/detach.js @@ -5,7 +5,7 @@ module.exports = { params: { containerUri: { type: 'string' }, resourceUri: { type: 'string' }, - webId: { type: 'string', optional: true }, + webId: { type: 'string', optional: true } }, async handler(ctx) { let { containerUri, resourceUri } = ctx.params; @@ -31,7 +31,7 @@ module.exports = { ${isRemoteContainer ? '}' : ''} } `, - webId, + webId }); if (!isRemoteContainer) @@ -39,9 +39,9 @@ module.exports = { 'ldp.container.detached', { containerUri, - resourceUri, + resourceUri }, - { meta: { webId: null, dataset: null } }, + { meta: { webId: null, dataset: null } } ); - }, + } }; diff --git a/src/middleware/packages/ldp/services/container/actions/exist.js b/src/middleware/packages/ldp/services/container/actions/exist.js index 6cad36663..1a1911203 100644 --- a/src/middleware/packages/ldp/services/container/actions/exist.js +++ b/src/middleware/packages/ldp/services/container/actions/exist.js @@ -4,7 +4,7 @@ module.exports = { visibility: 'public', params: { containerUri: { type: 'string' }, - webId: { type: 'string', optional: true }, + webId: { type: 'string', optional: true } }, async handler(ctx) { const webId = ctx.params.webId || ctx.meta.webId || 'anon'; @@ -25,7 +25,7 @@ module.exports = { } `, accept: MIME_TYPES.JSON, - webId, + webId }); - }, + } }; diff --git a/src/middleware/packages/ldp/services/container/actions/get.js b/src/middleware/packages/ldp/services/container/actions/get.js index a4f2dc475..9d7cbd273 100644 --- a/src/middleware/packages/ldp/services/container/actions/get.js +++ b/src/middleware/packages/ldp/services/container/actions/get.js @@ -5,7 +5,7 @@ const { buildDereferenceQuery, buildFiltersQuery, isContainer, - defaultToArray, + defaultToArray } = require('../../../utils'); module.exports = { @@ -13,13 +13,13 @@ module.exports = { const { containerUri } = ctx.params; const { accept, controlledActions } = { ...(await ctx.call('ldp.registry.getByUri', { containerUri })), - ...ctx.meta.headers, + ...ctx.meta.headers }; try { ctx.meta.$responseType = ctx.meta.$responseType || accept; return await ctx.call(controlledActions.list || 'ldp.container.get', { containerUri, - accept, + accept }); } catch (e) { console.error(e); @@ -38,11 +38,11 @@ module.exports = { jsonContext: { type: 'multi', rules: [{ type: 'array' }, { type: 'object' }, { type: 'string' }], - optional: true, - }, + optional: true + } }, cache: { - keys: ['containerUri', 'accept', 'filters', 'dereference', 'jsonContext', 'webId', '#webId'], + keys: ['containerUri', 'accept', 'filters', 'dereference', 'jsonContext', 'webId', '#webId'] }, async handler(ctx) { const { containerUri, filters } = ctx.params; @@ -51,7 +51,7 @@ module.exports = { const { accept, dereference, jsonContext } = { ...(await ctx.call('ldp.registry.getByUri', { containerUri })), - ...ctx.params, + ...ctx.params }; const filtersQuery = buildFiltersQuery(filters); @@ -76,7 +76,7 @@ module.exports = { } `, accept, - webId, + webId }); // Request each resources @@ -98,7 +98,7 @@ module.exports = { webId, forceSemantic: true, // We pass the following parameters only if they are explicit - ...explicitParams, + ...explicitParams }); // If we have a child container, remove the ldp:contains property and add a ldp:Resource type @@ -121,14 +121,14 @@ module.exports = { input: { '@id': containerUri, '@type': ['http://www.w3.org/ns/ldp#Container', 'http://www.w3.org/ns/ldp#BasicContainer'], - 'http://www.w3.org/ns/ldp#contains': resources, + 'http://www.w3.org/ns/ldp#contains': resources }, - context: jsonContext || getPrefixJSON(this.settings.ontologies), + context: jsonContext || getPrefixJSON(this.settings.ontologies) }); // If the ldp:contains is a single object, wrap it in an array for easier handling on the front side - const ldpContainsKey = Object.keys(result).find((key) => - ['http://www.w3.org/ns/ldp#contains', 'ldp:contains', 'contains'].includes(key), + const ldpContainsKey = Object.keys(result).find(key => + ['http://www.w3.org/ns/ldp#contains', 'ldp:contains', 'contains'].includes(key) ); if (ldpContainsKey && !Array.isArray(result[ldpContainsKey])) { result[ldpContainsKey] = [result[ldpContainsKey]]; @@ -159,8 +159,8 @@ module.exports = { } `, accept, - webId, + webId }); - }, - }, + } + } }; diff --git a/src/middleware/packages/ldp/services/container/actions/head.js b/src/middleware/packages/ldp/services/container/actions/head.js index 5869716b3..83cc0e878 100644 --- a/src/middleware/packages/ldp/services/container/actions/head.js +++ b/src/middleware/packages/ldp/services/container/actions/head.js @@ -9,7 +9,7 @@ module.exports = { ctx.meta.$statusMessage = 'OK'; ctx.meta.$responseHeaders = { Link: `<${aclUri}>; rel="acl"`, - 'Content-Length': 0, + 'Content-Length': 0 }; - }, + } }; diff --git a/src/middleware/packages/ldp/services/container/actions/includes.js b/src/middleware/packages/ldp/services/container/actions/includes.js index f8c87cc03..ac0e8be8f 100644 --- a/src/middleware/packages/ldp/services/container/actions/includes.js +++ b/src/middleware/packages/ldp/services/container/actions/includes.js @@ -5,8 +5,8 @@ module.exports = { resourceUri: { type: 'string' }, webId: { type: 'string', - optional: true, - }, + optional: true + } }, async handler(ctx) { const { containerUri, resourceUri } = ctx.params; @@ -22,7 +22,7 @@ module.exports = { ${isRemoteContainer ? '}' : ''} } `, - webId, + webId }); - }, + } }; diff --git a/src/middleware/packages/ldp/services/container/actions/isEmpty.js b/src/middleware/packages/ldp/services/container/actions/isEmpty.js index 7e0a24665..f4da7cb66 100644 --- a/src/middleware/packages/ldp/services/container/actions/isEmpty.js +++ b/src/middleware/packages/ldp/services/container/actions/isEmpty.js @@ -4,8 +4,8 @@ module.exports = { containerUri: { type: 'string' }, webId: { type: 'string', - optional: true, - }, + optional: true + } }, async handler(ctx) { const { containerUri } = ctx.params; @@ -15,10 +15,10 @@ module.exports = { const res = await ctx.call('triplestore.query', { query: `SELECT (COUNT (?o) as ?count) { <${containerUri}> ?o }`, webId, - dataset, + dataset }); const num = Number(res[0].count.value); return num === 0; - }, + } }; diff --git a/src/middleware/packages/ldp/services/container/actions/patch.js b/src/middleware/packages/ldp/services/container/actions/patch.js index f8156f933..31b2d16e1 100644 --- a/src/middleware/packages/ldp/services/container/actions/patch.js +++ b/src/middleware/packages/ldp/services/container/actions/patch.js @@ -11,13 +11,13 @@ module.exports = { if (ctx.meta.parser === 'sparql') { await ctx.call('ldp.container.patch', { containerUri, - sparqlUpdate: body, + sparqlUpdate: body }); } else { throw new MoleculerError(`The content-type should be application/sparql-update`, 400, 'BAD_REQUEST'); } ctx.meta.$responseHeaders = { - 'Content-Length': 0, + 'Content-Length': 0 }; ctx.meta.$statusCode = 204; } catch (e) { @@ -30,15 +30,15 @@ module.exports = { visibility: 'public', params: { containerUri: { - type: 'string', + type: 'string' }, sparqlUpdate: { - type: 'string', + type: 'string' }, webId: { type: 'string', - optional: true, - }, + optional: true + } }, async handler(ctx) { let { containerUri, sparqlUpdate, webId } = ctx.params; @@ -56,7 +56,7 @@ module.exports = { throw new MoleculerError('Invalid SPARQL. Must be an Update', 400, 'BAD_REQUEST'); const updates = { insert: [], delete: [] }; - parsedQuery.updates.forEach((p) => updates[p.updateType].push(p[p.updateType][0])); + parsedQuery.updates.forEach(p => updates[p.updateType].push(p[p.updateType][0])); for (const inss of updates.insert) { // check that the containerUri is the same as specified in the params. ignore if not. @@ -74,7 +74,7 @@ module.exports = { resourceUri: insUri, keepInSync: true, mirrorGraph: true, - webId, + webId }); // Now if the import went well, we can retry the attach @@ -111,6 +111,6 @@ module.exports = { } ctx.emit('ldp.container.patched', { containerUri }, { meta: { webId: null, dataset: null } }); - }, - }, + } + } }; diff --git a/src/middleware/packages/ldp/services/container/actions/post.js b/src/middleware/packages/ldp/services/container/actions/post.js index c4a380ee9..1cfdf6664 100644 --- a/src/middleware/packages/ldp/services/container/actions/post.js +++ b/src/middleware/packages/ldp/services/container/actions/post.js @@ -12,7 +12,7 @@ module.exports = { containerUri, slug: ctx.meta.headers.slug, resource, - contentType: ctx.meta.headers['content-type'], + contentType: ctx.meta.headers['content-type'] }); } else { if (ctx.params.files.length > 1) { @@ -22,13 +22,13 @@ module.exports = { containerUri, slug: ctx.meta.headers.slug || ctx.params.files[0].filename, file: ctx.params.files[0], - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }); } ctx.meta.$responseHeaders = { Location: resourceUri, Link: '; rel="type"', - 'Content-Length': 0, + 'Content-Length': 0 }; ctx.meta.$statusCode = 201; } catch (e) { @@ -41,31 +41,31 @@ module.exports = { visibility: 'public', params: { containerUri: { - type: 'string', + type: 'string' }, slug: { type: 'string', - optional: true, + optional: true }, resource: { type: 'object', - optional: true, + optional: true }, file: { type: 'object', - optional: true, + optional: true }, contentType: { - type: 'string', + type: 'string' }, webId: { type: 'string', - optional: true, + optional: true }, disassembly: { type: 'array', - optional: true, - }, + optional: true + } }, async handler(ctx) { let { resource, containerUri, slug, contentType, file } = ctx.params; @@ -78,7 +78,7 @@ module.exports = { throw new MoleculerError( `Cannot create resource in non-existing container ${containerUri}`, 400, - 'BAD_REQUEST', + 'BAD_REQUEST' ); } @@ -87,7 +87,7 @@ module.exports = { // TODO Add temporary ACLs to the resource so that it can be created, then link it to the container ? await ctx.call('triplestore.insert', { resource: `<${containerUri}> <${resourceUri}>`, - webId, + webId }); try { @@ -100,16 +100,16 @@ module.exports = { await ctx.call(controlledActions.create || 'ldp.resource.create', { resource: { '@id': resourceUri, - ...resource, + ...resource }, contentType, - webId, + webId }); } catch (e) { // If there was an error inserting the resource, detach it from the container await ctx.call('triplestore.update', { query: `DELETE WHERE { <${containerUri}> <${resourceUri}> }`, - webId, + webId }); // Re-throw the error so that it's displayed by the API function @@ -121,12 +121,12 @@ module.exports = { { containerUri, resourceUri, - fromContainerPost: true, + fromContainerPost: true }, - { meta: { webId: null, dataset: null } }, + { meta: { webId: null, dataset: null } } ); return resourceUri; - }, - }, + } + } }; diff --git a/src/middleware/packages/ldp/services/container/index.js b/src/middleware/packages/ldp/services/container/index.js index 90f642e43..4522f0d04 100644 --- a/src/middleware/packages/ldp/services/container/index.js +++ b/src/middleware/packages/ldp/services/container/index.js @@ -20,7 +20,7 @@ module.exports = { baseUrl: null, ontologies: [], podProvider: false, - mirrorGraphName: null, + mirrorGraphName: null }, dependencies: ['triplestore', 'jsonld'], actions: { @@ -40,7 +40,7 @@ module.exports = { api_get: getAction.api, api_post: postAction.api, api_head: headAction.api, - api_patch: patchAction.api, + api_patch: patchAction.api }, methods: { isRemoteUri(uri, dataset) { @@ -50,7 +50,7 @@ module.exports = { !urlJoin(uri, '/').startsWith(this.settings.baseUrl) || (this.settings.podProvider && !urlJoin(uri, '/').startsWith(`${urlJoin(this.settings.baseUrl, dataset)}/`)) ); - }, + } }, hooks: { before: { @@ -64,7 +64,7 @@ module.exports = { // this.logger.warn(`No dataset found when calling ${ctx.action.name} with URI ${ctx.params.containerUri}`); ctx.meta.dataset = getDatasetFromUri(ctx.params.containerUri); } - }, - }, - }, + } + } + } }; diff --git a/src/middleware/packages/ldp/services/registry/actions/getByUri.js b/src/middleware/packages/ldp/services/registry/actions/getByUri.js index b044eacc2..87436d3a6 100644 --- a/src/middleware/packages/ldp/services/registry/actions/getByUri.js +++ b/src/middleware/packages/ldp/services/registry/actions/getByUri.js @@ -2,7 +2,7 @@ module.exports = { visibility: 'public', params: { containerUri: { type: 'string', optional: true }, - resourceUri: { type: 'string', optional: true }, + resourceUri: { type: 'string', optional: true } }, async handler(ctx) { let { containerUri, resourceUri } = ctx.params; @@ -19,9 +19,9 @@ module.exports = { if (containerUri) { const path = new URL(containerUri).pathname; const containerOptions = - Object.values(this.registeredContainers).find((container) => container.pathRegex.test(path)) || {}; + Object.values(this.registeredContainers).find(container => container.pathRegex.test(path)) || {}; return { ...this.settings.defaultOptions, ...containerOptions }; } return this.settings.defaultOptions; - }, + } }; diff --git a/src/middleware/packages/ldp/services/registry/actions/getUri.js b/src/middleware/packages/ldp/services/registry/actions/getUri.js index 224acde1b..dd30fae21 100644 --- a/src/middleware/packages/ldp/services/registry/actions/getUri.js +++ b/src/middleware/packages/ldp/services/registry/actions/getUri.js @@ -4,7 +4,7 @@ module.exports = { visibility: 'public', params: { path: { type: 'string' }, - webId: { type: 'string', optional: true }, + webId: { type: 'string', optional: true } }, async handler(ctx) { const { path, webId } = ctx.params; @@ -15,5 +15,5 @@ module.exports = { return urlJoin(account.podUri, path); } return urlJoin(this.settings.baseUrl, path); - }, + } }; diff --git a/src/middleware/packages/ldp/services/registry/actions/register.js b/src/middleware/packages/ldp/services/registry/actions/register.js index ad60d125d..36c58df23 100644 --- a/src/middleware/packages/ldp/services/registry/actions/register.js +++ b/src/middleware/packages/ldp/services/registry/actions/register.js @@ -17,7 +17,7 @@ module.exports = { excludeFromMirror: { type: 'boolean', optional: true }, newResourcesPermissions: { type: 'multi', rules: [{ type: 'object' }, { type: 'function' }], optional: true }, controlledActions: { type: 'object', optional: true }, - readOnly: { type: 'boolean', optional: true }, + readOnly: { type: 'boolean', optional: true } }, async handler(ctx) { let { path, fullPath, name, podsContainer, ...options } = ctx.params; @@ -25,7 +25,7 @@ module.exports = { if (!name) name = path; // Ignore undefined options - Object.keys(options).forEach((key) => (options[key] === undefined || options[key] === null) && delete options[key]); + Object.keys(options).forEach(key => (options[key] === undefined || options[key] === null) && delete options[key]); if (this.settings.podProvider && podsContainer === true) { name = 'actors'; @@ -63,7 +63,7 @@ module.exports = { ctx.emit( 'ldp.registry.registered', { container: this.registeredContainers[name] }, - { meta: { webId: null, dataset: null } }, + { meta: { webId: null, dataset: null } } ); - }, + } }; diff --git a/src/middleware/packages/ldp/services/registry/index.js b/src/middleware/packages/ldp/services/registry/index.js index e036056c9..3736dc7a3 100644 --- a/src/middleware/packages/ldp/services/registry/index.js +++ b/src/middleware/packages/ldp/services/registry/index.js @@ -13,7 +13,7 @@ module.exports = { baseUrl: null, containers: [], defaultOptions, - podProvider: false, + podProvider: false }, dependencies: ['ldp.container', 'api'], actions: { @@ -21,7 +21,7 @@ module.exports = { getByUri: getByUriAction, getUri: getUriAction, list: listAction, - register: registerAction, + register: registerAction }, async started() { this.registeredContainers = {}; @@ -68,18 +68,18 @@ module.exports = { const parentExists = await ctx.call('ldp.container.exist', { containerUri: parentContainerUri, - webId: 'system', + webId: 'system' }); if (parentExists) { await ctx.call('ldp.container.attach', { containerUri: parentContainerUri, resourceUri: containerUri, - webId: 'system', + webId: 'system' }); } } } - }, + } }, events: { async 'auth.registered'(ctx) { @@ -92,6 +92,6 @@ module.exports = { await this.createAndAttachContainer(ctx, containerUri, container.path); } } - }, - }, + } + } }; diff --git a/src/middleware/packages/ldp/services/remote/actions/delete.js b/src/middleware/packages/ldp/services/remote/actions/delete.js index 20d12a221..0f7fded78 100644 --- a/src/middleware/packages/ldp/services/remote/actions/delete.js +++ b/src/middleware/packages/ldp/services/remote/actions/delete.js @@ -2,7 +2,7 @@ module.exports = { visibility: 'public', params: { resourceUri: { type: 'string' }, - webId: { type: 'string', optional: true }, + webId: { type: 'string', optional: true } }, async handler(ctx) { const { resourceUri, webId } = ctx.params; @@ -28,7 +28,7 @@ module.exports = { ${graphName ? '}' : ''} } `, - webId: 'system', + webId: 'system' }); // Detach from all containers with the mirrored resource @@ -38,10 +38,10 @@ module.exports = { } ctx.call('triplestore.deleteOrphanBlankNodes', { - graphName, + graphName }); ctx.emit('ldp.remote.deleted', { resourceUri, webId }, { meta: { webId: null } }); } - }, + } }; diff --git a/src/middleware/packages/ldp/services/remote/actions/get.js b/src/middleware/packages/ldp/services/remote/actions/get.js index c7b4f8985..0233d271e 100644 --- a/src/middleware/packages/ldp/services/remote/actions/get.js +++ b/src/middleware/packages/ldp/services/remote/actions/get.js @@ -10,8 +10,8 @@ module.exports = { strategy: { type: 'enum', values: ['cacheFirst', 'networkFirst', 'cacheOnly', 'networkOnly', 'staleWhileRevalidate'], - default: 'cacheFirst', - }, + default: 'cacheFirst' + } }, async handler(ctx) { const { resourceUri, accept, ...rest } = ctx.params; @@ -29,7 +29,7 @@ module.exports = { switch (strategy) { case 'cacheFirst': - return this.actions.getStored({ resourceUri, webId, accept, ...rest }, { parentCtx: ctx }).catch((e) => { + return this.actions.getStored({ resourceUri, webId, accept, ...rest }, { parentCtx: ctx }).catch(e => { if (e.code === 404) { return this.actions.getNetwork({ resourceUri, webId, accept }, { parentCtx: ctx }); } @@ -37,7 +37,7 @@ module.exports = { }); case 'networkFirst': - return this.actions.getNetwork({ resourceUri, webId, accept }, { parentCtx: ctx }).catch((e) => { + return this.actions.getNetwork({ resourceUri, webId, accept }, { parentCtx: ctx }).catch(e => { if (e.code === 404) { return this.actions.getStored({ resourceUri, webId, accept, ...rest }, { parentCtx: ctx }); } @@ -53,5 +53,5 @@ module.exports = { case 'staleWhileRevalidate': throw new Error(`Strategy staleWhileRevalidate not implemented yet`); } - }, + } }; diff --git a/src/middleware/packages/ldp/services/remote/actions/getGraph.js b/src/middleware/packages/ldp/services/remote/actions/getGraph.js index c967398d2..fcd1723d3 100644 --- a/src/middleware/packages/ldp/services/remote/actions/getGraph.js +++ b/src/middleware/packages/ldp/services/remote/actions/getGraph.js @@ -3,14 +3,14 @@ const { triple, namedNode, variable } = require('@rdfjs/data-model'); module.exports = { visibility: 'public', params: { - resourceUri: { type: 'string' }, + resourceUri: { type: 'string' } }, async handler(ctx) { const { resourceUri } = ctx.params; let exist = await ctx.call('triplestore.tripleExist', { triple: triple(namedNode(resourceUri), variable('p'), variable('s')), - webId: 'system', + webId: 'system' }); if (exist) { @@ -18,12 +18,12 @@ module.exports = { } exist = await ctx.call('triplestore.tripleExist', { triple: triple(namedNode(resourceUri), variable('p'), variable('s')), - graphName: this.settings.mirrorGraphName, + graphName: this.settings.mirrorGraphName }); if (exist) { return this.settings.mirrorGraphName; } return false; - }, + } }; diff --git a/src/middleware/packages/ldp/services/remote/actions/getNetwork.js b/src/middleware/packages/ldp/services/remote/actions/getNetwork.js index ff0a2bc8d..8c156b99b 100644 --- a/src/middleware/packages/ldp/services/remote/actions/getNetwork.js +++ b/src/middleware/packages/ldp/services/remote/actions/getNetwork.js @@ -7,7 +7,7 @@ module.exports = { params: { resourceUri: { type: 'string' }, accept: { type: 'string', default: MIME_TYPES.JSON }, - webId: { type: 'string', optional: true }, + webId: { type: 'string', optional: true } }, async handler(ctx) { const { resourceUri, accept } = ctx.params; @@ -23,7 +23,7 @@ module.exports = { url: resourceUri, method: 'GET', headers, - actorUri: webId, + actorUri: webId }); return body; } @@ -35,5 +35,5 @@ module.exports = { return await response.text(); } throw new MoleculerError(response.statusText, response.status); - }, + } }; diff --git a/src/middleware/packages/ldp/services/remote/actions/getStored.js b/src/middleware/packages/ldp/services/remote/actions/getStored.js index 4c2be4f0f..ab1446556 100644 --- a/src/middleware/packages/ldp/services/remote/actions/getStored.js +++ b/src/middleware/packages/ldp/services/remote/actions/getStored.js @@ -7,7 +7,7 @@ module.exports = { params: { resourceUri: { type: 'string' }, accept: { type: 'string', default: MIME_TYPES.JSON }, - webId: { type: 'string', optional: true }, + webId: { type: 'string', optional: true } }, async handler(ctx) { const { resourceUri } = ctx.params; @@ -15,7 +15,7 @@ module.exports = { const { accept, dereference, jsonContext } = { ...(await ctx.call('ldp.registry.getByUri', { resourceUri })), - ...ctx.params, + ...ctx.params }; const graphName = await this.actions.getGraph({ resourceUri, webId }, { parentCtx: ctx }); @@ -47,7 +47,7 @@ module.exports = { } `, accept, - webId, + webId }); // If we asked for JSON-LD, frame it using the correct context in order to have clean, consistent results @@ -56,13 +56,13 @@ module.exports = { input: result, frame: { '@context': jsonContext || getPrefixJSON(this.settings.ontologies), - '@id': resourceUri, - }, + '@id': resourceUri + } }); } return result; } throw new MoleculerError(`Resource Not found ${resourceUri} in dataset ${ctx.meta.dataset}`, 404, 'NOT_FOUND'); - }, + } }; diff --git a/src/middleware/packages/ldp/services/remote/index.js b/src/middleware/packages/ldp/services/remote/index.js index 61842a3eb..d896c8d05 100644 --- a/src/middleware/packages/ldp/services/remote/index.js +++ b/src/middleware/packages/ldp/services/remote/index.js @@ -15,7 +15,7 @@ module.exports = { baseUrl: null, ontologies: [], podProvider: false, - mirrorGraphName: null, + mirrorGraphName: null }, dependencies: ['triplestore', 'jsonld'], actions: { @@ -28,7 +28,7 @@ module.exports = { store: storeAction, runCron() { this.updateSingleMirroredResources(); - }, // Used by tests + } // Used by tests }, methods: { isRemoteUri(uri, webId) { @@ -43,7 +43,7 @@ module.exports = { }, async proxyAvailable() { const services = await this.broker.call('$node.services'); - return services.some((s) => s.name === 'signature.proxy'); + return services.some(s => s.name === 'signature.proxy'); }, async updateSingleMirroredResources() { if (!this.settings.podProvider) { @@ -55,15 +55,15 @@ module.exports = { ?s ?o } } - `, + ` }); - for (const resourceUri of singles.map((node) => node.s.value)) { + for (const resourceUri of singles.map(node => node.s.value)) { try { await this.actions.store({ resourceUri, keepInSync: true, - mirrorGraph: true, + mirrorGraph: true }); } catch (e) { if (e.code === 403 || e.code === 404 || e.code === 401) { @@ -76,12 +76,12 @@ module.exports = { } } } - }, + } }, jobs: [ { rule: '0 * * * *', - handler: 'updateSingleMirroredResources', - }, - ], + handler: 'updateSingleMirroredResources' + } + ] }; diff --git a/src/middleware/packages/ldp/services/resource/actions/delete.js b/src/middleware/packages/ldp/services/resource/actions/delete.js index c02fa627b..37f31d2f1 100644 --- a/src/middleware/packages/ldp/services/resource/actions/delete.js +++ b/src/middleware/packages/ldp/services/resource/actions/delete.js @@ -9,12 +9,12 @@ module.exports = { try { await ctx.call(controlledActions.delete || 'ldp.resource.delete', { - resourceUri, + resourceUri }); ctx.meta.$statusCode = 204; ctx.meta.$responseHeaders = { Link: '; rel="type"', - 'Content-Length': 0, + 'Content-Length': 0 }; } catch (e) { console.error(e); @@ -27,7 +27,7 @@ module.exports = { params: { resourceUri: 'string', webId: { type: 'string', optional: true }, - disassembly: { type: 'array', optional: true }, + disassembly: { type: 'array', optional: true } }, async handler(ctx) { const { resourceUri } = ctx.params; @@ -40,7 +40,7 @@ module.exports = { const { disassembly } = { ...(await ctx.call('ldp.registry.getByUri', { resourceUri })), - ...ctx.params, + ...ctx.params }; // Save the current data, to be able to send it through the event @@ -49,7 +49,7 @@ module.exports = { resourceUri, accept: MIME_TYPES.JSON, forceSemantic: true, - webId, + webId }); if (disassembly) { @@ -63,7 +63,7 @@ module.exports = { <${resourceUri}> ?p1 ?o1 . } `, - webId, + webId }); // We must detach the resource from the containers after deletion, otherwise the permissions may fail @@ -79,7 +79,7 @@ module.exports = { const returnValues = { resourceUri, oldData, - webId, + webId }; ctx.call('triplestore.deleteOrphanBlankNodes'); @@ -87,6 +87,6 @@ module.exports = { ctx.emit('ldp.resource.deleted', returnValues, { meta: { webId: null } }); return returnValues; - }, - }, + } + } }; diff --git a/src/middleware/packages/ldp/services/resource/actions/generateId.js b/src/middleware/packages/ldp/services/resource/actions/generateId.js index 86af76106..232e9b7df 100644 --- a/src/middleware/packages/ldp/services/resource/actions/generateId.js +++ b/src/middleware/packages/ldp/services/resource/actions/generateId.js @@ -6,7 +6,7 @@ module.exports = { visibility: 'public', params: { containerUri: 'string', - slug: { type: 'string', optional: true }, + slug: { type: 'string', optional: true } }, async handler(ctx) { let { containerUri, slug } = ctx.params; @@ -29,12 +29,12 @@ module.exports = { counter++; resourceAlreadyExists = await ctx.call('ldp.resource.exist', { resourceUri: preferredUri + counter, - webId: 'system', + webId: 'system' }); } while (resourceAlreadyExists); preferredUri += counter; } return preferredUri; - }, + } }; diff --git a/src/middleware/packages/ldp/services/resource/actions/getContainers.js b/src/middleware/packages/ldp/services/resource/actions/getContainers.js index 76fc621ad..67fb192d0 100644 --- a/src/middleware/packages/ldp/services/resource/actions/getContainers.js +++ b/src/middleware/packages/ldp/services/resource/actions/getContainers.js @@ -4,7 +4,7 @@ const { getContainerFromUri } = require('../../../utils'); module.exports = { visibility: 'public', params: { - resourceUri: 'string', + resourceUri: 'string' }, async handler(ctx) { const { resourceUri } = ctx.params; @@ -26,9 +26,9 @@ module.exports = { } `, accept: MIME_TYPES.JSON, - webId: 'system', + webId: 'system' }); - return result.map((node) => node.containerUri.value); - }, + return result.map(node => node.containerUri.value); + } }; diff --git a/src/middleware/packages/ldp/services/resource/actions/head.js b/src/middleware/packages/ldp/services/resource/actions/head.js index d36753c54..4c5defc3b 100644 --- a/src/middleware/packages/ldp/services/resource/actions/head.js +++ b/src/middleware/packages/ldp/services/resource/actions/head.js @@ -10,7 +10,7 @@ module.exports = { ctx.meta.$statusMessage = 'OK'; ctx.meta.$responseHeaders = { Link: `<${aclUri}>; rel="acl"`, - 'Content-Length': 0, + 'Content-Length': 0 }; - }, + } }; diff --git a/src/middleware/packages/ldp/services/resource/actions/patch.js b/src/middleware/packages/ldp/services/resource/actions/patch.js index 4b6423a23..4ba802d11 100644 --- a/src/middleware/packages/ldp/services/resource/actions/patch.js +++ b/src/middleware/packages/ldp/services/resource/actions/patch.js @@ -30,7 +30,7 @@ module.exports = { if (ctx.meta.parser === 'sparql') { await ctx.call(controlledActions.patch || 'ldp.resource.patch', { resourceUri, - sparqlUpdate: body, + sparqlUpdate: body }); } else { throw new MoleculerError(`The content-type should be application/sparql-update`, 400, 'BAD_REQUEST'); @@ -38,7 +38,7 @@ module.exports = { ctx.meta.$statusCode = 204; ctx.meta.$responseHeaders = { Link: '; rel="type"', - 'Content-Length': 0, + 'Content-Length': 0 }; } catch (e) { console.error(e); @@ -50,24 +50,24 @@ module.exports = { visibility: 'public', params: { resourceUri: { - type: 'string', + type: 'string' }, sparqlUpdate: { type: 'string', - optional: true, + optional: true }, triplesToAdd: { type: 'array', - optional: true, + optional: true }, triplesToRemove: { type: 'array', - optional: true, + optional: true }, webId: { type: 'string', - optional: true, - }, + optional: true + } }, async handler(ctx) { let { resourceUri, sparqlUpdate, triplesToAdd, triplesToRemove, webId } = ctx.params; @@ -93,15 +93,15 @@ module.exports = { const triplesByOperation = Object.fromEntries( parsedQuery.updates - .filter((p) => ACCEPTED_OPERATIONS.includes(p.updateType)) - .map((p) => [p.updateType, p[p.updateType][0].triples]), + .filter(p => ACCEPTED_OPERATIONS.includes(p.updateType)) + .map(p => [p.updateType, p[p.updateType][0].triples]) ); if (Object.values(triplesByOperation).length === 0) throw new MoleculerError( 'Invalid SPARQL operation. Must be INSERT DATA and/or DELETE DATA', 400, - 'BAD_REQUEST', + 'BAD_REQUEST' ); triplesToAdd = triplesByOperation.insert; @@ -114,14 +114,14 @@ module.exports = { // Rebuild the sparql update to reduce security risks sparqlUpdate = { type: 'update', - updates: [], + updates: [] }; if (triplesToAdd) { checkTriplesSubjectIsResource(triplesToAdd, resourceUri); sparqlUpdate.updates.push({ updateType: 'insert', - insert: [{ type: 'bgp', triples: triplesToAdd }], + insert: [{ type: 'bgp', triples: triplesToAdd }] }); } @@ -129,25 +129,25 @@ module.exports = { checkTriplesSubjectIsResource(triplesToRemove, resourceUri); sparqlUpdate.updates.push({ updateType: 'delete', - delete: [{ type: 'bgp', triples: triplesToRemove }], + delete: [{ type: 'bgp', triples: triplesToRemove }] }); } await ctx.call('triplestore.update', { query: sparqlUpdate, - webId, + webId }); const returnValues = { resourceUri, triplesAdded: triplesToAdd, triplesRemoved: triplesToRemove, - webId, + webId }; ctx.emit('ldp.resource.patched', returnValues, { meta: { webId: null } }); return returnValues; - }, - }, + } + } }; diff --git a/src/middleware/packages/ldp/services/resource/actions/put.js b/src/middleware/packages/ldp/services/resource/actions/put.js index 91a4fde7b..204ad1d65 100644 --- a/src/middleware/packages/ldp/services/resource/actions/put.js +++ b/src/middleware/packages/ldp/services/resource/actions/put.js @@ -10,7 +10,7 @@ module.exports = { resource['@id'] = urlJoin(containerUri, id); const { controlledActions } = await ctx.call('ldp.registry.getByUri', { - resourceUri: resource['@id'], + resourceUri: resource['@id'] }); if (ctx.meta.parser === 'file') { @@ -23,12 +23,12 @@ module.exports = { contentType: ctx.meta.headers['content-type'], containerUri, body, - slug: id, + slug: id }); ctx.meta.$statusCode = 204; ctx.meta.$responseHeaders = { Link: '; rel="type"', - 'Content-Length': 0, + 'Content-Length': 0 }; } catch (e) { console.error(e); @@ -40,23 +40,23 @@ module.exports = { visibility: 'public', params: { resource: { - type: 'object', + type: 'object' }, webId: { type: 'string', - optional: true, + optional: true }, body: { type: 'string', - optional: true, + optional: true }, contentType: { - type: 'string', + type: 'string' }, disassembly: { type: 'array', - optional: true, - }, + optional: true + } }, async handler(ctx) { let { resource, contentType, body } = ctx.params; @@ -71,9 +71,9 @@ module.exports = { const { disassembly, jsonContext } = { ...(await ctx.call('ldp.registry.getByUri', { - resourceUri, + resourceUri })), - ...ctx.params, + ...ctx.params }; // Save the current data, to be able to send it through the event @@ -81,14 +81,14 @@ module.exports = { const oldData = await ctx.call('ldp.resource.get', { resourceUri, accept: MIME_TYPES.JSON, - webId, + webId }); // Adds the default context, if it is missing if (contentType === MIME_TYPES.JSON && !resource['@context'] && jsonContext) { resource = { '@context': jsonContext, - ...resource, + ...resource }; } @@ -124,10 +124,10 @@ module.exports = { } else { // Keep track of blank nodes to use in WHERE clause const newBlankNodes = this.getTriplesDifference(newTriples, oldTriples).filter( - (triple) => triple.object.termType === 'Variable', + triple => triple.object.termType === 'Variable' ); const existingBlankNodes = oldTriples.filter( - (triple) => triple.object.termType === 'Variable' || triple.subject.termType === 'Variable', + triple => triple.object.termType === 'Variable' || triple.subject.termType === 'Variable' ); // Generate the query @@ -143,7 +143,7 @@ module.exports = { await ctx.call('triplestore.update', { query, - webId, + webId }); // Get the new data, with the same formatting as the old data @@ -153,13 +153,13 @@ module.exports = { { resourceUri, accept: MIME_TYPES.JSON, - webId, + webId }, { meta: { - $cache: false, - }, - }, + $cache: false + } + } ); ctx.emit( @@ -168,14 +168,14 @@ module.exports = { resourceUri, oldData, newData, - webId, + webId }, { meta: { webId: null, - dataset: null, - }, - }, + dataset: null + } + } ); } @@ -183,8 +183,8 @@ module.exports = { resourceUri, oldData, newData, - webId, + webId }; - }, - }, + } + } }; diff --git a/src/middleware/packages/ldp/services/resource/actions/upload.js b/src/middleware/packages/ldp/services/resource/actions/upload.js index 9f08d0e42..050e819b9 100644 --- a/src/middleware/packages/ldp/services/resource/actions/upload.js +++ b/src/middleware/packages/ldp/services/resource/actions/upload.js @@ -7,7 +7,7 @@ module.exports = { visibility: 'public', params: { resourceUri: 'string', - file: 'object', + file: 'object' }, async handler(ctx) { const { resourceUri, file } = ctx.params; @@ -34,7 +34,7 @@ module.exports = { encoding: file.encoding, mimeType: file.mimetype, localPath, - fileName, + fileName }; - }, + } }; diff --git a/src/middleware/packages/ldp/services/resource/methods.js b/src/middleware/packages/ldp/services/resource/methods.js index de235f1ed..9cf49bcc3 100644 --- a/src/middleware/packages/ldp/services/resource/methods.js +++ b/src/middleware/packages/ldp/services/resource/methods.js @@ -12,7 +12,10 @@ module.exports = { async streamToFile(inputStream, filePath) { return new Promise((resolve, reject) => { const fileWriteStream = fs.createWriteStream(filePath); - inputStream.pipe(fileWriteStream).on('finish', resolve).on('error', reject); + inputStream + .pipe(fileWriteStream) + .on('finish', resolve) + .on('error', reject); }); }, async bodyToTriples(body, contentType) { @@ -25,20 +28,18 @@ module.exports = { const res = []; rdfParser .parse(textStream, { contentType }) - .on('data', (quad) => res.push(quad)) - .on('error', (error) => reject(error)) + .on('data', quad => res.push(quad)) + .on('error', error => reject(error)) .on('end', () => resolve(res)); }); }, // Filter out triples whose subject is not the resource itself // We don't want to update or delete resources with IDs filterOtherNamedNodes(triples, resourceUri) { - return triples.filter( - (triple) => !(triple.subject.termType === 'NamedNode' && triple.subject.value !== resourceUri), - ); + return triples.filter(triple => !(triple.subject.termType === 'NamedNode' && triple.subject.value !== resourceUri)); }, convertBlankNodesToVars(triples, blankNodesVarsMap) { - return triples.map((triple) => { + return triples.map(triple => { if (triple.subject.termType === 'BlankNode') { triple.subject = variable(triple.subject.value); } @@ -50,7 +51,7 @@ module.exports = { }, // Exclude from triples1 the triples which also exist in triples2 getTriplesDifference(triples1, triples2) { - return triples1.filter((t1) => !triples2.some((t2) => t1.equals(t2))); + return triples1.filter(t1 => !triples2.some(t2 => t1.equals(t2))); }, nodeToString(node) { switch (node.termType) { @@ -71,7 +72,7 @@ module.exports = { } }, buildJsonVariable(identifier, triples) { - const blankVariables = triples.filter((t) => t.subject.value.localeCompare(identifier) === 0); + const blankVariables = triples.filter(t => t.subject.value.localeCompare(identifier) === 0); const json = {}; let allIdentifiers = [identifier]; for (const blankVariable of blankVariables) { @@ -86,10 +87,10 @@ module.exports = { return { json, allIdentifiers }; }, removeDuplicatedVariables(triples) { - const roots = triples.filter((n) => n.object.termType === 'Variable' && n.subject.termType !== 'Variable'); + const roots = triples.filter(n => n.object.termType === 'Variable' && n.subject.termType !== 'Variable'); const rootsIdentifiers = roots.reduce((previousValue, currentValue) => { const result = previousValue; - if (!result.find((i) => i.localeCompare(currentValue.object.value) === 0)) { + if (!result.find(i => i.localeCompare(currentValue.object.value) === 0)) { result.push(currentValue.object.value); } return result; @@ -100,34 +101,34 @@ module.exports = { rootsJson.push({ rootIdentifier, stringified: JSON.stringify(jsonVariable.json), - allIdentifiers: jsonVariable.allIdentifiers, + allIdentifiers: jsonVariable.allIdentifiers }); } const keepVariables = []; const duplicatedVariables = []; for (var rootJson of rootsJson) { - if (keepVariables.find((kp) => kp.stringified.localeCompare(rootJson.stringified) === 0)) { + if (keepVariables.find(kp => kp.stringified.localeCompare(rootJson.stringified) === 0)) { duplicatedVariables.push(rootJson); } else { keepVariables.push(rootJson); } } - const allRemovedIdentifiers = duplicatedVariables.map((dv) => dv.allIdentifiers).flat(); + const allRemovedIdentifiers = duplicatedVariables.map(dv => dv.allIdentifiers).flat(); const removedDuplicatedVariables = triples.filter( - (t) => !allRemovedIdentifiers.includes(t.object.value) && !allRemovedIdentifiers.includes(t.subject.value), + t => !allRemovedIdentifiers.includes(t.object.value) && !allRemovedIdentifiers.includes(t.subject.value) ); return removedDuplicatedVariables; }, triplesToString(triples) { return triples .map( - (triple) => - `${this.nodeToString(triple.subject)} <${triple.predicate.value}> ${this.nodeToString(triple.object)} .`, + triple => + `${this.nodeToString(triple.subject)} <${triple.predicate.value}> ${this.nodeToString(triple.object)} .` ) .join('\n'); }, bindNewBlankNodes(triples) { - return triples.map((triple) => `BIND (BNODE() AS ?${triple.object.value}) .`).join('\n'); + return triples.map(triple => `BIND (BNODE() AS ?${triple.object.value}) .`).join('\n'); }, async createDisassembly(ctx, disassembly, newData) { for (const disassemblyConfig of disassembly) { @@ -143,10 +144,10 @@ module.exports = { containerUri: disassemblyConfig.container, resource: { '@context': newData['@context'], - ...resourceWithoutId, + ...resourceWithoutId }, contentType: MIME_TYPES.JSON, - webId: 'system', + webId: 'system' }); uriAdded.push({ '@id': newResourceUri, '@type': '@id' }); } @@ -164,13 +165,13 @@ module.exports = { const newDisassemblyValue = defaultToArray(newData[disassemblyConfig.path]) || []; const resourcesToAdd = newDisassemblyValue.filter( - (t1) => !oldDisassemblyValue.some((t2) => (t1.id || t1['@id']) === (t2.id || t2['@id'])), + t1 => !oldDisassemblyValue.some(t2 => (t1.id || t1['@id']) === (t2.id || t2['@id'])) ); const resourcesToRemove = oldDisassemblyValue.filter( - (t1) => !newDisassemblyValue.some((t2) => (t1.id || t1['@id']) === (t2.id || t2['@id'])), + t1 => !newDisassemblyValue.some(t2 => (t1.id || t1['@id']) === (t2.id || t2['@id'])) ); - const resourcesToKeep = oldDisassemblyValue.filter((t1) => - newDisassemblyValue.some((t2) => (t1.id || t1['@id']) === (t2.id || t2['@id'])), + const resourcesToKeep = oldDisassemblyValue.filter(t1 => + newDisassemblyValue.some(t2 => (t1.id || t1['@id']) === (t2.id || t2['@id'])) ); if (resourcesToAdd) { @@ -181,10 +182,10 @@ module.exports = { containerUri: disassemblyConfig.container, resource: { '@context': newData['@context'], - ...resource, + ...resource }, contentType: MIME_TYPES.JSON, - webId: 'system', + webId: 'system' }); uriAdded.push({ '@id': newResourceUri, '@type': '@id' }); } @@ -195,17 +196,17 @@ module.exports = { for (const resource of resourcesToRemove) { await ctx.call('ldp.resource.delete', { resourceUri: resource['@id'] || resource.id || resource, - webId: 'system', + webId: 'system' }); uriRemoved.push({ '@id': resource['@id'] || resource.id || resource, '@type': '@id' }); } } if (resourcesToKeep) { - uriKept = resourcesToKeep.map((r) => ({ '@id': r['@id'] || r.id || r, '@type': '@id' })); + uriKept = resourcesToKeep.map(r => ({ '@id': r['@id'] || r.id || r, '@type': '@id' })); } } else if (method === 'PATCH') { - uriKept = oldDisassemblyValue.map((r) => ({ '@id': r['@id'] || r.id || r, '@type': '@id' })); + uriKept = oldDisassemblyValue.map(r => ({ '@id': r['@id'] || r.id || r, '@type': '@id' })); } else { throw new Error(`Unknown method ${method}`); } @@ -224,7 +225,7 @@ module.exports = { for (const resource of disassemblyValue) { await ctx.call('ldp.resource.delete', { resourceUri: resource['@id'] || resource.id || resource, - webId: 'system', + webId: 'system' }); } } @@ -237,5 +238,5 @@ module.exports = { !urlJoin(uri, '/').startsWith(this.settings.baseUrl) || (this.settings.podProvider && !urlJoin(uri, '/').startsWith(`${urlJoin(this.settings.baseUrl, dataset)}/`)) ); - }, + } }; diff --git a/src/middleware/packages/ldp/utils.js b/src/middleware/packages/ldp/utils.js index 3cb0da1ec..53ab0ef4c 100644 --- a/src/middleware/packages/ldp/utils.js +++ b/src/middleware/packages/ldp/utils.js @@ -12,7 +12,11 @@ const regexProtocolAndHostAndPort = new RegExp('^http(s)?:\\/\\/([\\w-\\.:]*)'); function createFragmentURL(baseUrl, serverUrl) { let fragment = 'me'; const res = serverUrl.match(regexProtocolAndHostAndPort); - if (res) fragment = res[2].replace('-', '_').replace('.', '_').replace(':', '_'); + if (res) + fragment = res[2] + .replace('-', '_') + .replace('.', '_') + .replace(':', '_'); return urlJoin(baseUrl, `#${fragment}`); } @@ -22,7 +26,7 @@ const isMirror = (resourceUri, baseUrl) => { }; // Transform ['ont:predicate1/ont:predicate2'] to ['ont:predicate1', 'ont:predicate1/ont:predicate2'] -const extractNodes = (predicates) => { +const extractNodes = predicates => { const nodes = []; if (predicates) { for (const predicate of predicates) { @@ -39,27 +43,31 @@ const extractNodes = (predicates) => { return nodes; }; -const generateSparqlVarName = (node) => crypto.createHash('md5').update(node).digest('hex'); +const generateSparqlVarName = node => + crypto + .createHash('md5') + .update(node) + .digest('hex'); -const getParentNode = (node) => node.includes('/') && node.split('/')[0]; +const getParentNode = node => node.includes('/') && node.split('/')[0]; -const getPredicate = (node) => (node.includes('/') ? node.split('/')[1] : node); +const getPredicate = node => (node.includes('/') ? node.split('/')[1] : node); const buildOptionalQuery = (queries, parentNode = false) => queries - .filter((q) => q.parentNode === parentNode) + .filter(q => q.parentNode === parentNode) .map( - (q) => ` + q => ` OPTIONAL { ${q.query} ${q.filter} ${buildOptionalQuery(queries, q.node)} } - `, + ` ) .join('\n'); -const buildDereferenceQuery = (predicates) => { +const buildDereferenceQuery = predicates => { const queries = []; const nodes = extractNodes(predicates); @@ -74,30 +82,30 @@ const buildDereferenceQuery = (predicates) => { node, parentNode, query: `?s${parentVarName} ${predicate} ?s${varName} .\n?s${varName} ?p${varName} ?o${varName} .`, - filter: `FILTER(isBLANK(?s${varName})) .`, + filter: `FILTER(isBLANK(?s${varName})) .` }); } return { - construct: queries.map((q) => q.query).join('\n'), - where: buildOptionalQuery(queries), + construct: queries.map(q => q.query).join('\n'), + where: buildOptionalQuery(queries) }; } return { construct: '', - where: '', + where: '' }; }; -const buildFiltersQuery = (filters) => { +const buildFiltersQuery = filters => { let where = ''; if (filters) { Object.keys(filters).forEach((predicate, i) => { if (filters[predicate]) { where += ` FILTER EXISTS { ?s1 ${predicate.startsWith('http') ? `<${predicate}>` : predicate} ${ - filters[predicate].startsWith('http') ? `<${filters[predicate]}>` : `"${filters[predicate]}"` - } } . + filters[predicate].startsWith('http') ? `<${filters[predicate]}>` : `"${filters[predicate]}"` + } } . `; } else { where += ` @@ -109,20 +117,20 @@ const buildFiltersQuery = (filters) => { return { where }; }; -const getPrefixRdf = (ontologies) => { - return ontologies.map((ontology) => `PREFIX ${ontology.prefix}: <${ontology.url}>`).join('\n'); +const getPrefixRdf = ontologies => { + return ontologies.map(ontology => `PREFIX ${ontology.prefix}: <${ontology.url}>`).join('\n'); }; -const getPrefixJSON = (ontologies) => { +const getPrefixJSON = ontologies => { const pattern = {}; - ontologies.forEach((ontology) => (pattern[ontology.prefix] = ontology.url)); + ontologies.forEach(ontology => (pattern[ontology.prefix] = ontology.url)); return pattern; }; // Replace a full URI with a prefix const usePrefix = (uri, ontologies) => { if (!uri.startsWith('http')) return uri; // If it is already prefixed - const ontology = ontologies.find((o) => uri.startsWith(o.url)); + const ontology = ontologies.find(o => uri.startsWith(o.url)); return uri.replace(ontology.url, `${ontology.prefix}:`); }; @@ -130,16 +138,16 @@ const usePrefix = (uri, ontologies) => { const useFullURI = (prefixedUri, ontologies) => { if (prefixedUri.startsWith('http')) return prefixedUri; // If it is already a full URI const [prefix] = prefixedUri.split(':'); - const ontology = ontologies.find((o) => o.prefix === prefix); + const ontology = ontologies.find(o => o.prefix === prefix); return prefixedUri.replace(`${ontology.prefix}:`, ontology.url); }; -const getSlugFromUri = (uri) => uri.match(new RegExp(`.*/(.*)`))[1]; +const getSlugFromUri = uri => uri.match(new RegExp(`.*/(.*)`))[1]; -const getContainerFromUri = (uri) => uri.match(new RegExp(`(.*)/.*`))[1]; +const getContainerFromUri = uri => uri.match(new RegExp(`(.*)/.*`))[1]; // Transforms "http://localhost:3000/dataset/data" to "dataset" -const getDatasetFromUri = (uri) => { +const getDatasetFromUri = uri => { const path = new URL(uri).pathname; const parts = path.split('/'); if (parts.length > 1) return parts[1]; @@ -150,11 +158,11 @@ const hasType = (resource, type) => { return Array.isArray(resourceType) ? resourceType.includes(type) : resourceType === type; }; -const isContainer = (resource) => hasType(resource, 'ldp:Container'); +const isContainer = resource => hasType(resource, 'ldp:Container'); -const defaultToArray = (value) => (!value ? undefined : Array.isArray(value) ? value : [value]); +const defaultToArray = value => (!value ? undefined : Array.isArray(value) ? value : [value]); -const delay = (t) => new Promise((resolve) => setTimeout(resolve, t)); +const delay = t => new Promise(resolve => setTimeout(resolve, t)); module.exports = { buildDereferenceQuery, @@ -174,5 +182,5 @@ module.exports = { isMirror, createFragmentURL, regexPrefix, - regexProtocolAndHostAndPort, + regexProtocolAndHostAndPort }; diff --git a/src/middleware/packages/middlewares/index.js b/src/middleware/packages/middlewares/index.js index 2236a1498..55518d65b 100644 --- a/src/middleware/packages/middlewares/index.js +++ b/src/middleware/packages/middlewares/index.js @@ -19,18 +19,18 @@ const negotiateContentType = (req, res, next) => { } } else if (req.$params.body) { next( - new MoleculerError('Content-Type has to be specified for a non-empty body ', 400, 'CONTENT_TYPE_NOT_SPECIFIED'), + new MoleculerError('Content-Type has to be specified for a non-empty body ', 400, 'CONTENT_TYPE_NOT_SPECIFIED') ); } else { next(); } }; -const throw403 = (msg) => { +const throw403 = msg => { throw new MoleculerError('Forbidden', 403, 'ACCESS_DENIED', { status: 'Forbidden', text: msg }); }; -const throw500 = (msg) => { +const throw500 = msg => { throw new MoleculerError(msg, 500, 'INTERNAL_SERVER_ERROR', { status: 'Server Error', text: msg }); }; @@ -53,10 +53,10 @@ const negotiateAccept = (req, res, next) => { } }; -const getRawBody = (req) => { +const getRawBody = req => { return new Promise((resolve, reject) => { let data = ''; - req.on('data', (chunk) => { + req.on('data', chunk => { data += chunk; }); req.on('end', () => { @@ -121,13 +121,13 @@ const parseFile = (req, res, next) => { const files = []; busboy.on('file', (fieldname, file, filename, encoding, mimetype) => { const readableStream = new streams.ReadableStream(); - file.on('data', (data) => readableStream.push(data)); + file.on('data', data => readableStream.push(data)); files.push({ fieldname, readableStream, filename, encoding, - mimetype, + mimetype }); }); busboy.on('field', (fieldname, val) => { @@ -143,8 +143,8 @@ const parseFile = (req, res, next) => { req.$params.files = [ { readableStream: req, - mimetype: req.headers['content-type'], - }, + mimetype: req.headers['content-type'] + } ]; req.$ctx.meta.parser = 'file'; next(); @@ -154,7 +154,7 @@ const parseFile = (req, res, next) => { } }; -const addContainerUriMiddleware = (containerUri) => (req, res, next) => { +const addContainerUriMiddleware = containerUri => (req, res, next) => { if (containerUri.includes('/:username')) { req.$params.containerUri = containerUri.replace(':username', req.$params.username).replace(/\/$/, ''); } else { @@ -179,5 +179,5 @@ module.exports = { addContainerUriMiddleware, saveDatasetMeta, throw403, - throw500, + throw500 }; diff --git a/src/middleware/packages/migration/service.js b/src/middleware/packages/migration/service.js index 643a7e03f..5c6e79180 100644 --- a/src/middleware/packages/migration/service.js +++ b/src/middleware/packages/migration/service.js @@ -4,7 +4,7 @@ const { getContainerFromUri } = require('@semapps/ldp'); module.exports = { name: 'migration', settings: { - baseUrl: undefined, + baseUrl: undefined }, created() { if (!this.settings.baseUrl) { @@ -29,7 +29,7 @@ module.exports = { WHERE { ?s <${oldPredicate}> ?o . } `, dataset, - webId: 'system', + webId: 'system' }); }, async moveResource(ctx) { @@ -44,7 +44,7 @@ module.exports = { WHERE { <${oldResourceUri}> ?p ?o } `, dataset, - webId: 'system', + webId: 'system' }); await ctx.call('triplestore.update', { @@ -54,7 +54,7 @@ module.exports = { WHERE { ?s ?p <${oldResourceUri}> } `, dataset, - webId: 'system', + webId: 'system' }); await ctx.call('triplestore.update', { @@ -65,7 +65,7 @@ module.exports = { WHERE { ?s ?p <${oldResourceUri}> } `, dataset, - webId: 'system', + webId: 'system' }); const oldContainerUri = getContainerFromUri(oldResourceUri); @@ -79,7 +79,7 @@ module.exports = { WHERE { <${oldContainerUri}> ldp:contains <${newResourceUri}> } `, dataset, - webId: 'system', + webId: 'system' }); await this.actions.moveAclRights({ newResourceUri, oldResourceUri, dataset }, { parentCtx: ctx }); @@ -97,7 +97,7 @@ module.exports = { WHERE { <${oldGroupUri}> ?p ?o } `, dataset, - webId: 'system', + webId: 'system' }); await ctx.call('triplestore.update', { @@ -108,12 +108,12 @@ module.exports = { WHERE { ?s ?p <${oldGroupUri}> } `, dataset, - webId: 'system', + webId: 'system' }); await this.actions.moveAclRights( { newResourceUri: newGroupUri, oldResourceUri: oldGroupUri, dataset }, - { parentCtx: ctx }, + { parentCtx: ctx } ); }, async moveAclRights(ctx) { @@ -133,7 +133,7 @@ module.exports = { WHERE { <${oldResourceAclUri}> ?p ?o } `, dataset, - webId: 'system', + webId: 'system' }); } }, @@ -148,7 +148,7 @@ module.exports = { WHERE { ?groupUri <${userUri}> } `, dataset, - webId: 'system', + webId: 'system' }); // Remove all authorization given specifically to this user @@ -159,8 +159,8 @@ module.exports = { WHERE { ?authorizationUri <${userUri}> } `, dataset, - webId: 'system', + webId: 'system' }); - }, - }, + } + } }; diff --git a/src/middleware/packages/mime-types/index.js b/src/middleware/packages/mime-types/index.js index dc16ef697..6442e3b18 100644 --- a/src/middleware/packages/mime-types/index.js +++ b/src/middleware/packages/mime-types/index.js @@ -2,33 +2,33 @@ const Negotiator = require('negotiator'); const { MoleculerError } = require('moleculer').Errors; const { MIME_TYPES, TYPES_REPO } = require('./constants'); -const negotiateType = function (incomingType) { +const negotiateType = function(incomingType) { const availableMediaTypes = []; const negotiatorType = incomingType; - TYPES_REPO.forEach((trSupported) => { - trSupported.mimeFull.forEach((tr) => availableMediaTypes.push(tr)); + TYPES_REPO.forEach(trSupported => { + trSupported.mimeFull.forEach(tr => availableMediaTypes.push(tr)); }); const negotiator = new Negotiator({ headers: { - accept: negotiatorType, - }, + accept: negotiatorType + } }); const rawNegotiatedAccept = negotiator.mediaType(availableMediaTypes); if (rawNegotiatedAccept !== undefined) { - return TYPES_REPO.filter((tr) => tr.mimeFull.includes(rawNegotiatedAccept))[0]; + return TYPES_REPO.filter(tr => tr.mimeFull.includes(rawNegotiatedAccept))[0]; } throw new MoleculerError(`Type not supported : ${incomingType}`, 400, 'TYPE_NOT_SUPPORTED'); }; -const negotiateTypeMime = function (incomingType) { +const negotiateTypeMime = function(incomingType) { return negotiateType(incomingType).mime; }; -const negotiateTypeN3 = function (incomingType) { +const negotiateTypeN3 = function(incomingType) { return negotiateType(incomingType).N3Mapping; }; -const negotiateTypeFuseki = function (incomingType) { +const negotiateTypeFuseki = function(incomingType) { return negotiateType(incomingType).fusekiMapping; }; @@ -37,5 +37,5 @@ module.exports = { negotiateType, negotiateTypeMime, negotiateTypeN3, - negotiateTypeFuseki, + negotiateTypeFuseki }; diff --git a/src/middleware/packages/notifications/services/digest/service.js b/src/middleware/packages/notifications/services/digest/service.js index 8dc65dcd3..a0d53d40c 100644 --- a/src/middleware/packages/notifications/services/digest/service.js +++ b/src/middleware/packages/notifications/services/digest/service.js @@ -18,12 +18,12 @@ const DigestNotificationsService = { from: null, transport: null, // Data available in all templates - data: {}, + data: {} }, dependencies: ['digest.subscription'], created() { this.broker.createService(DigestSubscriptionService, { - adapter: new TripleStoreAdapter({ type: 'DigestSubscription', dataset: this.settings.subscriptionsDataset }), + adapter: new TripleStoreAdapter({ type: 'DigestSubscription', dataset: this.settings.subscriptionsDataset }) }); }, async started() { @@ -45,7 +45,7 @@ const DigestNotificationsService = { const interval = cronParser.parseExpression(this.settings.frequencies[frequency], { currentDate, - tz: this.settings.timeZone, + tz: this.settings.timeZone }); const previousDate = new Date(interval.prev().toISOString()); @@ -59,7 +59,7 @@ const DigestNotificationsService = { const newActivities = await ctx.call('activitypub.inbox.getByDates', { collectionUri: subscriber.inbox, fromDate: previousDate, - toDate: currentDate, + toDate: currentDate }); if (newActivities.length > 0) { @@ -70,7 +70,7 @@ const DigestNotificationsService = { for (const activity of newActivities) { const notification = await ctx.call('activity-mapping.map', { activity, - locale: subscription.locale || account.locale, + locale: subscription.locale || account.locale }); if (notification && (await this.filterNotification(notification, subscription, notifications))) { notifications.push(notification); @@ -78,7 +78,7 @@ const DigestNotificationsService = { if (!notificationsByCategories[notification.category]) notificationsByCategories[notification.category] = { category: notification.category, - notifications: [], + notifications: [] }; notificationsByCategories[notification.category].notifications.push(notification); } @@ -97,12 +97,12 @@ const DigestNotificationsService = { notificationsByCategories, subscription, subscriber, - account, - }, + account + } }, { - parentCtx: ctx, - }, + parentCtx: ctx + } ); success.push({ @@ -110,28 +110,28 @@ const DigestNotificationsService = { locale: subscription.locale || account.locale, numNotifications: notifications.length, categories: Object.keys(notificationsByCategories), - notificationsIds: notifications.map((n) => n.id), - subscription, + notificationsIds: notifications.map(n => n.id), + subscription }); } } } catch (e) { failures.push({ error: e.message, - subscription, + subscription }); } } return { failures, success }; - }, + } }, methods: { // Optional method called for each notification // Return true if you want the notification to be included in the digest async filterNotification(notification, subscription) { return true; - }, + } }, queues: { build: [ @@ -139,10 +139,10 @@ const DigestNotificationsService = { name: '*', process(job) { return this.actions.build({ frequency: job.name, timestamp: job.opts.prevMillis }); - }, - }, - ], - }, + } + } + ] + } }; module.exports = DigestNotificationsService; diff --git a/src/middleware/packages/notifications/services/expo-push/device.js b/src/middleware/packages/notifications/services/expo-push/device.js index 85beab3fe..b27d3e6cd 100644 --- a/src/middleware/packages/notifications/services/expo-push/device.js +++ b/src/middleware/packages/notifications/services/expo-push/device.js @@ -9,8 +9,8 @@ const ExpoPushDeviceService = { idField: '@id', newDeviceNotification: { message: null, - data: {}, - }, + data: {} + } }, actions: { async subscribe(ctx) { @@ -20,10 +20,10 @@ const ExpoPushDeviceService = { { query: { ownedBy: userUri, - pushToken: pushToken, - }, + pushToken: pushToken + } }, - { parentCtx: ctx }, + { parentCtx: ctx } ); if (!device['ldp:contains']) { @@ -33,15 +33,15 @@ const ExpoPushDeviceService = { yearClass: yearClass, ownedBy: userUri, pushToken: pushToken, - addedAt: new Date().toISOString(), + addedAt: new Date().toISOString() }, - { parentCtx: ctx }, + { parentCtx: ctx } ); if (this.settings.newDeviceNotification && this.settings.newDeviceNotification.message) { await ctx.call('push.notification.send', { to: userUri, - ...this.settings.newDeviceNotification, + ...this.settings.newDeviceNotification }); } } else { @@ -51,9 +51,9 @@ const ExpoPushDeviceService = { '@id': device['ldp:contains'][0]['@id'], name: name, yearClass: yearClass, - errorMessage: null, + errorMessage: null }, - { parentCtx: ctx }, + { parentCtx: ctx } ); } @@ -67,10 +67,10 @@ const ExpoPushDeviceService = { { query: { ownedBy: userUri, - errorMessage: null, - }, + errorMessage: null + } }, - { parentCtx: ctx }, + { parentCtx: ctx } ); if (container['ldp:contains']) { @@ -79,8 +79,8 @@ const ExpoPushDeviceService = { } return devices; - }, - }, + } + } }; module.exports = ExpoPushDeviceService; diff --git a/src/middleware/packages/notifications/services/expo-push/notification.js b/src/middleware/packages/notifications/services/expo-push/notification.js index 980d20862..4b87f40dc 100644 --- a/src/middleware/packages/notifications/services/expo-push/notification.js +++ b/src/middleware/packages/notifications/services/expo-push/notification.js @@ -7,7 +7,7 @@ const ExpoPushNotificationService = { mixins: [DbService], adapter: new TripleStoreAdapter({ type: 'PushNotification', dataset: 'settings' }), settings: { - idField: '@id', + idField: '@id' }, started() { this.expo = new Expo(); @@ -25,7 +25,7 @@ const ExpoPushNotificationService = { const { to, message, data } = ctx.params; const devices = await ctx.call('push.device.findUsersDevices', { - users: Array.isArray(to) ? to : [to], + users: Array.isArray(to) ? to : [to] }); for (const device of devices) { @@ -37,10 +37,10 @@ const ExpoPushNotificationService = { message: JSON.stringify({ to: device.pushToken, body: message, - data, - }), + data + }) }, - { parentCtx: ctx }, + { parentCtx: ctx } ); } }, @@ -62,9 +62,9 @@ const ExpoPushNotificationService = { { '@id': notification['@id'], status: 'processed', - receiptId: receipt[0].id, + receiptId: receipt[0].id }, - { parentCtx: ctx }, + { parentCtx: ctx } ); } else { // NOTE: If a ticket contains an error code in ticket.details.error, you @@ -81,7 +81,7 @@ const ExpoPushNotificationService = { if (notifications) { const receiptIdChunks = this.expo.chunkPushNotificationReceiptIds( - notifications.map((notification) => notification['semapps:receiptId']), + notifications.map(notification => notification['semapps:receiptId']) ); // Like sending notifications, there are different strategies you could use @@ -94,16 +94,16 @@ const ExpoPushNotificationService = { // notification and information about an error, if one occurred. for (const receiptId in receipts) { let { status, message, details } = receipts[receiptId]; - const notificationId = notifications.find((notification) => notification.receiptId === receiptId)['@id']; + const notificationId = notifications.find(notification => notification.receiptId === receiptId)['@id']; if (status === 'ok') { await this.actions.update( { '@id': notificationId, status: 'checked', - receiptStatus: status, + receiptStatus: status }, - { parentCtx: ctx }, + { parentCtx: ctx } ); } else if (status === 'error') { // Append the error code to the message for easier debug @@ -121,15 +121,15 @@ const ExpoPushNotificationService = { } } } - }, + } }, methods: { async findByStatus(status, ctx) { const collection = await this.actions.find( { - query: { status }, + query: { status } }, - { parentCtx: ctx }, + { parentCtx: ctx } ); return collection['ldp:contains'] || []; }, @@ -138,18 +138,18 @@ const ExpoPushNotificationService = { { '@id': notificationId, status: 'error', - errorMessage: message, + errorMessage: message }, - { parentCtx: ctx }, + { parentCtx: ctx } ); // Also mark device as error await ctx.call('push.device.update', { '@id': notification.deviceId, - errorMessage: message, + errorMessage: message }); - }, - }, + } + } }; module.exports = ExpoPushNotificationService; diff --git a/src/middleware/packages/notifications/services/single-mail/service.js b/src/middleware/packages/notifications/services/single-mail/service.js index c0c280a51..0b947d4c3 100644 --- a/src/middleware/packages/notifications/services/single-mail/service.js +++ b/src/middleware/packages/notifications/services/single-mail/service.js @@ -3,7 +3,7 @@ const path = require('path'); const MailService = require('moleculer-mail'); const { getSlugFromUri } = require('@semapps/ldp'); -const delay = (t) => new Promise((resolve) => setTimeout(resolve, t)); +const delay = t => new Promise(resolve => setTimeout(resolve, t)); const SingleMailNotificationsService = { name: 'notifications.single-mail', @@ -17,7 +17,7 @@ const SingleMailNotificationsService = { templateFolder: path.join(__dirname, '../../templates'), from: null, transport: null, - data: {}, + data: {} }, events: { async 'activitypub.inbox.received'(ctx) { @@ -48,12 +48,12 @@ const SingleMailNotificationsService = { color: this.settings.color, descriptionWithBr: notification.description ? notification.description.replace(/\r\n|\r|\n/g, '
') - : undefined, - }, + : undefined + } }); } } - }, + } }, methods: { // Optional method called for each notification @@ -75,7 +75,7 @@ const SingleMailNotificationsService = { return this.createJob('sendMail', key, payload); } await this.actions.send(payload, { parentCtx: ctx }); - }, + } }, queues: { sendMail: { @@ -85,9 +85,9 @@ const SingleMailNotificationsService = { const result = await this.actions.send(job.data); job.progress(100); return result; - }, - }, - }, + } + } + } }; module.exports = SingleMailNotificationsService; diff --git a/src/middleware/packages/signature/service.js b/src/middleware/packages/signature/service.js index 6220e6945..7d7e21e53 100644 --- a/src/middleware/packages/signature/service.js +++ b/src/middleware/packages/signature/service.js @@ -7,15 +7,15 @@ const KeypairService = require('./services/keypair'); const SignatureService = { name: 'signature', settings: { - actorsKeyPairsDir: null, + actorsKeyPairsDir: null }, created() { const { actorsKeyPairsDir } = this.settings; this.broker.createService(KeypairService, { settings: { - actorsKeyPairsDir, - }, + actorsKeyPairsDir + } }); }, actions: { @@ -43,7 +43,7 @@ const SignatureService = { includeHeaders, keyId: actorUri, signature: signatureHash, - algorithm: 'rsa-sha256', + algorithm: 'rsa-sha256' }).substr('Signature '.length); return headers; @@ -64,7 +64,7 @@ const SignatureService = { const parsedSignature = parseRequest({ url: path || url.replace(new URL(url).origin, ''), // URL without domain name method, - headers, + headers }); const { keyId } = parsedSignature.params; @@ -83,7 +83,7 @@ const SignatureService = { if (req.headers.signature) { const { isValid, actorUri } = await this.actions.verifyHttpSignature( { path: req.originalUrl, method: req.method, headers: req.headers }, - { parentCtx: ctx }, + { parentCtx: ctx } ); if (isValid) { ctx.meta.webId = actorUri; @@ -101,7 +101,7 @@ const SignatureService = { if (req.headers.signature) { const { isValid, actorUri } = await this.actions.verifyHttpSignature( { path: req.originalUrl, method: req.method, headers: req.headers }, - { parentCtx: ctx }, + { parentCtx: ctx } ); if (isValid) { ctx.meta.webId = actorUri; @@ -112,13 +112,15 @@ const SignatureService = { } ctx.meta.webId = 'anon'; return Promise.reject(new E.UnAuthorizedError(E.ERR_NO_TOKEN)); - }, + } }, methods: { buildDigest(body) { - return `SHA-256=${createHash('sha256').update(body).digest('base64')}`; - }, - }, + return `SHA-256=${createHash('sha256') + .update(body) + .digest('base64')}`; + } + } }; module.exports = SignatureService; diff --git a/src/middleware/packages/signature/services/keypair.js b/src/middleware/packages/signature/services/keypair.js index cd9006f81..3094b6cf6 100644 --- a/src/middleware/packages/signature/services/keypair.js +++ b/src/middleware/packages/signature/services/keypair.js @@ -8,7 +8,7 @@ const { MIME_TYPES } = require('@semapps/mime-types'); const SignatureService = { name: 'signature.keypair', settings: { - actorsKeyPairsDir: null, + actorsKeyPairsDir: null }, created() { this.remoteActorPublicKeyCache = {}; @@ -37,22 +37,22 @@ const SignatureService = { modulusLength: 4096, publicKeyEncoding: { type: 'spki', - format: 'pem', + format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', - format: 'pem', - }, + format: 'pem' + } }, (err, publicKey, privateKey) => { if (!err) { - fs.writeFile(privateKeyPath, privateKey, (err) => reject(err)); - fs.writeFile(publicKeyPath, publicKey, (err) => reject(err)); + fs.writeFile(privateKeyPath, privateKey, err => reject(err)); + fs.writeFile(publicKeyPath, publicKey, err => reject(err)); resolve(publicKey); } else { reject(err); } - }, + } ); }); }, @@ -73,7 +73,7 @@ const SignatureService = { const actor = await ctx.call('ldp.resource.get', { resourceUri: actorUri, accept: MIME_TYPES.JSON, - webId: actorUri, + webId: actorUri }); // Ensure a public key is not already attached @@ -85,9 +85,9 @@ const SignatureService = { triplesToAdd: [ triple(namedNode(actorUri), namedNode('https://w3id.org/security#publicKey'), blankNode('b0')), triple(blankNode('b0'), namedNode('https://w3id.org/security#owner'), namedNode(actorUri)), - triple(blankNode('b0'), namedNode('https://w3id.org/security#publicKeyPem'), literal(publicKey)), + triple(blankNode('b0'), namedNode('https://w3id.org/security#publicKeyPem'), literal(publicKey)) ], - webId: 'system', + webId: 'system' }); } }, @@ -129,15 +129,15 @@ const SignatureService = { this.remoteActorPublicKeyCache[actorUri] = actor.publicKey.publicKeyPem; return actor.publicKey.publicKeyPem; - }, + } }, events: { async 'auth.registered'(ctx) { const { webId } = ctx.params; await this.actions.generate({ actorUri: webId }, { parentCtx: ctx }); await this.actions.attachPublicKey({ actorUri: webId }, { parentCtx: ctx }); - }, - }, + } + } }; module.exports = SignatureService; diff --git a/src/middleware/packages/signature/services/proxy.js b/src/middleware/packages/signature/services/proxy.js index 37197a9dd..827c4665f 100644 --- a/src/middleware/packages/signature/services/proxy.js +++ b/src/middleware/packages/signature/services/proxy.js @@ -4,19 +4,19 @@ const { parseFile, saveDatasetMeta } = require('@semapps/middlewares'); const fetch = require('node-fetch'); const { Errors: E } = require('moleculer-web'); -const stream2buffer = (stream) => { +const stream2buffer = stream => { return new Promise((resolve, reject) => { const _buf = []; - stream.on('data', (chunk) => _buf.push(chunk)); + stream.on('data', chunk => _buf.push(chunk)); stream.on('end', () => resolve(Buffer.concat(_buf))); - stream.on('error', (err) => reject(err)); + stream.on('error', err => reject(err)); }); }; const ProxyService = { name: 'signature.proxy', settings: { - podProvider: false, + podProvider: false }, dependencies: ['api'], async started() { @@ -25,8 +25,8 @@ const ProxyService = { authorization: true, authentication: false, aliases: { - 'POST /': [parseFile, saveDatasetMeta, 'signature.proxy.api_query'], // parseFile handles multipart/form-data - }, + 'POST /': [parseFile, saveDatasetMeta, 'signature.proxy.api_query'] // parseFile handles multipart/form-data + } }; if (this.settings.podProvider) { @@ -62,11 +62,11 @@ const ProxyService = { method, headers, body, - actorUri, + actorUri }, { - parentCtx: ctx, - }, + parentCtx: ctx + } ); ctx.meta.$statusCode = response.status; ctx.meta.$statusMessage = response.statusText; @@ -85,7 +85,7 @@ const ProxyService = { url, method, body, - actorUri, + actorUri }); // Convert Headers object if necessary (otherwise we can't destructure it below) @@ -97,9 +97,9 @@ const ProxyService = { method, headers: { ...headers, - ...signatureHeaders, + ...signatureHeaders }, - body, + body }); if (response.ok) { @@ -118,28 +118,28 @@ const ProxyService = { body, headers: Object.fromEntries(response.headers.entries()), status: response.status, - statusText: response.statusText, + statusText: response.statusText }; } this.logger.warn(`Could not fetch ${url} through proxy of ${actorUri}`); throw new MoleculerError(response.statusText, response.status); - }, + } }, events: { async 'auth.registered'(ctx) { const { webId } = ctx.params; if (this.settings.podProvider) { const services = await ctx.call('$node.services'); - if (services.filter((s) => s.name === 'activitypub.actor')) { + if (services.filter(s => s.name === 'activitypub.actor')) { await ctx.call('activitypub.actor.addEndpoint', { actorUri: webId, predicate: 'https://www.w3.org/ns/activitystreams#proxyUrl', - endpoint: urlJoin(webId, 'proxy'), + endpoint: urlJoin(webId, 'proxy') }); } } - }, - }, + } + } }; module.exports = ProxyService; diff --git a/src/middleware/packages/sparql-endpoint/getRoute.js b/src/middleware/packages/sparql-endpoint/getRoute.js index 9239d3728..b5d2e3a09 100644 --- a/src/middleware/packages/sparql-endpoint/getRoute.js +++ b/src/middleware/packages/sparql-endpoint/getRoute.js @@ -10,21 +10,21 @@ function getRoute(path) { mergeParams: true, aliases: { 'GET /': [...middlewares, 'sparqlEndpoint.query'], - 'POST /': [...middlewares, 'sparqlEndpoint.query'], + 'POST /': [...middlewares, 'sparqlEndpoint.query'] }, // Disable the body parsers so that we can parse the body ourselves // (Moleculer-web doesn't handle non-JSON bodies, so we must do it) bodyParsers: { json: false, - urlencoded: false, + urlencoded: false }, onError(req, res, err) { const { type, code, message, data, name } = err; res.writeHead(Number(code) || 500, data && data.status ? data.status : 'Server error', { - 'Content-Type': 'application/json', + 'Content-Type': 'application/json' }); res.end(JSON.stringify({ type, code, message, data, name })); - }, + } }; } diff --git a/src/middleware/packages/sync/middlewares/objects-watcher.js b/src/middleware/packages/sync/middlewares/objects-watcher.js index 970779586..214537a00 100644 --- a/src/middleware/packages/sync/middlewares/objects-watcher.js +++ b/src/middleware/packages/sync/middlewares/objects-watcher.js @@ -8,7 +8,7 @@ const handledActions = [ 'webacl.resource.addRights', 'webacl.resource.setRights', 'webacl.resource.removeRights', - 'webacl.resource.deleteAllRights', + 'webacl.resource.deleteAllRights' ]; const ObjectsWatcherMiddleware = (config = {}) => { @@ -45,16 +45,16 @@ const ObjectsWatcherMiddleware = (config = {}) => { const isPublic = await ctx.call('webacl.resource.isPublic', { resourceUri }); const actor = await getActor(ctx, resourceUri); const usersWithReadRights = await ctx.call('webacl.resource.getUsersWithReadRights', { resourceUri }); - const recipients = usersWithReadRights.filter((u) => u !== actor.id); + const recipients = usersWithReadRights.filter(u => u !== actor.id); if (isPublic) { return [...recipients, actor.followers, PUBLIC_URI]; } return recipients; }; - const isWatched = (containersUris) => { - return containersUris.some((uri) => - watchedContainers.some((container) => container.pathRegex.test(new URL(uri).pathname)), + const isWatched = containersUris => { + return containersUris.some(uri => + watchedContainers.some(container => container.pathRegex.test(new URL(uri).pathname)) ); }; @@ -79,9 +79,9 @@ const ObjectsWatcherMiddleware = (config = {}) => { actor: actor.id, type: ACTIVITY_TYPES.ANNOUNCE, object: activity, - to: recipients, + to: recipients }, - { meta: { webId: actor.id } }, + { meta: { webId: actor.id } } ); } }; @@ -95,14 +95,14 @@ const ObjectsWatcherMiddleware = (config = {}) => { } const containers = await broker.call('ldp.registry.list'); - watchedContainers = Object.values(containers).filter((c) => !c.excludeFromMirror); + watchedContainers = Object.values(containers).filter(c => !c.excludeFromMirror); initialized = true; cacherActivated = !!broker.cacher; }, localAction: (next, action) => { if (handledActions.includes(action.name)) { - return async (ctx) => { + return async ctx => { // Don't handle actions until middleware is fully started // Otherwise, the creation of the relay actor calls the middleware before it started if (!initialized) return await next(ctx); @@ -136,7 +136,7 @@ const ObjectsWatcherMiddleware = (config = {}) => { if (new URL(ctx.params.resourceUri).pathname.startsWith('/_groups/')) return await next(ctx); const containerExist = await ctx.call('ldp.container.exist', { containerUri: ctx.params.resourceUri, - webId: 'system', + webId: 'system' }); if (containerExist) { containerUri = ctx.params.resourceUri; @@ -178,11 +178,11 @@ const ObjectsWatcherMiddleware = (config = {}) => { // Ensure the resource has not already been deleted (this action is used by the WebAclMiddleware when resources are deleted) const containerExist = await ctx.call('ldp.container.exist', { containerUri: ctx.params.resourceUri, - webId: 'system', + webId: 'system' }); const resourceExist = await ctx.call('ldp.resource.exist', { resourceUri: ctx.params.resourceUri, - webId: 'system', + webId: 'system' }); if (containerExist || resourceExist) { oldRecipients = await getRecipients(ctx, ctx.params.resourceUri); @@ -205,7 +205,7 @@ const ObjectsWatcherMiddleware = (config = {}) => { await announce(ctx, actionReturnValue, recipients, { type: ACTIVITY_TYPES.CREATE, object: actionReturnValue, - target: ctx.params.containerUri, + target: ctx.params.containerUri }); } break; @@ -217,7 +217,7 @@ const ObjectsWatcherMiddleware = (config = {}) => { if (recipients.length > 0) { await announce(ctx, resourceUri, recipients, { type: ACTIVITY_TYPES.UPDATE, - object: resourceUri, + object: resourceUri }); } break; @@ -228,7 +228,7 @@ const ObjectsWatcherMiddleware = (config = {}) => { await announce(ctx, ctx.params.resourceUri, oldRecipients, { type: ACTIVITY_TYPES.DELETE, object: ctx.params.resourceUri, - target: oldContainers, + target: oldContainers }); } break; @@ -239,15 +239,15 @@ const ObjectsWatcherMiddleware = (config = {}) => { // Clear cache now otherwise getRecipients() may return the old cache rights await clearWebAclCache(ctx, resourceUri, containerUri); const newRecipients = await getRecipients(ctx, ctx.params.resourceUri); - const recipientsAdded = newRecipients.filter((u) => !oldRecipients.includes(u)); + const recipientsAdded = newRecipients.filter(u => !oldRecipients.includes(u)); if (recipientsAdded.length > 0) { const containers = await ctx.call('ldp.resource.getContainers', { - resourceUri: ctx.params.resourceUri, + resourceUri: ctx.params.resourceUri }); await announce(ctx, ctx.params.resourceUri, recipientsAdded, { type: ACTIVITY_TYPES.CREATE, object: ctx.params.resourceUri, - target: containers, + target: containers }); } } @@ -260,21 +260,21 @@ const ObjectsWatcherMiddleware = (config = {}) => { const newRecipients = await getRecipients(ctx, ctx.params.resourceUri); const containers = await ctx.call('ldp.resource.getContainers', { resourceUri: ctx.params.resourceUri }); - const recipientsAdded = newRecipients.filter((u) => !oldRecipients.includes(u)); + const recipientsAdded = newRecipients.filter(u => !oldRecipients.includes(u)); if (recipientsAdded.length > 0) { await announce(ctx, ctx.params.resourceUri, recipientsAdded, { type: ACTIVITY_TYPES.CREATE, object: ctx.params.resourceUri, - target: containers, + target: containers }); } - const recipientsRemoved = oldRecipients.filter((u) => !newRecipients.includes(u)); + const recipientsRemoved = oldRecipients.filter(u => !newRecipients.includes(u)); if (recipientsRemoved.length > 0) { await announce(ctx, ctx.params.resourceUri, recipientsRemoved, { type: ACTIVITY_TYPES.DELETE, object: ctx.params.resourceUri, - target: containers, + target: containers }); } @@ -284,7 +284,7 @@ const ObjectsWatcherMiddleware = (config = {}) => { await announce(ctx, ctx.params.resourceUri, { type: ACTIVITY_TYPES.CREATE, object: subUris, - target: ctx.params.resourceUri, + target: ctx.params.resourceUri }); } @@ -294,7 +294,7 @@ const ObjectsWatcherMiddleware = (config = {}) => { await announce(ctx, ctx.params.resourceUri, { type: ACTIVITY_TYPES.DELETE, object: subUris, - target: ctx.params.resourceUri, + target: ctx.params.resourceUri }); } @@ -308,15 +308,15 @@ const ObjectsWatcherMiddleware = (config = {}) => { // Clear cache now otherwise getRecipients() may return the old cache rights await clearWebAclCache(ctx, resourceUri, containerUri); const newRecipients = await getRecipients(ctx, ctx.params.resourceUri); - const recipientsRemoved = oldRecipients.filter((u) => !newRecipients.includes(u)); + const recipientsRemoved = oldRecipients.filter(u => !newRecipients.includes(u)); if (recipientsRemoved.length > 0 && !newRecipients.includes(PUBLIC_URI)) { const containers = await ctx.call('ldp.resource.getContainers', { - resourceUri: ctx.params.resourceUri, + resourceUri: ctx.params.resourceUri }); await announce(ctx, ctx.params.resourceUri, recipientsRemoved, { type: ACTIVITY_TYPES.DELETE, object: ctx.params.resourceUri, - target: containers, + target: containers }); } break; @@ -333,14 +333,14 @@ const ObjectsWatcherMiddleware = (config = {}) => { }, localEvent(next, event) { if (event.name === 'ldp.registry.registered') { - return async (ctx) => { + return async ctx => { const { container } = ctx.params; if (!container.excludeFromMirror) watchedContainers.push(container); return next(ctx); }; } return next; - }, + } }; }; diff --git a/src/middleware/packages/sync/services/aggregator.js b/src/middleware/packages/sync/services/aggregator.js index 2e3378744..d37dce046 100644 --- a/src/middleware/packages/sync/services/aggregator.js +++ b/src/middleware/packages/sync/services/aggregator.js @@ -6,7 +6,7 @@ module.exports = { mixins: [ActivitiesHandlerMixin], settings: { acceptFollowOffers: true, - mirrorGraph: true, + mirrorGraph: true }, dependencies: ['activitypub.relay'], created() { @@ -15,8 +15,8 @@ module.exports = { podProvider: false, mirrorGraph: this.settings.mirrorGraph, synchronizeContainers: false, - attachToLocalContainers: true, - }, + attachToLocalContainers: true + } }); }, async started() { @@ -27,8 +27,8 @@ module.exports = { match: { type: ACTIVITY_TYPES.OFFER, object: { - type: ACTIVITY_TYPES.FOLLOW, - }, + type: ACTIVITY_TYPES.FOLLOW + } }, async onReceive(ctx, activity, recipientUri) { if (this.settings.acceptFollowOffers && recipientUri === this.relayActor.id) { @@ -38,10 +38,10 @@ module.exports = { actor: this.relayActor.id, type: ACTIVITY_TYPES.FOLLOW, object: activity.actor, - to: activity.actor, + to: activity.actor }); } - }, - }, - }, + } + } + } }; diff --git a/src/middleware/packages/sync/services/mirror.js b/src/middleware/packages/sync/services/mirror.js index d4316e509..d6ab29677 100644 --- a/src/middleware/packages/sync/services/mirror.js +++ b/src/middleware/packages/sync/services/mirror.js @@ -11,7 +11,7 @@ module.exports = { name: 'mirror', settings: { graphName: 'http://semapps.org/mirror', - servers: [], + servers: [] }, dependencies: [ 'triplestore', @@ -20,7 +20,7 @@ module.exports = { 'activitypub.relay', 'auth.account', 'ldp.container', - 'ldp.registry', + 'ldp.registry' ], created() { this.broker.createService(SynchronizerService, { @@ -28,8 +28,8 @@ module.exports = { podProvider: false, mirrorGraph: true, synchronizeContainers: true, - attachToLocalContainers: false, - }, + attachToLocalContainers: false + } }); }, async started() { @@ -39,7 +39,7 @@ module.exports = { // Do not await because we don't want to block the startup of the services. this.actions .mirror({ serverUrl }) - .catch((e) => this.logger.warn(`Mirroring failed for ${serverUrl} : ${e.message}`)); + .catch(e => this.logger.warn(`Mirroring failed for ${serverUrl} : ${e.message}`)); } } }, @@ -47,7 +47,7 @@ module.exports = { mirror: { visibility: 'public', params: { - serverUrl: { type: 'string', optional: false }, + serverUrl: { type: 'string', optional: false } }, async handler(ctx) { const { serverUrl } = ctx.params; @@ -59,7 +59,7 @@ module.exports = { const alreadyFollowing = await ctx.call('activitypub.follow.isFollowing', { follower: this.relayActor.id, - following: remoteRelayActorUri, + following: remoteRelayActorUri }); if (alreadyFollowing) { @@ -76,8 +76,8 @@ module.exports = { const response = await fetch(voidUrl, { method: 'GET', headers: { - Accept: 'application/ld+json', - }, + Accept: 'application/ld+json' + } }); if (!response.ok) throw new MoleculerError(`No VOID endpoint on the server ${serverUrl}`, 404, 'NOT_FOUND'); @@ -92,7 +92,7 @@ module.exports = { throw new MoleculerError( `The VOID answer does not contain valid information for ${serverUrl}`, 400, - 'INVALID', + 'INVALID' ); // We mirror only the relevant server, meaning, not the mirrored data of the remote server. @@ -109,8 +109,8 @@ module.exports = { const rep = await fetch(p['void:uriSpace'], { method: 'GET', headers: { - Accept: 'text/turtle', - }, + Accept: 'text/turtle' + } }); if (rep.ok) { @@ -136,7 +136,7 @@ module.exports = { const singles = await this.broker.call('triplestore.query', { query: `SELECT DISTINCT ?s WHERE { GRAPH <${this.settings.graphName}> { - ?s <${serverUrl}> } }`, + ?s <${serverUrl}> } }` }); for (const single of singles) { @@ -145,7 +145,7 @@ module.exports = { await this.broker.call('triplestore.update', { webId: 'system', query: `DELETE WHERE { GRAPH <${this.settings.graphName}> { - <${resourceUri}> ?q. } }`, + <${resourceUri}> ?q. } }` }); } catch (e) { // fail silently @@ -164,11 +164,11 @@ module.exports = { actor: this.relayActor.id, type: ACTIVITY_TYPES.FOLLOW, object: remoteRelayActorUri, - to: [remoteRelayActorUri], + to: [remoteRelayActorUri] }); return remoteRelayActorUri; - }, - }, - }, + } + } + } }; diff --git a/src/middleware/packages/sync/services/synchronizer.js b/src/middleware/packages/sync/services/synchronizer.js index e291538a5..b722da165 100644 --- a/src/middleware/packages/sync/services/synchronizer.js +++ b/src/middleware/packages/sync/services/synchronizer.js @@ -8,7 +8,7 @@ const SynchronizerService = { podProvider: false, mirrorGraph: true, synchronizeContainers: true, - attachToLocalContainers: false, + attachToLocalContainers: false }, async started() { if (!this.settings.podProvider) { @@ -28,17 +28,17 @@ const SynchronizerService = { // Check that the activity emitter is being followed by the relay actor return await this.broker.call('activitypub.follow.isFollowing', { follower: recipient, - following: activity.actor, + following: activity.actor }); - }, + } }, activities: { announceCreate: { match: { type: ACTIVITY_TYPES.ANNOUNCE, object: { - type: ACTIVITY_TYPES.CREATE, - }, + type: ACTIVITY_TYPES.CREATE + } }, async onReceive(ctx, activity, recipientUri) { if (await this.isValid(activity, recipientUri)) { @@ -46,7 +46,7 @@ const SynchronizerService = { const object = await ctx.call('ldp.remote.store', { resourceUri, mirrorGraph: this.settings.mirrorGraph, - webId: recipientUri, + webId: recipientUri }); if (activity.object.target && this.settings.synchronizeContainers) { @@ -54,7 +54,7 @@ const SynchronizerService = { await ctx.call('ldp.container.attach', { containerUri, resourceUri, - webId: recipientUri, + webId: recipientUri }); } } @@ -67,30 +67,30 @@ const SynchronizerService = { try { const containerUri = await ctx.call('ldp.registry.getUri', { path: container.path, - webId: recipientUri, + webId: recipientUri }); await ctx.call('ldp.container.attach', { containerUri, resourceUri, webId: recipientUri }); } catch (e) { this.logger.warn( - `Error when attaching remote resource ${resourceUri} to local container: ${e.message}`, + `Error when attaching remote resource ${resourceUri} to local container: ${e.message}` ); } } else { this.logger.warn( - `Cannot attach resource ${resourceUri} of type "${type}", no matching local containers were found`, + `Cannot attach resource ${resourceUri} of type "${type}", no matching local containers were found` ); } } } } - }, + } }, announceUpdate: { match: { type: ACTIVITY_TYPES.ANNOUNCE, object: { - type: ACTIVITY_TYPES.UPDATE, - }, + type: ACTIVITY_TYPES.UPDATE + } }, async onReceive(ctx, activity, recipientUri) { if (await this.isValid(activity, recipientUri)) { @@ -98,18 +98,18 @@ const SynchronizerService = { await ctx.call('ldp.remote.store', { resourceUri, mirrorGraph: this.settings.mirrorGraph, - webId: recipientUri, + webId: recipientUri }); } } - }, + } }, announceDelete: { match: { type: ACTIVITY_TYPES.ANNOUNCE, object: { - type: ACTIVITY_TYPES.DELETE, - }, + type: ACTIVITY_TYPES.DELETE + } }, async onReceive(ctx, activity, recipientUri) { if (await this.isValid(activity, recipientUri)) { @@ -117,7 +117,7 @@ const SynchronizerService = { // If the remote resource is attached to a local container, it will be automatically detached await ctx.call('ldp.remote.delete', { resourceUri, - webId: recipientUri, + webId: recipientUri }); if (activity.object.target && this.settings.synchronizeContainers) { @@ -125,13 +125,13 @@ const SynchronizerService = { await ctx.call('ldp.container.detach', { containerUri, resourceUri, - webId: recipientUri, + webId: recipientUri }); } } } } - }, + } }, announceAddToContainer: { match: { @@ -139,27 +139,27 @@ const SynchronizerService = { object: { type: ACTIVITY_TYPES.ADD, object: { - type: OBJECT_TYPES.RELATIONSHIP, - }, - }, + type: OBJECT_TYPES.RELATIONSHIP + } + } }, async onReceive(ctx, activity, recipientUri) { if (this.settings.synchronizeContainers) { if (await this.isValid(activity, recipientUri)) { const predicate = await ctx.call('jsonld.expandPredicate', { predicate: activity.object.object.relationship, - context: activity['@context'], + context: activity['@context'] }); if (predicate === 'http://www.w3.org/ns/ldp#contains') { await ctx.call('ldp.container.attach', { containerUri: activity.object.object.subject, resourceUri: activity.object.object.object, - webId: recipientUri, + webId: recipientUri }); } } } - }, + } }, announceRemoveFromContainer: { match: { @@ -167,29 +167,29 @@ const SynchronizerService = { object: { type: ACTIVITY_TYPES.REMOVE, object: { - type: OBJECT_TYPES.RELATIONSHIP, - }, - }, + type: OBJECT_TYPES.RELATIONSHIP + } + } }, async onReceive(ctx, activity, recipientUri) { if (this.settings.synchronizeContainers) { if (await this.isValid(activity, recipientUri)) { const predicate = await ctx.call('jsonld.expandPredicate', { predicate: activity.object.object.relationship, - context: activity['@context'], + context: activity['@context'] }); if (predicate === 'http://www.w3.org/ns/ldp#contains') { await ctx.call('ldp.container.detach', { containerUri: activity.object.object.subject, resourceUri: activity.object.object.object, - webId: recipientUri, + webId: recipientUri }); } } } - }, - }, - }, + } + } + } }; module.exports = SynchronizerService; diff --git a/src/middleware/packages/triplestore/actions/countTriplesOfSubject.js b/src/middleware/packages/triplestore/actions/countTriplesOfSubject.js index 2aa1a445a..e13454edf 100644 --- a/src/middleware/packages/triplestore/actions/countTriplesOfSubject.js +++ b/src/middleware/packages/triplestore/actions/countTriplesOfSubject.js @@ -4,20 +4,20 @@ module.exports = { visibility: 'public', params: { uri: { - type: 'string', + type: 'string' }, webId: { type: 'string', - optional: true, + optional: true }, dataset: { type: 'string', - optional: true, + optional: true }, graphName: { type: 'string', - optional: true, - }, + optional: true + } }, async handler(ctx) { const webId = ctx.params.webId || ctx.meta.webId || 'anon'; @@ -33,9 +33,9 @@ module.exports = { `, accept: MIME_TYPES.JSON, webId, - dataset, + dataset }); return results.length; - }, + } }; diff --git a/src/middleware/packages/triplestore/actions/deleteOrphanBlankNodes.js b/src/middleware/packages/triplestore/actions/deleteOrphanBlankNodes.js index 9a86af3a1..5b7c8c761 100644 --- a/src/middleware/packages/triplestore/actions/deleteOrphanBlankNodes.js +++ b/src/middleware/packages/triplestore/actions/deleteOrphanBlankNodes.js @@ -3,12 +3,12 @@ module.exports = { params: { dataset: { type: 'string', - optional: true, + optional: true }, graphName: { type: 'string', - optional: true, - }, + optional: true + } }, async handler(ctx) { const dataset = ctx.params.dataset || ctx.meta.dataset || this.settings.mainDataset; @@ -29,10 +29,10 @@ module.exports = { } `, webId: 'system', - dataset, + dataset }, - { parentCtx: ctx }, + { parentCtx: ctx } ); } - }, + } }; diff --git a/src/middleware/packages/triplestore/actions/insert.js b/src/middleware/packages/triplestore/actions/insert.js index d635f6986..272b61ecf 100644 --- a/src/middleware/packages/triplestore/actions/insert.js +++ b/src/middleware/packages/triplestore/actions/insert.js @@ -6,24 +6,24 @@ module.exports = { params: { resource: { type: 'multi', - rules: [{ type: 'string' }, { type: 'object' }], + rules: [{ type: 'string' }, { type: 'object' }] }, contentType: { type: 'string', - optional: true, + optional: true }, webId: { type: 'string', - optional: true, + optional: true }, graphName: { type: 'string', - optional: true, + optional: true }, dataset: { type: 'string', - optional: true, - }, + optional: true + } }, async handler(ctx) { const { resource, contentType, graphName } = ctx.params; @@ -37,8 +37,8 @@ module.exports = { rdf = await ctx.call('jsonld.toRDF', { input: resource, options: { - format: 'application/n-quads', - }, + format: 'application/n-quads' + } }); } @@ -54,9 +54,9 @@ module.exports = { headers: { 'Content-Type': 'application/sparql-update', 'X-SemappsUser': webId, - Authorization: this.Authorization, - }, + Authorization: this.Authorization + } }); } - }, + } }; diff --git a/src/middleware/packages/triplestore/actions/query.js b/src/middleware/packages/triplestore/actions/query.js index 23ea55ad5..688c75f17 100644 --- a/src/middleware/packages/triplestore/actions/query.js +++ b/src/middleware/packages/triplestore/actions/query.js @@ -6,20 +6,20 @@ module.exports = { params: { query: { type: 'multi', - rules: [{ type: 'string' }, { type: 'object' }], + rules: [{ type: 'string' }, { type: 'object' }] }, accept: { type: 'string', - default: MIME_TYPES.JSON, + default: MIME_TYPES.JSON }, webId: { type: 'string', - optional: true, + optional: true }, dataset: { type: 'string', - optional: true, - }, + optional: true + } }, async handler(ctx) { let { accept, query } = ctx.params; @@ -38,8 +38,8 @@ module.exports = { headers: { 'Content-Type': 'application/sparql-query', 'X-SemappsUser': webId, - Accept: acceptNegotiatedType.fusekiMapping, - }, + Accept: acceptNegotiatedType.fusekiMapping + } }); // we don't use the property ctx.meta.$responseType because we are not in a HTTP API call here @@ -73,5 +73,5 @@ module.exports = { default: throw new Error('SPARQL Verb not supported'); } - }, + } }; diff --git a/src/middleware/packages/triplestore/actions/update.js b/src/middleware/packages/triplestore/actions/update.js index e1f85dbb2..d9d90145d 100644 --- a/src/middleware/packages/triplestore/actions/update.js +++ b/src/middleware/packages/triplestore/actions/update.js @@ -5,16 +5,16 @@ module.exports = { params: { query: { type: 'multi', - rules: [{ type: 'string' }, { type: 'object' }], + rules: [{ type: 'string' }, { type: 'object' }] }, webId: { type: 'string', - optional: true, + optional: true }, dataset: { type: 'string', - optional: true, - }, + optional: true + } }, async handler(ctx) { let { query } = ctx.params; @@ -34,9 +34,9 @@ module.exports = { body: query, headers: { 'Content-Type': 'application/sparql-update', - 'X-SemappsUser': webId, - }, + 'X-SemappsUser': webId + } }); } - }, + } }; diff --git a/src/middleware/packages/triplestore/adapter.js b/src/middleware/packages/triplestore/adapter.js index 4c4320580..a6c9e20b0 100644 --- a/src/middleware/packages/triplestore/adapter.js +++ b/src/middleware/packages/triplestore/adapter.js @@ -19,7 +19,7 @@ class TripleStoreAdapter { await this.broker.call('triplestore.dataset.create', { dataset: this.dataset, - secure: false, + secure: false }); } @@ -52,24 +52,24 @@ class TripleStoreAdapter { ${ query ? Object.keys(query) - .map((predicate) => `?s <${this.ontology + predicate}> "${query[predicate]}"`) + .map(predicate => `?s <${this.ontology + predicate}> "${query[predicate]}"`) .join(' . ') : '' } } `, accept: MIME_TYPES.JSON, - dataset: this.dataset, + dataset: this.dataset }) - .then((result) => { + .then(result => { return this.broker.call('jsonld.frame', { input: result, frame: { - '@context': { '@vocab': this.ontology }, - }, + '@context': { '@vocab': this.ontology } + } }); }) - .then((result) => { + .then(result => { if (result['@graph']) { // Several results return result['@graph']; @@ -103,15 +103,15 @@ class TripleStoreAdapter { } `, accept: MIME_TYPES.JSON, - dataset: this.dataset, + dataset: this.dataset }) - .then((result) => { + .then(result => { return this.broker.call('jsonld.frame', { input: result, frame: { '@context': { '@vocab': this.ontology }, - '@id': _id, - }, + '@id': _id + } }); }); } @@ -120,7 +120,7 @@ class TripleStoreAdapter { * Find all entities by IDs */ findByIds(ids) { - return Promise.all(ids.map((id) => this.findById(id))); + return Promise.all(ids.map(id => this.findById(id))); } /** @@ -132,7 +132,7 @@ class TripleStoreAdapter { * - query */ count(filters = {}) { - return this.find(filters).then((result) => result.length); + return this.find(filters).then(result => result.length); } /** @@ -147,10 +147,10 @@ class TripleStoreAdapter { resource: { '@context': { '@vocab': this.ontology }, '@type': this.type, - ...resource, + ...resource }, contentType: MIME_TYPES.JSON, - dataset: this.dataset, + dataset: this.dataset }) .then(() => this.findById(resource['@id'])); } @@ -180,7 +180,7 @@ class TripleStoreAdapter { if (!_id) throw new Error('An ID must be specified to update resources'); return this.findById(_id) - .then((oldData) => { + .then(oldData => { newData = { ...oldData, ...newData, '@id': null, '@type': null, '@context': null }; return this.broker.call('triplestore.update', { query: ` @@ -192,8 +192,8 @@ class TripleStoreAdapter { ${ newData ? Object.keys(newData) - .filter((predicate) => newData[predicate]) - .map((predicate) => `<${_id}> <${this.ontology + predicate}> "${newData[predicate]}"`) + .filter(predicate => newData[predicate]) + .map(predicate => `<${_id}> <${this.ontology + predicate}> "${newData[predicate]}"`) .join(' . ') : '' } @@ -203,7 +203,7 @@ class TripleStoreAdapter { } `, contentType: MIME_TYPES.JSON, - dataset: this.dataset, + dataset: this.dataset }); }) .then(() => newData); @@ -223,7 +223,7 @@ class TripleStoreAdapter { return this.broker .call('triplestore.update', { query: `DELETE WHERE { <${_id}> ?p ?o . }`, - dataset: this.dataset, + dataset: this.dataset }) .then(() => { // We must return the number of deleted resource diff --git a/src/middleware/packages/triplestore/service.js b/src/middleware/packages/triplestore/service.js index b2264e7fe..65a7d29d9 100644 --- a/src/middleware/packages/triplestore/service.js +++ b/src/middleware/packages/triplestore/service.js @@ -20,7 +20,7 @@ const TripleStoreService = { password: null, mainDataset: null, // Sub-services customization - dataset: {}, + dataset: {} }, dependencies: ['jsonld'], async created() { @@ -33,8 +33,8 @@ const TripleStoreService = { url, user, password, - ...dataset, - }, + ...dataset + } }); } }, @@ -51,7 +51,7 @@ const TripleStoreService = { dropAll, countTriplesOfSubject, tripleExist, - deleteOrphanBlankNodes, + deleteOrphanBlankNodes }, methods: { async fetch(url, { method = 'POST', body, headers }) { @@ -60,8 +60,8 @@ const TripleStoreService = { body, headers: { ...headers, - Authorization: `Basic ${Buffer.from(`${this.settings.user}:${this.settings.password}`).toString('base64')}`, - }, + Authorization: `Basic ${Buffer.from(`${this.settings.user}:${this.settings.password}`).toString('base64')}` + } }); if (!response.ok) { @@ -87,8 +87,8 @@ const TripleStoreService = { console.error(e); throw new MoleculerError(`Invalid SPARQL.js object: ${JSON.stringify(query)}`, 400, 'BAD_REQUEST'); } - }, - }, + } + } }; module.exports = TripleStoreService; diff --git a/src/middleware/packages/triplestore/subservices/dataset.js b/src/middleware/packages/triplestore/subservices/dataset.js index 14a564616..3f3ab3685 100644 --- a/src/middleware/packages/triplestore/subservices/dataset.js +++ b/src/middleware/packages/triplestore/subservices/dataset.js @@ -4,18 +4,18 @@ const path = require('path'); const urlJoin = require('url-join'); const format = require('string-template'); -const delay = (t) => new Promise((resolve) => setTimeout(resolve, t)); +const delay = t => new Promise(resolve => setTimeout(resolve, t)); const DatasetService = { name: 'triplestore.dataset', settings: { url: null, user: null, - password: null, + password: null }, started() { this.headers = { - Authorization: `Basic ${Buffer.from(`${this.settings.user}:${this.settings.password}`).toString('base64')}`, + Authorization: `Basic ${Buffer.from(`${this.settings.user}:${this.settings.password}`).toString('base64')}` }; }, actions: { @@ -25,7 +25,7 @@ const DatasetService = { // Ask Fuseki to backup the given dataset const response = await fetch(urlJoin(this.settings.url, '$/backup', dataset), { method: 'POST', - headers: this.headers, + headers: this.headers }); // Wait for backup to complete @@ -49,7 +49,7 @@ const DatasetService = { response = await fetch(urlJoin(this.settings.url, '$/datasets'), { method: 'POST', headers: { ...this.headers, 'Content-Type': 'text/turtle' }, - body: assembler, + body: assembler }); if (response.status === 200) { @@ -64,18 +64,18 @@ const DatasetService = { async exist(ctx) { const { dataset } = ctx.params; const response = await fetch(urlJoin(this.settings.url, '$/datasets/', dataset), { - headers: this.headers, + headers: this.headers }); return response.status === 200; }, async list() { const response = await fetch(urlJoin(this.settings.url, '$/datasets'), { - headers: this.headers, + headers: this.headers }); if (response.ok) { const json = await response.json(); - return json.datasets.map((dataset) => dataset['ds.name'].substring(1)); + return json.datasets.map(dataset => dataset['ds.name'].substring(1)); } return []; }, @@ -96,15 +96,15 @@ const DatasetService = { const response = await fetch(urlJoin(this.settings.url, '$/tasks/', `${taskId}`), { method: 'GET', - headers: this.headers, + headers: this.headers }); if (response.ok) { task = await response.json(); } } while (!task || !task.finished); - }, - }, + } + } }; module.exports = DatasetService; diff --git a/src/middleware/packages/void/service.js b/src/middleware/packages/void/service.js index 2df083e8f..42e1810f1 100644 --- a/src/middleware/packages/void/service.js +++ b/src/middleware/packages/void/service.js @@ -11,14 +11,14 @@ const { parseHeader } = require('@semapps/middlewares'); const prefixes = { dc: 'http://purl.org/dc/terms/', void: 'http://rdfs.org/ns/void#', - semapps: 'http://semapps.org/ns/core#', + semapps: 'http://semapps.org/ns/core#' }; function streamToString(stream) { let res = ''; return new Promise((resolve, reject) => { - stream.on('data', (chunk) => (res += chunk)); - stream.on('error', (err) => reject(err)); + stream.on('data', chunk => (res += chunk)); + stream.on('error', err => reject(err)); stream.on('end', () => resolve(res)); }); } @@ -26,27 +26,27 @@ function streamToString(stream) { const jsonContext = { ...prefixes, 'dc:license': { - '@type': '@id', + '@type': '@id' }, 'void:feature': { - '@type': '@id', + '@type': '@id' }, 'void:sparqlEndpoint': { - '@type': '@id', + '@type': '@id' }, 'void:rootResource': { - '@type': '@id', + '@type': '@id' }, 'void:vocabulary': { - '@type': '@id', + '@type': '@id' }, 'void:entities': { '@type': 'xsd:integer' }, 'void:doNotMirror': { '@type': 'xsd:boolean' }, 'void:class': { '@type': '@id' }, 'void:classPartition': { '@type': '@id' }, 'semapps:blankNodes': { - '@type': '@id', - }, + '@type': '@id' + } }; const addClassPartition = (serverUrl, partition, graph, scalar) => { @@ -55,9 +55,9 @@ const addClassPartition = (serverUrl, partition, graph, scalar) => { { s: blankNode(`b${scalar}`), p: namedNode('http://rdfs.org/ns/void#uriSpace'), - o: literal(partition['http://rdfs.org/ns/void#uriSpace']), + o: literal(partition['http://rdfs.org/ns/void#uriSpace']) }, - ...partition['http://rdfs.org/ns/void#class'].map((t) => { + ...partition['http://rdfs.org/ns/void#class'].map(t => { return { s: blankNode(`b${scalar}`), p: namedNode('http://rdfs.org/ns/void#class'), o: namedNode(t) }; }), { @@ -65,21 +65,21 @@ const addClassPartition = (serverUrl, partition, graph, scalar) => { p: namedNode('http://rdfs.org/ns/void#entities'), o: literal( partition['http://rdfs.org/ns/void#entities'].toString(), - namedNode('http://www.w3.org/2001/XMLSchema#integer'), - ), - }, + namedNode('http://www.w3.org/2001/XMLSchema#integer') + ) + } ]; if (partition['http://semapps.org/ns/core#blankNodes']) blank.data.push({ s: blankNode(`b${scalar}`), p: namedNode('http://semapps.org/ns/core#blankNodes'), - o: partition['http://semapps.org/ns/core#blankNodes'].map((bn) => namedNode(bn)), + o: partition['http://semapps.org/ns/core#blankNodes'].map(bn => namedNode(bn)) }); if (partition['http://semapps.org/ns/core#doNotMirror']) blank.data.push({ s: blankNode(`b${scalar}`), p: namedNode('http://semapps.org/ns/core#doNotMirror'), - o: literal(true, namedNode('http://www.w3.org/2001/XMLSchema#boolean')), + o: literal(true, namedNode('http://www.w3.org/2001/XMLSchema#boolean')) }); graph.push({ s: namedNode(serverUrl), p: namedNode('http://rdfs.org/ns/void#classPartition'), o: blank }); @@ -94,14 +94,14 @@ const addMirrorServer = async ( mirrorGraph, ctx, nextScalar, - originalVoid, + originalVoid ) => { const thisServer = createFragmentURL(baseUrl, serverUrl); graph.push({ s: namedNode(thisServer), p: namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), - o: namedNode('http://rdfs.org/ns/void#Dataset'), + o: namedNode('http://rdfs.org/ns/void#Dataset') }); // graph.push({ // s: namedNode(thisServer), @@ -111,7 +111,7 @@ const addMirrorServer = async ( graph.push({ s: namedNode(thisServer), p: namedNode('http://rdfs.org/ns/void#feature'), - o: namedNode('http://www.w3.org/ns/formats/N-Triples'), + o: namedNode('http://www.w3.org/ns/formats/N-Triples') }); graph.push({ s: namedNode(thisServer), p: namedNode('http://rdfs.org/ns/void#uriSpace'), o: literal(serverUrl) }); @@ -119,7 +119,7 @@ const addMirrorServer = async ( graph.push({ s: namedNode(thisServer), p: namedNode('http://rdfs.org/ns/void#sparqlEndpoint'), - o: namedNode(hasSparql), + o: namedNode(hasSparql) }); const partitionsMap = {}; @@ -137,12 +137,12 @@ const addMirrorServer = async ( for (const [i, p] of containers.entries()) { const types = await ctx.call('triplestore.query', { - query: `SELECT DISTINCT ?t FROM <${mirrorGraph}> { <${p}> ?o. ?o ?t }`, + query: `SELECT DISTINCT ?t FROM <${mirrorGraph}> { <${p}> ?o. ?o ?t }` }); const partition = { 'http://rdfs.org/ns/void#uriSpace': p, - 'http://rdfs.org/ns/void#class': types.map((type) => type.t.value), + 'http://rdfs.org/ns/void#class': types.map(type => type.t.value) }; const dereference = partitionsMap[p]; @@ -151,7 +151,7 @@ const addMirrorServer = async ( } const count = await ctx.call('triplestore.query', { - query: `SELECT (COUNT (?o) as ?count) FROM <${mirrorGraph}> { <${p}> ?o }`, + query: `SELECT (COUNT (?o) as ?count) FROM <${mirrorGraph}> { <${p}> ?o }` }); partition['http://rdfs.org/ns/void#entities'] = Number(count[0].count.value); @@ -168,14 +168,14 @@ module.exports = { ontologies: [], title: null, description: null, - license: null, + license: null }, dependencies: ['ldp.registry', 'api', 'triplestore', 'jsonld'], actions: { getRemote: { visibility: 'public', params: { - serverUrl: { type: 'string', optional: false }, + serverUrl: { type: 'string', optional: false } }, async handler(ctx) { try { @@ -183,8 +183,8 @@ module.exports = { const response = await fetch(voidUrl, { method: 'GET', headers: { - Accept: 'application/ld+json', - }, + Accept: 'application/ld+json' + } }); if (response.ok) { const json = await response.json(); @@ -193,13 +193,13 @@ module.exports = { } catch (e) { this.logger.warn(`Silently ignored error when fetching void endpoint: ${e.message}`); } - }, + } }, get: { visibility: 'public', params: { accept: { type: 'string', optional: true }, - webId: { type: 'string', optional: true }, + webId: { type: 'string', optional: true } }, async handler(ctx) { let { webId, accept } = ctx.params; @@ -219,27 +219,27 @@ module.exports = { graph.push({ s: namedNode(thisServer), p: namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), - o: namedNode('http://rdfs.org/ns/void#Dataset'), + o: namedNode('http://rdfs.org/ns/void#Dataset') }); if (this.settings.title) { graph.push({ s: namedNode(thisServer), p: namedNode('http://purl.org/dc/terms/title'), - o: literal(this.settings.title), + o: literal(this.settings.title) }); } if (this.settings.description) { graph.push({ s: namedNode(thisServer), p: namedNode('http://purl.org/dc/terms/description'), - o: literal(this.settings.description), + o: literal(this.settings.description) }); } if (this.settings.license) { graph.push({ s: namedNode(thisServer), p: namedNode('http://purl.org/dc/terms/license'), - o: namedNode(this.settings.license), + o: namedNode(this.settings.license) }); } // graph.push({ @@ -250,36 +250,36 @@ module.exports = { graph.push({ s: namedNode(thisServer), p: namedNode('http://rdfs.org/ns/void#feature'), - o: namedNode('http://www.w3.org/ns/formats/N-Triples'), + o: namedNode('http://www.w3.org/ns/formats/N-Triples') }); graph.push({ s: namedNode(thisServer), p: namedNode('http://rdfs.org/ns/void#uriSpace'), - o: literal(this.settings.baseUrl), + o: literal(this.settings.baseUrl) }); const services = await ctx.call('$node.services'); const hasSparql = - services.filter((s) => s.name === 'sparqlEndpoint').length > 0 + services.filter(s => s.name === 'sparqlEndpoint').length > 0 ? urlJoin(this.settings.baseUrl, 'sparql') : undefined; if (hasSparql) graph.push({ s: namedNode(thisServer), p: namedNode('http://rdfs.org/ns/void#sparqlEndpoint'), - o: namedNode(hasSparql), + o: namedNode(hasSparql) }); graph.push({ s: namedNode(thisServer), p: namedNode('http://rdfs.org/ns/void#rootResource'), - o: namedNode(this.settings.baseUrl), + o: namedNode(this.settings.baseUrl) }); for (const onto of this.settings.ontologies) { graph.push({ s: namedNode(thisServer), p: namedNode('http://rdfs.org/ns/void#vocabulary'), - o: namedNode(onto.url), + o: namedNode(onto.url) }); } @@ -291,11 +291,11 @@ module.exports = { // then we move on to the mirrored data (containers that have been mirrored from remote servers) const serversContainers = await ctx.call('triplestore.query', { - query: `SELECT DISTINCT ?s FROM <${this.settings.mirrorGraphName}> { ?s ?o }`, + query: `SELECT DISTINCT ?s FROM <${this.settings.mirrorGraphName}> { ?s ?o }` }); const serversMap = {}; - for (const s of serversContainers.map((sc) => sc.s.value)) { + for (const s of serversContainers.map(sc => sc.s.value)) { const res = s.match(regexProtocolAndHostAndPort); if (res) { const name = urlJoin(res[0], '/'); @@ -329,7 +329,7 @@ module.exports = { this.settings.mirrorGraphName, ctx, scalar, - originalVoid, + originalVoid ); scalar += serversMap[serverUrl].length; } @@ -343,7 +343,7 @@ module.exports = { // }; return await this.formatOutput(ctx, graph, url, accept === MIME_TYPES.JSON); - }, + } }, api_get: async function api(ctx) { let { accept } = ctx.meta.headers; @@ -352,9 +352,9 @@ module.exports = { throw new MoleculerError(`Accept not supported : ${accept}`, 400, 'ACCEPT_NOT_SUPPORTED'); return await ctx.call('void.get', { - accept: accept, + accept: accept }); - }, + } }, async started() { await this.broker.call('api.addRoute', { @@ -365,9 +365,9 @@ module.exports = { authorization: false, authentication: true, aliases: { - 'GET /': [parseHeader, 'void.api_get'], - }, - }, + 'GET /': [parseHeader, 'void.api_get'] + } + } }); }, methods: { @@ -377,20 +377,20 @@ module.exports = { const res = await Promise.all( Object.values(registeredContainers) - .filter((c) => c.acceptedTypes) - .map(async (c) => { + .filter(c => c.acceptedTypes) + .map(async c => { const partition = { 'http://rdfs.org/ns/void#uriSpace': urlJoin(baseUrl, c.path), - 'http://rdfs.org/ns/void#class': defaultToArray(c.acceptedTypes), + 'http://rdfs.org/ns/void#class': defaultToArray(c.acceptedTypes) }; if (c.dereference) partition['http://semapps.org/ns/core#blankNodes'] = c.dereference; if (c.excludeFromMirror) partition['http://semapps.org/ns/core#doNotMirror'] = true; const count = await ctx.call('triplestore.query', { - query: `SELECT (COUNT (?o) as ?count) { <${partition['http://rdfs.org/ns/void#uriSpace']}> ?o }`, + query: `SELECT (COUNT (?o) as ?count) { <${partition['http://rdfs.org/ns/void#uriSpace']}> ?o }` }); partition['http://rdfs.org/ns/void#entities'] = Number(count[0].count.value); return partition; - }), + }) ); return res; }, @@ -400,16 +400,16 @@ module.exports = { const turtle = await new Promise((resolve, reject) => { const writer = new Writer({ prefixes: { ...prefixes, ...prefix, '': `${voidUrl}#` }, - format: 'Turtle', + format: 'Turtle' }); - output.forEach((f) => { + output.forEach(f => { if (f.o.termType === 'BlankNode') { - const predicates = f.o.data.map((p) => { + const predicates = f.o.data.map(p => { let obj = p.o; if (Array.isArray(obj)) obj = writer.list(obj); return { predicate: p.p, - object: obj, + object: obj }; }); writer.addQuad(f.s, f.p, writer.blank(predicates)); @@ -426,7 +426,7 @@ module.exports = { const mySerializer = new JsonLdSerializer({ context: jsonldContext, - baseIRI: voidUrl, + baseIRI: voidUrl }); for (const f of output) { @@ -451,16 +451,16 @@ module.exports = { input: jsonLd, frame: { '@context': jsonldContext, - '@type': 'void:Dataset', + '@type': 'void:Dataset' }, // Force results to be in a @graph, even if we have a single result - options: { omitGraph: false }, + options: { omitGraph: false } }); // Add the @base context. We did not use it in the frame operation, as we don't want URIs to become relative compactJsonLd['@context'] = { ...compactJsonLd['@context'], '@base': voidUrl }; return compactJsonLd; - }, - }, + } + } }; diff --git a/src/middleware/packages/webacl/bots/authorizer.js b/src/middleware/packages/webacl/bots/authorizer.js index ff977c3bc..27711df4c 100644 --- a/src/middleware/packages/webacl/bots/authorizer.js +++ b/src/middleware/packages/webacl/bots/authorizer.js @@ -1,7 +1,7 @@ module.exports = { name: 'authorizer', settings: { - rules: [], + rules: [] }, dependencies: ['webacl.resource'], methods: { @@ -11,7 +11,7 @@ module.exports = { return rule.match(record); } // If match is an object, go through all entries and check they match with the record - return Object.keys(rule.match).every((predicate) => { + return Object.keys(rule.match).every(predicate => { const value = rule.match[predicate]; return Array.isArray(record[predicate]) ? record[predicate].includes(value) : record[predicate] === value; }); @@ -26,7 +26,7 @@ module.exports = { } if (!users) return []; return Array.isArray(users) ? users : [users]; - }, + } }, events: { async 'ldp.resource.created'(ctx) { @@ -40,17 +40,17 @@ module.exports = { additionalRights: { user: { uri: user, - ...rule.rights, - }, + ...rule.rights + } }, - webId: 'system', + webId: 'system' }); } if (users.length > 0) { ctx.emit('authorizer.added', { resourceUri, users, - rule, + rule }); } } @@ -64,49 +64,49 @@ module.exports = { const newUsers = this.getUsers(rule, newData); const oldUsers = this.getUsers(rule, oldData); - const usersToAdd = newUsers.filter((t1) => !oldUsers.some((t2) => t1 === t2)); + const usersToAdd = newUsers.filter(t1 => !oldUsers.some(t2 => t1 === t2)); for (const userUri of usersToAdd) { await ctx.call('webacl.resource.addRights', { resourceUri, additionalRights: { user: { uri: userUri, - ...rule.rights, - }, + ...rule.rights + } }, - webId: 'system', + webId: 'system' }); } if (usersToAdd.length > 0) { ctx.emit('authorizer.added', { resourceUri, users: usersToAdd, - rule, + rule }); } - const usersToRemove = oldUsers.filter((t1) => !newUsers.some((t2) => t1 === t2)); + const usersToRemove = oldUsers.filter(t1 => !newUsers.some(t2 => t1 === t2)); for (const userUri of usersToRemove) { await ctx.call('webacl.resource.removeRights', { resourceUri, rights: { user: { uri: userUri, - ...rule.rights, - }, + ...rule.rights + } }, - webId: 'system', + webId: 'system' }); } if (usersToRemove.length > 0) { ctx.emit('authorizer.removed', { resourceUri, users: usersToRemove, - rule, + rule }); } } } - }, - }, + } + } }; diff --git a/src/middleware/packages/webacl/bots/groups-manager.js b/src/middleware/packages/webacl/bots/groups-manager.js index 9de4534eb..ccce225d8 100644 --- a/src/middleware/packages/webacl/bots/groups-manager.js +++ b/src/middleware/packages/webacl/bots/groups-manager.js @@ -4,7 +4,7 @@ module.exports = { name: 'groups-manager', settings: { usersContainer: null, - rules: [], + rules: [] }, dependencies: ['webacl.group'], async started() { @@ -22,14 +22,14 @@ module.exports = { return rule.match(record); } // If match is an object, go through all entries and check they match with the record - return Object.keys(rule.match).every((predicate) => { + return Object.keys(rule.match).every(predicate => { const value = rule.match[predicate]; return Array.isArray(record[predicate]) ? record[predicate].includes(value) : record[predicate] === value; }); }, isUser(resourceUri) { return getContainerFromUri(resourceUri) === this.settings.usersContainer; - }, + } }, events: { async 'ldp.resource.created'(ctx) { @@ -40,7 +40,7 @@ module.exports = { await ctx.call('webacl.group.addMember', { groupSlug: rule.groupSlug, memberUri: resourceUri, - webId: 'system', + webId: 'system' }); } } @@ -54,13 +54,13 @@ module.exports = { await ctx.call('webacl.group.addMember', { groupSlug: rule.groupSlug, memberUri: resourceUri, - webId: 'system', + webId: 'system' }); } else { await ctx.call('webacl.group.removeMember', { groupSlug: rule.groupSlug, memberUri: resourceUri, - webId: 'system', + webId: 'system' }); } } @@ -73,10 +73,10 @@ module.exports = { await ctx.call('webacl.group.removeMember', { groupSlug: rule.groupSlug, memberUri: resourceUri, - webId: 'system', + webId: 'system' }); } } - }, - }, + } + } }; diff --git a/src/middleware/packages/webacl/middlewares/cacher.js b/src/middleware/packages/webacl/middlewares/cacher.js index e8a09d6f9..e033f6be7 100644 --- a/src/middleware/packages/webacl/middlewares/cacher.js +++ b/src/middleware/packages/webacl/middlewares/cacher.js @@ -4,7 +4,7 @@ let cacher; // It has been suggested to put this middleware in Moleculer core code: // https://github.com/moleculerjs/moleculer/issues/892 -const CacherMiddleware = (opts) => ({ +const CacherMiddleware = opts => ({ name: 'CacherMiddleware', created(broker) { if (opts) { @@ -24,7 +24,7 @@ const CacherMiddleware = (opts) => ({ return cacher.localAction(next, action); } return next; - }, + } }); module.exports = CacherMiddleware; diff --git a/src/middleware/packages/webacl/middlewares/webacl.js b/src/middleware/packages/webacl/middlewares/webacl.js index b3d1a53ac..f965f3bdc 100644 --- a/src/middleware/packages/webacl/middlewares/webacl.js +++ b/src/middleware/packages/webacl/middlewares/webacl.js @@ -11,7 +11,7 @@ const modifyActions = [ 'webid.create', 'ldp.remote.store', 'ldp.remote.delete', - 'ldp.resource.delete', + 'ldp.resource.delete' ]; const addRightsToNewResource = async (ctx, resourceUri, webId) => { @@ -22,7 +22,7 @@ const addRightsToNewResource = async (ctx, resourceUri, webId) => { await ctx.call('webacl.resource.addRights', { webId: 'system', resourceUri, - newRights, + newRights }); }; @@ -41,15 +41,15 @@ const addRightsToNewUser = async (ctx, userUri) => { resourceUri: userUri, newRights: { anon: { - read: true, + read: true }, user: { uri: userUri, read: true, write: true, - control: true, - }, - }, + control: true + } + } }); }; @@ -80,7 +80,7 @@ const WebAclMiddleware = ({ baseUrl, podProvider = false, graphName = 'http://se } } `, - webId: 'system', + webId: 'system' }); if (authorizations.length > 0) { @@ -96,7 +96,7 @@ const WebAclMiddleware = ({ baseUrl, podProvider = false, graphName = 'http://se * This allows us to quickly check the permissions for GET operations using the Redis cache * This way, we don't need to add the webId in the Redis cache key and it is more efficient */ - return async (ctx) => { + return async ctx => { const webId = ctx.params.webId || ctx.meta.webId || 'anon'; const bypass = () => { ctx.params.aclVerified = true; @@ -131,7 +131,7 @@ const WebAclMiddleware = ({ baseUrl, podProvider = false, graphName = 'http://se const result = await ctx.call('webacl.resource.hasRights', { resourceUri, rights: { read: true }, // Check only the read permissions to improve performances - webId, + webId }); if (result.read) { @@ -141,7 +141,7 @@ const WebAclMiddleware = ({ baseUrl, podProvider = false, graphName = 'http://se }; } if (modifyActions.includes(action.name)) { - return async (ctx) => { + return async ctx => { const webId = ctx.params.webId || ctx.meta.webId || 'anon'; let actionReturnValue; @@ -163,7 +163,7 @@ const WebAclMiddleware = ({ baseUrl, podProvider = false, graphName = 'http://se case 'activitypub.collection.create': const { permissions } = await ctx.call('activitypub.registry.getByUri', { - collectionUri: ctx.params.collectionUri, + collectionUri: ctx.params.collectionUri }); const collectionRights = typeof permissions === 'function' ? permissions(webId) : permissions; @@ -171,7 +171,7 @@ const WebAclMiddleware = ({ baseUrl, podProvider = false, graphName = 'http://se await ctx.call('webacl.resource.addRights', { resourceUri: ctx.params.collectionUri, newRights: ctx.params.rights || collectionRights || defaultCollectionRights(webId), - webId: 'system', + webId: 'system' }); break; } @@ -188,14 +188,14 @@ const WebAclMiddleware = ({ baseUrl, podProvider = false, graphName = 'http://se await ctx.call( 'webacl.resource.deleteAllRights', { resourceUri: ctx.params.resource['@id'] || ctx.params.resource.id }, - { meta: { webId: 'system' } }, + { meta: { webId: 'system' } } ); break; case 'activitypub.collection.create': await ctx.call( 'webacl.resource.deleteAllRights', { resourceUri: ctx.params.collectionUri }, - { meta: { webId: 'system' } }, + { meta: { webId: 'system' } } ); break; } @@ -210,7 +210,7 @@ const WebAclMiddleware = ({ baseUrl, podProvider = false, graphName = 'http://se await ctx.call( 'webacl.resource.deleteAllRights', { resourceUri: ctx.params.resourceUri }, - { meta: { webId: 'system' } }, + { meta: { webId: 'system' } } ); break; @@ -218,20 +218,20 @@ const WebAclMiddleware = ({ baseUrl, podProvider = false, graphName = 'http://se await ctx.call( 'webacl.resource.deleteAllRights', { resourceUri: ctx.params.resourceUri }, - { meta: { webId: 'system' } }, + { meta: { webId: 'system' } } ); break; case 'ldp.container.create': const { permissions } = await ctx.call('ldp.registry.getByUri', { - containerUri: ctx.params.containerUri, + containerUri: ctx.params.containerUri }); const containerRights = typeof permissions === 'function' ? permissions(webId) : permissions; await ctx.call('webacl.resource.addRights', { resourceUri: ctx.params.containerUri, newRights: ctx.params.rights || containerRights || defaultContainerRights(webId), - webId: 'system', + webId: 'system' }); break; @@ -252,12 +252,12 @@ const WebAclMiddleware = ({ baseUrl, podProvider = false, graphName = 'http://se additionalRights: { user: { uri: webId, - read: true, - }, + read: true + } }, - webId: 'system', + webId: 'system' }, - { meta: { dataset } }, + { meta: { dataset } } ); } break; @@ -267,7 +267,7 @@ const WebAclMiddleware = ({ baseUrl, podProvider = false, graphName = 'http://se case 'activitypub.activity.attach': const activity = await ctx.call('activitypub.activity.get', { resourceUri: actionReturnValue.resourceUri, - webId: ctx.params.webId || 'system', + webId: ctx.params.webId || 'system' }); const recipients = await ctx.call('activitypub.activity.getRecipients', { activity }); @@ -286,10 +286,10 @@ const WebAclMiddleware = ({ baseUrl, podProvider = false, graphName = 'http://se additionalRights: { user: { uri: recipient, - read: true, - }, + read: true + } }, - webId: 'system', + webId: 'system' }); } @@ -299,10 +299,10 @@ const WebAclMiddleware = ({ baseUrl, podProvider = false, graphName = 'http://se resourceUri: actionReturnValue.resourceUri, additionalRights: { anon: { - read: true, - }, + read: true + } }, - webId: 'system', + webId: 'system' }); } } @@ -313,7 +313,7 @@ const WebAclMiddleware = ({ baseUrl, podProvider = false, graphName = 'http://se // Do not use the middleware for this action return next; - }, + } }); module.exports = WebAclMiddleware; diff --git a/src/middleware/packages/webacl/routes/getRoutes.js b/src/middleware/packages/webacl/routes/getRoutes.js index c4fde05fd..320ceb366 100644 --- a/src/middleware/packages/webacl/routes/getRoutes.js +++ b/src/middleware/packages/webacl/routes/getRoutes.js @@ -3,7 +3,7 @@ const { parseHeader, negotiateContentType, negotiateAccept, parseJson } = requir const onError = (req, res, err) => { const { type, code, message, data, name } = err; res.writeHead(Number(code) || 500, data && data.status ? data.status : 'Server error', { - 'Content-Type': 'application/json', + 'Content-Type': 'application/json' }); res.end(JSON.stringify({ type, code, message, data, name })); }; @@ -21,8 +21,8 @@ const getRoutes = () => { json: false, urlencoded: false, text: { - type: ['text/turtle', 'application/ld+json'], - }, + type: ['text/turtle', 'application/ld+json'] + } }, onBeforeCall(ctx, route, req) { ctx.meta.body = req.body; @@ -30,9 +30,9 @@ const getRoutes = () => { aliases: { 'PATCH /:slugParts*': [parseHeader, 'webacl.resource.api_addRights'], 'PUT /:slugParts*': [parseHeader, 'webacl.resource.api_setRights'], - 'GET /:slugParts*': [...middlewares, 'webacl.resource.api_getRights'], + 'GET /:slugParts*': [...middlewares, 'webacl.resource.api_getRights'] }, - onError, + onError }, { path: '/_rights', @@ -41,12 +41,12 @@ const getRoutes = () => { authentication: true, aliases: { 'GET /:slugParts*': [...middlewares, 'webacl.resource.api_hasRights'], - 'POST /:slugParts*': [...middlewares, 'webacl.resource.api_hasRights'], + 'POST /:slugParts*': [...middlewares, 'webacl.resource.api_hasRights'] }, bodyParsers: { - json: false, + json: false }, - onError, + onError }, { path: '/_groups', @@ -59,13 +59,13 @@ const getRoutes = () => { 'GET /:id': ['webacl.group.api_getMembers'], 'GET /': ['webacl.group.api_getGroups'], 'DELETE /:id': ['webacl.group.api_delete'], - 'POST /:id': ['webacl.group.api_removeMember'], + 'POST /:id': ['webacl.group.api_removeMember'] }, bodyParsers: { - json: true, + json: true }, - onError, - }, + onError + } ]; }; diff --git a/src/middleware/packages/webacl/service.js b/src/middleware/packages/webacl/service.js index 973677a32..888bf3e3a 100644 --- a/src/middleware/packages/webacl/service.js +++ b/src/middleware/packages/webacl/service.js @@ -9,7 +9,7 @@ module.exports = { baseUrl: null, graphName: 'http://semapps.org/webacl', podProvider: false, - superAdmins: [], + superAdmins: [] }, dependencies: ['api'], async created() { @@ -19,8 +19,8 @@ module.exports = { settings: { baseUrl, graphName, - podProvider, - }, + podProvider + } }); await this.broker.createService(WebAclGroupService, { @@ -28,8 +28,8 @@ module.exports = { baseUrl, graphName, podProvider, - superAdmins, - }, + superAdmins + } }); // Only create this service if a cacher is defined @@ -46,14 +46,14 @@ module.exports = { try { await this.broker.call('triplestore.query', { query: `ASK WHERE { GRAPH <${this.settings.graphName}> { ?s ?p ?o } }`, - webId: 'anon', + webId: 'anon' }); } catch (e) { if (e.code === 403) hasWebAcl = true; } if (!hasWebAcl) { throw new Error( - 'Error when starting the webAcl service: the main dataset is not secure. You must use the triplestore.dataset.create action with the `secure: true` param', + 'Error when starting the webAcl service: the main dataset is not secure. You must use the triplestore.dataset.create action with the `secure: true` param' ); } } @@ -61,5 +61,5 @@ module.exports = { for (const route of getRoutes()) { await this.broker.call('api.addRoute', { route }); } - }, + } }; diff --git a/src/middleware/packages/webacl/services/cache/index.js b/src/middleware/packages/webacl/services/cache/index.js index dff4323af..3db931058 100644 --- a/src/middleware/packages/webacl/services/cache/index.js +++ b/src/middleware/packages/webacl/services/cache/index.js @@ -29,7 +29,7 @@ module.exports = { await ctx.call('webacl.resource.hasRights', { resourceUri, rights: { read: true }, - webId, + webId }); } } @@ -40,14 +40,14 @@ module.exports = { for (const webId of users) { await this.actions.generateForUser({ webId }, { parentCtx: ctx }); } - }, + } }, events: { async 'webacl.resource.updated'(ctx) { const { uri, isContainer, defaultRightsUpdated } = ctx.params; await this.actions.invalidateResourceRights( { uri, specificUriOnly: !isContainer || !defaultRightsUpdated }, - { parentCtx: ctx }, + { parentCtx: ctx } ); }, async 'webacl.resource.deleted'(ctx) { @@ -63,6 +63,6 @@ module.exports = { const { groupUri, memberUri } = ctx.params; await this.actions.invalidateResourceRights({ uri: groupUri, specificUriOnly: true }, { parentCtx: ctx }); await this.actions.invalidateAllUserRights({ uri: memberUri }, { parentCtx: ctx }); - }, - }, + } + } }; diff --git a/src/middleware/packages/webacl/services/group/actions/addMember.js b/src/middleware/packages/webacl/services/group/actions/addMember.js index 72722233c..149761182 100644 --- a/src/middleware/packages/webacl/services/group/actions/addMember.js +++ b/src/middleware/packages/webacl/services/group/actions/addMember.js @@ -8,7 +8,7 @@ module.exports = { await ctx.call('webacl.group.addMember', { groupSlug: ctx.params.id, - memberUri: ctx.params.memberUri, + memberUri: ctx.params.memberUri }); ctx.meta.$statusCode = 204; @@ -19,7 +19,7 @@ module.exports = { groupSlug: { type: 'string', optional: true, min: 1, trim: true }, groupUri: { type: 'string', optional: true, trim: true }, memberUri: { type: 'string', optional: false, trim: true }, - webId: { type: 'string', optional: true }, + webId: { type: 'string', optional: true } }, async handler(ctx) { let { groupSlug, groupUri, memberUri } = ctx.params; @@ -41,9 +41,9 @@ module.exports = { resourceUri: groupUri, rights: { append: true, - write: true, + write: true }, - webId, + webId }); if (!groupRights.append && !groupRights.write) throw new MoleculerError(`Access denied to the group ${groupUri}`, 403, 'ACCESS_DENIED'); @@ -53,10 +53,10 @@ module.exports = { query: `PREFIX vcard: INSERT DATA { GRAPH <${this.settings.graphName}> { <${groupUri}> vcard:hasMember <${memberUri}> } }`, - webId: 'system', + webId: 'system' }); ctx.emit('webacl.group.member-added', { groupUri, memberUri }, { meta: { webId: null, dataset: null } }); - }, - }, + } + } }; diff --git a/src/middleware/packages/webacl/services/group/actions/create.js b/src/middleware/packages/webacl/services/group/actions/create.js index 6caecd32a..c194874da 100644 --- a/src/middleware/packages/webacl/services/group/actions/create.js +++ b/src/middleware/packages/webacl/services/group/actions/create.js @@ -8,7 +8,7 @@ module.exports = { if (!ctx.params.slug) throw new MoleculerError('needs a slug in your POST (json)', 400, 'BAD_REQUEST'); await ctx.call('webacl.group.create', { - groupSlug: ctx.params.slug, + groupSlug: ctx.params.slug }); ctx.meta.$statusCode = 204; @@ -18,7 +18,7 @@ module.exports = { params: { groupUri: { type: 'string', optional: true }, groupSlug: { type: 'string', optional: true, min: 1, trim: true }, - webId: { type: 'string', optional: true }, + webId: { type: 'string', optional: true } }, async handler(ctx) { let { groupUri, groupSlug } = ctx.params; @@ -39,24 +39,24 @@ module.exports = { if (webId === 'anon') { newRights.anon = { read: true, - write: true, + write: true }; } else if (webId === 'system') { newRights.anon = { - read: true, + read: true }; } else { newRights.user = { uri: webId, read: true, write: true, - control: true, + control: true }; } await ctx.call('webacl.resource.addRights', { webId: 'system', resourceUri: groupUri, - newRights, + newRights }); await ctx.call('triplestore.update', { @@ -64,12 +64,12 @@ module.exports = { PREFIX vcard: INSERT DATA { GRAPH <${this.settings.graphName}> { <${groupUri}> a vcard:Group } }`, - webId: 'system', + webId: 'system' }); // ctx.meta.$statusCode = 200; // ctx.meta.$responseType = 'application/json' return { groupUri }; - }, - }, + } + } }; diff --git a/src/middleware/packages/webacl/services/group/actions/delete.js b/src/middleware/packages/webacl/services/group/actions/delete.js index 07ffbadc8..83f52b5f7 100644 --- a/src/middleware/packages/webacl/services/group/actions/delete.js +++ b/src/middleware/packages/webacl/services/group/actions/delete.js @@ -5,7 +5,7 @@ const { removeAgentGroupOrAgentFromAuthorizations, sanitizeSPARQL } = require('. module.exports = { api: async function api(ctx) { await ctx.call('webacl.group.delete', { - groupSlug: ctx.params.id, + groupSlug: ctx.params.id }); ctx.meta.$statusCode = 204; @@ -15,7 +15,7 @@ module.exports = { params: { groupSlug: { type: 'string', optional: true, min: 1, trim: true }, groupUri: { type: 'string', optional: true, trim: true }, - webId: { type: 'string', optional: true }, + webId: { type: 'string', optional: true } }, async handler(ctx) { let { groupSlug, groupUri } = ctx.params; @@ -34,9 +34,9 @@ module.exports = { const groupRights = await ctx.call('webacl.resource.hasRights', { resourceUri: groupUri, rights: { - write: true, + write: true }, - webId, + webId }); if (!groupRights.write) throw new MoleculerError(`Access denied to the group ${groupUri}`, 403, 'ACCESS_DENIED'); @@ -46,12 +46,12 @@ module.exports = { await ctx.call('triplestore.update', { query: `DELETE WHERE { GRAPH <${this.settings.graphName}> { <${groupUri}> ?p ?o. } }`, - webId: 'system', + webId: 'system' }); await ctx.call('webacl.resource.deleteAllRights', { resourceUri: groupUri }); await removeAgentGroupOrAgentFromAuthorizations(groupUri, true, this.settings.graphName, ctx); - }, - }, + } + } }; diff --git a/src/middleware/packages/webacl/services/group/actions/getGroups.js b/src/middleware/packages/webacl/services/group/actions/getGroups.js index 5527ba978..7e10c96c2 100644 --- a/src/middleware/packages/webacl/services/group/actions/getGroups.js +++ b/src/middleware/packages/webacl/services/group/actions/getGroups.js @@ -5,7 +5,7 @@ module.exports = { action: { visibility: 'public', params: { - webId: { type: 'string', optional: true }, + webId: { type: 'string', optional: true } }, async handler(ctx) { const webId = ctx.params.webId || ctx.meta.webId || 'anon'; @@ -27,7 +27,7 @@ module.exports = { acl:accessTo ?g; ${agentSelector} } }`, - webId: 'system', + webId: 'system' }); /// TODO: implement to find the groups the user has Read access to, via his membership of other groups (agentGroup) @@ -37,11 +37,11 @@ module.exports = { query: `PREFIX vcard: SELECT ?g WHERE { GRAPH <${this.settings.graphName}> { ?g a vcard:Group } }`, - webId: 'system', + webId: 'system' }); } - return groups.map((m) => m.g.value); - }, - }, + return groups.map(m => m.g.value); + } + } }; diff --git a/src/middleware/packages/webacl/services/group/actions/getMembers.js b/src/middleware/packages/webacl/services/group/actions/getMembers.js index fbff6d193..399630402 100644 --- a/src/middleware/packages/webacl/services/group/actions/getMembers.js +++ b/src/middleware/packages/webacl/services/group/actions/getMembers.js @@ -5,7 +5,7 @@ const { sanitizeSPARQL } = require('../../../utils'); module.exports = { api: async function api(ctx) { return await ctx.call('webacl.group.getMembers', { - groupSlug: ctx.params.id, + groupSlug: ctx.params.id }); }, action: { @@ -13,7 +13,7 @@ module.exports = { params: { groupSlug: { type: 'string', optional: true, min: 1, trim: true }, groupUri: { type: 'string', optional: true, trim: true }, - webId: { type: 'string', optional: true }, + webId: { type: 'string', optional: true } }, async handler(ctx) { let { groupSlug, groupUri } = ctx.params; @@ -32,9 +32,9 @@ module.exports = { const groupRights = await ctx.call('webacl.resource.hasRights', { resourceUri: groupUri, rights: { - read: true, + read: true }, - webId, + webId }); if (!groupRights.read) throw new MoleculerError(`Access denied to the group ${groupUri}`, 403, 'ACCESS_DENIED'); } @@ -43,10 +43,10 @@ module.exports = { query: `PREFIX vcard: SELECT ?m WHERE { GRAPH <${this.settings.graphName}> { <${groupUri}> vcard:hasMember ?m } }`, - webId: 'system', + webId: 'system' }); - return members.map((m) => m.m.value); - }, - }, + return members.map(m => m.m.value); + } + } }; diff --git a/src/middleware/packages/webacl/services/group/actions/getUri.js b/src/middleware/packages/webacl/services/group/actions/getUri.js index 7a1d68d2c..fe3ccb80e 100644 --- a/src/middleware/packages/webacl/services/group/actions/getUri.js +++ b/src/middleware/packages/webacl/services/group/actions/getUri.js @@ -4,11 +4,11 @@ module.exports = { action: { visibility: 'public', params: { - groupSlug: { type: 'string', optional: false, trim: true }, + groupSlug: { type: 'string', optional: false, trim: true } }, async handler(ctx) { const { groupSlug } = ctx.params; return urlJoin(this.settings.baseUrl, '_groups', groupSlug); - }, - }, + } + } }; diff --git a/src/middleware/packages/webacl/services/group/actions/isMember.js b/src/middleware/packages/webacl/services/group/actions/isMember.js index 66c3c944f..4e9a2fad3 100644 --- a/src/middleware/packages/webacl/services/group/actions/isMember.js +++ b/src/middleware/packages/webacl/services/group/actions/isMember.js @@ -9,7 +9,7 @@ module.exports = { groupSlug: { type: 'string', optional: true, min: 1, trim: true }, groupUri: { type: 'string', optional: true, trim: true }, webId: { type: 'string', optional: true }, - memberId: { type: 'string', optional: true }, + memberId: { type: 'string', optional: true } }, async handler(ctx) { let { groupSlug, groupUri, memberId } = ctx.params; @@ -29,9 +29,9 @@ module.exports = { const groupRights = await ctx.call('webacl.resource.hasRights', { resourceUri: groupUri, rights: { - read: true, + read: true }, - webId, + webId }); if (!groupRights.read) throw new MoleculerError(`Access denied to the group ${groupUri}`, 403, 'ACCESS_DENIED'); } @@ -46,8 +46,8 @@ module.exports = { <${groupUri}> vcard:hasMember <${memberId}> . } } `, - webId: 'system', + webId: 'system' }); - }, - }, + } + } }; diff --git a/src/middleware/packages/webacl/services/group/actions/removeMember.js b/src/middleware/packages/webacl/services/group/actions/removeMember.js index 1499fa0b5..2db3acc88 100644 --- a/src/middleware/packages/webacl/services/group/actions/removeMember.js +++ b/src/middleware/packages/webacl/services/group/actions/removeMember.js @@ -9,7 +9,7 @@ module.exports = { await ctx.call('webacl.group.removeMember', { groupSlug: ctx.params.id, - memberUri: ctx.params.deleteUserUri, + memberUri: ctx.params.deleteUserUri }); ctx.meta.$statusCode = 204; @@ -20,7 +20,7 @@ module.exports = { groupSlug: { type: 'string', optional: true, min: 1, trim: true }, groupUri: { type: 'string', optional: true, trim: true }, memberUri: { type: 'string', optional: false, trim: true }, - webId: { type: 'string', optional: true }, + webId: { type: 'string', optional: true } }, async handler(ctx) { let { groupSlug, groupUri, memberUri } = ctx.params; @@ -41,9 +41,9 @@ module.exports = { const groupRights = await ctx.call('webacl.resource.hasRights', { resourceUri: groupUri, rights: { - write: true, + write: true }, - webId, + webId }); if (!groupRights.write) throw new MoleculerError(`Access denied to the group ${groupUri}`, 403, 'ACCESS_DENIED'); @@ -53,10 +53,10 @@ module.exports = { query: `PREFIX vcard: DELETE DATA { GRAPH <${this.settings.graphName}> { <${groupUri}> vcard:hasMember <${memberUri}> } }`, - webId: 'system', + webId: 'system' }); ctx.emit('webacl.group.member-removed', { groupUri, memberUri }, { meta: { webId: null, dataset: null } }); - }, - }, + } + } }; diff --git a/src/middleware/packages/webacl/services/group/index.js b/src/middleware/packages/webacl/services/group/index.js index 59224c15d..4d998eb1d 100644 --- a/src/middleware/packages/webacl/services/group/index.js +++ b/src/middleware/packages/webacl/services/group/index.js @@ -15,7 +15,7 @@ module.exports = { baseUrl: null, graphName: null, podProvider: false, - superAdmins: [], + superAdmins: [] }, dependencies: ['triplestore', 'webacl.resource', 'ldp.container'], actions: { @@ -34,7 +34,7 @@ module.exports = { getMembers: getMembersAction.action, api_getMembers: getMembersAction.api, removeMember: removeMemberAction.action, - api_removeMember: removeMemberAction.api, + api_removeMember: removeMemberAction.api }, async started() { if (this.settings.superAdmins && this.settings.superAdmins.length > 0) { @@ -51,7 +51,7 @@ module.exports = { const rootContainerExist = await this.broker.call('ldp.container.exist', { containerUri: this.settings.baseUrl, - webId: 'system', + webId: 'system' }); if (!rootContainerExist) { @@ -67,25 +67,25 @@ module.exports = { uri: groupUri, read: true, write: true, - control: true, + control: true }, default: { group: { uri: groupUri, read: true, write: true, - control: true, - }, - }, + control: true + } + } }, - webId: 'system', + webId: 'system' }); for (const memberUri of this.settings.superAdmins) { const isMember = await this.actions.isMember({ groupUri, memberId: memberUri, - webId: 'system', + webId: 'system' }); if (!isMember) { @@ -112,7 +112,7 @@ module.exports = { } } } - }, - }, - }, + } + } + } }; diff --git a/src/middleware/packages/webacl/services/resource/actions/addRights.js b/src/middleware/packages/webacl/services/resource/actions/addRights.js index 1a827b802..8ef7ee85e 100644 --- a/src/middleware/packages/webacl/services/resource/actions/addRights.js +++ b/src/middleware/packages/webacl/services/resource/actions/addRights.js @@ -7,7 +7,7 @@ const { filterTriplesForResource, processRights, FULL_FOAF_AGENT, - FULL_AGENTCLASS_URI, + FULL_AGENTCLASS_URI } = require('../../../utils'); module.exports = { @@ -26,7 +26,7 @@ module.exports = { await ctx.call('webacl.resource.addRights', { resourceUri: urlJoin(this.settings.baseUrl, ...slugParts), - addedRights, + addedRights }); ctx.meta.$statusCode = 204; @@ -42,7 +42,7 @@ module.exports = { // newRights is used to add rights to a non existing resource. newRights: { type: 'object', optional: true }, // additionalRights is used to add rights to an existing resource. - additionalRights: { type: 'object', optional: true }, + additionalRights: { type: 'object', optional: true } }, async handler(ctx) { let { webId, addedRights, resourceUri, newRights, additionalRights } = ctx.params; @@ -57,7 +57,7 @@ module.exports = { throw new MoleculerError( 'please use addedRights or additionalRights, none were provided', 403, - 'BAD_REQUEST', + 'BAD_REQUEST' ); isContainer = await this.checkResourceOrContainerExists(ctx, resourceUri); @@ -68,7 +68,7 @@ module.exports = { const { control } = await ctx.call('webacl.resource.hasRights', { resourceUri, rights: { control: true }, - webId, + webId }); if (!control) throw new MoleculerError('Access denied ! user must have Control permission', 403, 'ACCESS_DENIED'); @@ -84,7 +84,7 @@ module.exports = { if (addedRights.length === 0) new MoleculerError('No additional permissions to add!', 400, 'BAD_REQUEST'); } else { // filter out all the addedRights that are not for the resource - addedRights = addedRights.filter((a) => filterTriplesForResource(a, aclUri, isContainer)); + addedRights = addedRights.filter(a => filterTriplesForResource(a, aclUri, isContainer)); if (addedRights.length === 0) throw new MoleculerError('The rights cannot be added because they are incorrect', 400, 'BAD_REQUEST'); } @@ -94,13 +94,11 @@ module.exports = { resourceUri, this.settings.baseUrl, this.settings.graphName, - isContainer, + isContainer ); // find the difference between addedRights and currentPerms. add only what is not existant yet. - difference = addedRights.filter( - (x) => !currentPerms.some((y) => x.auth === y.auth && x.o === y.o && x.p === y.p), - ); + difference = addedRights.filter(x => !currentPerms.some(y => x.auth === y.auth && x.o === y.o && x.p === y.p)); if (difference.length === 0) return; // compile a list of Authorization already present. if some of them don't exist, we need to create them here below @@ -111,7 +109,7 @@ module.exports = { throw new MoleculerError( 'Access denied ! only system can add permissions for a newly created resource', 403, - 'ACCESS_DENIED', + 'ACCESS_DENIED' ); // we set new rights for a non existing resource @@ -140,7 +138,7 @@ module.exports = { await ctx.call('triplestore.insert', { resource: addRequest, webId: 'system', - graphName: this.settings.graphName, + graphName: this.settings.graphName }); if (newRights) { @@ -148,15 +146,15 @@ module.exports = { ctx.emit('webacl.resource.created', returnValues, { meta: { webId: null, dataset: null } }); return returnValues; } - const defaultRightsUpdated = isContainer && difference.some((triple) => triple.auth.includes('#Default')); + const defaultRightsUpdated = isContainer && difference.some(triple => triple.auth.includes('#Default')); const addPublicRead = difference.some( - (triple) => triple.auth.includes('#Read') && triple.p === FULL_AGENTCLASS_URI && triple.o === FULL_FOAF_AGENT, + triple => triple.auth.includes('#Read') && triple.p === FULL_AGENTCLASS_URI && triple.o === FULL_FOAF_AGENT ); const addDefaultPublicRead = isContainer && difference.some( - (triple) => - triple.auth.includes('#DefaultRead') && triple.p === FULL_AGENTCLASS_URI && triple.o === FULL_FOAF_AGENT, + triple => + triple.auth.includes('#DefaultRead') && triple.p === FULL_AGENTCLASS_URI && triple.o === FULL_FOAF_AGENT ); const returnValues = { @@ -166,10 +164,10 @@ module.exports = { isContainer, defaultRightsUpdated, addPublicRead, - addDefaultPublicRead, + addDefaultPublicRead }; ctx.emit('webacl.resource.updated', returnValues, { meta: { webId: null, dataset: null } }); return returnValues; - }, - }, + } + } }; diff --git a/src/middleware/packages/webacl/services/resource/actions/awaitReadRight.js b/src/middleware/packages/webacl/services/resource/actions/awaitReadRight.js index 693ee4f94..cf33f66c9 100644 --- a/src/middleware/packages/webacl/services/resource/actions/awaitReadRight.js +++ b/src/middleware/packages/webacl/services/resource/actions/awaitReadRight.js @@ -4,11 +4,11 @@ module.exports = { params: { resourceUri: { type: 'string' }, webId: { type: 'string' }, - timeout: { type: 'number', default: 10000 }, + timeout: { type: 'number', default: 10000 } }, handler(ctx) { const { resourceUri, webId, timeout } = ctx.params; - return new Promise((resolve) => { + return new Promise(resolve => { let i = 0; let interval; const checkRights = () => { @@ -16,9 +16,9 @@ module.exports = { .call('webacl.resource.hasRights', { resourceUri, rights: { read: true }, - webId, + webId }) - .then((rights) => { + .then(rights => { if (rights.read === true) { if (interval) clearInterval(interval); resolve(true); @@ -32,6 +32,6 @@ module.exports = { checkRights(); // Try immediately, then launch interval interval = setInterval(checkRights, 1000); }); - }, - }, + } + } }; diff --git a/src/middleware/packages/webacl/services/resource/actions/deleteAllRights.js b/src/middleware/packages/webacl/services/resource/actions/deleteAllRights.js index a98202fda..6eae2d7fd 100644 --- a/src/middleware/packages/webacl/services/resource/actions/deleteAllRights.js +++ b/src/middleware/packages/webacl/services/resource/actions/deleteAllRights.js @@ -4,7 +4,7 @@ module.exports = { action: { visibility: 'public', params: { - resourceUri: { type: 'string', optional: false }, + resourceUri: { type: 'string', optional: false } }, async handler(ctx) { const { resourceUri } = ctx.params; @@ -20,10 +20,10 @@ module.exports = { FILTER (?p IN (acl:accessTo, acl:default ) ) ?auth ?p2 ?o } `, - webId: 'system', + webId: 'system' }); ctx.emit('webacl.resource.deleted', { uri: resourceUri, isContainer }, { meta: { webId: null, dataset: null } }); - }, - }, + } + } }; diff --git a/src/middleware/packages/webacl/services/resource/actions/getRights.js b/src/middleware/packages/webacl/services/resource/actions/getRights.js index cb92cd6a0..aa6630ee7 100644 --- a/src/middleware/packages/webacl/services/resource/actions/getRights.js +++ b/src/middleware/packages/webacl/services/resource/actions/getRights.js @@ -13,41 +13,41 @@ const { findParentContainers, filterAgentAcl, getAclUriFromResourceUri, - getUserAgentSearchParam, + getUserAgentSearchParam } = require('../../../utils'); const prefixes = { acl: 'http://www.w3.org/ns/auth/acl#', - foaf: 'http://xmlns.com/foaf/0.1/', + foaf: 'http://xmlns.com/foaf/0.1/' }; const webAclContext = { ...prefixes, 'acl:accessTo': { - '@type': '@id', + '@type': '@id' }, 'acl:agentClass': { - '@type': '@id', + '@type': '@id' }, 'acl:agent': { - '@type': '@id', + '@type': '@id' }, 'acl:agentGroup': { - '@type': '@id', + '@type': '@id' }, 'acl:default': { - '@type': '@id', + '@type': '@id' }, 'acl:mode': { - '@type': '@id', - }, + '@type': '@id' + } }; function streamToString(stream) { let res = ''; return new Promise((resolve, reject) => { - stream.on('data', (chunk) => (res += chunk)); - stream.on('error', (err) => reject(err)); + stream.on('data', chunk => (res += chunk)); + stream.on('error', err => reject(err)); stream.on('end', () => resolve(res)); }); } @@ -56,9 +56,9 @@ async function formatOutput(ctx, output, resourceAclUri, jsonLD) { const turtle = await new Promise((resolve, reject) => { const writer = new Writer({ prefixes: { ...prefixes, '': `${resourceAclUri}#` }, - format: 'Turtle', + format: 'Turtle' }); - output.forEach((f) => writer.addQuad(f.auth, f.p, f.o)); + output.forEach(f => writer.addQuad(f.auth, f.p, f.o)); writer.end((error, res) => { resolve(res); }); @@ -68,10 +68,10 @@ async function formatOutput(ctx, output, resourceAclUri, jsonLD) { const mySerializer = new JsonLdSerializer({ context: webAclContext, - baseIRI: resourceAclUri, + baseIRI: resourceAclUri }); - output.forEach((f) => mySerializer.write(quad(f.auth, f.p, f.o))); + output.forEach(f => mySerializer.write(quad(f.auth, f.p, f.o))); mySerializer.end(); const jsonLd = JSON.parse(await streamToString(mySerializer)); @@ -80,10 +80,10 @@ async function formatOutput(ctx, output, resourceAclUri, jsonLD) { input: jsonLd, frame: { '@context': webAclContext, - '@type': 'acl:Authorization', + '@type': 'acl:Authorization' }, // Force results to be in a @graph, even if we have a single result - options: { omitGraph: false }, + options: { omitGraph: false } }); // Add the @base context. We did not use it in the frame operation, as we don't want URIs to become relative @@ -95,9 +95,9 @@ async function formatOutput(ctx, output, resourceAclUri, jsonLD) { async function filterAcls(hasControl, uaSearchParam, acls) { if (hasControl || uaSearchParam.system) return acls; - const filtered = acls.filter((acl) => filterAgentAcl(acl, uaSearchParam, false)); + const filtered = acls.filter(acl => filterAgentAcl(acl, uaSearchParam, false)); if (filtered.length) { - const header = acls.filter((acl) => filterAgentAcl(acl, uaSearchParam, true)); + const header = acls.filter(acl => filterAgentAcl(acl, uaSearchParam, true)); return header.concat(filtered); } @@ -143,7 +143,7 @@ async function getPermissions(ctx, resourceUri, baseUrl, user, graphName, isCont reads, writes, appends, - controls: containerControls, + controls: containerControls }; const moreParentContainers = await findParentContainers(ctx, containerUri); @@ -192,7 +192,7 @@ module.exports = { return await ctx.call('webacl.resource.getRights', { resourceUri: urlJoin(this.settings.baseUrl, ...slugParts), - accept: accept, + accept: accept }); }, action: { @@ -201,10 +201,10 @@ module.exports = { resourceUri: { type: 'string' }, accept: { type: 'string', optional: true }, webId: { type: 'string', optional: true }, - skipResourceCheck: { type: 'boolean', default: false }, + skipResourceCheck: { type: 'boolean', default: false } }, cache: { - keys: ['resourceUri', 'accept', 'webId', '#webId'], + keys: ['resourceUri', 'accept', 'webId', '#webId'] }, async handler(ctx) { let { resourceUri, webId, accept, skipResourceCheck } = ctx.params; @@ -216,6 +216,6 @@ module.exports = { const isContainer = !skipResourceCheck && (await this.checkResourceOrContainerExists(ctx, resourceUri)); return await getPermissions(ctx, resourceUri, this.settings.baseUrl, webId, this.settings.graphName, isContainer); - }, - }, + } + } }; diff --git a/src/middleware/packages/webacl/services/resource/actions/getUsersWithReadRights.js b/src/middleware/packages/webacl/services/resource/actions/getUsersWithReadRights.js index 8590b84b6..f7cd4b758 100644 --- a/src/middleware/packages/webacl/services/resource/actions/getUsersWithReadRights.js +++ b/src/middleware/packages/webacl/services/resource/actions/getUsersWithReadRights.js @@ -5,17 +5,17 @@ module.exports = { action: { visibility: 'public', params: { - resourceUri: { type: 'string' }, + resourceUri: { type: 'string' } }, async handler(ctx) { const { resourceUri } = ctx.params; const authorizations = await this.actions.getRights( { resourceUri, accept: MIME_TYPES.JSON, webId: 'system' }, - { parentCtx: ctx }, + { parentCtx: ctx } ); const readAuthorization = - authorizations['@graph'] && authorizations['@graph'].find((auth) => auth['@id'] === '#Read'); + authorizations['@graph'] && authorizations['@graph'].find(auth => auth['@id'] === '#Read'); let usersWithReadRights = []; @@ -30,6 +30,6 @@ module.exports = { } return usersWithReadRights; - }, - }, + } + } }; diff --git a/src/middleware/packages/webacl/services/resource/actions/hasRights.js b/src/middleware/packages/webacl/services/resource/actions/hasRights.js index 8cdcd7dd7..7faf704a8 100644 --- a/src/middleware/packages/webacl/services/resource/actions/hasRights.js +++ b/src/middleware/packages/webacl/services/resource/actions/hasRights.js @@ -5,14 +5,14 @@ const { getUserGroups, findParentContainers, getUserAgentSearchParam, - getAclUriFromResourceUri, + getAclUriFromResourceUri } = require('../../../utils'); const perms = { read: 'Read', write: 'Write', append: 'Append', - control: 'Control', + control: 'Control' }; async function checkRights( @@ -23,7 +23,7 @@ async function checkRights( resourceAclUri, uaSearchParam, graphName, - isContainerDefault, + isContainerDefault ) { for (const [p1, p2] of Object.entries(perms)) { if (askedRights[p1] && !resultRights[p1]) { @@ -33,7 +33,7 @@ async function checkRights( resourceAclUri, p2, graphName, - isContainerDefault, + isContainerDefault ); const hasPerm = checkAgentPresent(permTuples, uaSearchParam); if (hasPerm) resultRights[p1] = hasPerm; @@ -89,7 +89,7 @@ module.exports = { return await ctx.call('webacl.resource.hasRights', { resourceUri: urlJoin(this.settings.baseUrl, ...slugParts), rights: ctx.params.rights, - webId: ctx.meta.webId, + webId: ctx.meta.webId }); }, action: { @@ -104,17 +104,17 @@ module.exports = { read: { type: 'boolean', optional: true }, write: { type: 'boolean', optional: true }, append: { type: 'boolean', optional: true }, - control: { type: 'boolean', optional: true }, - }, + control: { type: 'boolean', optional: true } + } }, - webId: { type: 'string', optional: true }, + webId: { type: 'string', optional: true } }, cache: { enabled(ctx) { // Do not cache remote resources as we have no mecanism to clear this cache return ctx.params.resourceUri.startsWith(this.settings.baseUrl); }, - keys: ['resourceUri', 'rights', 'webId'], + keys: ['resourceUri', 'rights', 'webId'] }, async handler(ctx) { let { resourceUri, webId, rights } = ctx.params; @@ -124,6 +124,6 @@ module.exports = { await this.checkResourceOrContainerExists(ctx, resourceUri); return await hasPermissions(ctx, resourceUri, rights, this.settings.baseUrl, webId, this.settings.graphName); - }, - }, + } + } }; diff --git a/src/middleware/packages/webacl/services/resource/actions/removeRights.js b/src/middleware/packages/webacl/services/resource/actions/removeRights.js index e42eda7ef..0f383ee75 100644 --- a/src/middleware/packages/webacl/services/resource/actions/removeRights.js +++ b/src/middleware/packages/webacl/services/resource/actions/removeRights.js @@ -7,7 +7,7 @@ module.exports = { params: { resourceUri: { type: 'string', optional: false }, webId: { type: 'string', optional: true }, - rights: { type: 'object', optional: false }, + rights: { type: 'object', optional: false } }, async handler(ctx) { let { resourceUri, rights, webId } = ctx.params; @@ -20,7 +20,7 @@ module.exports = { const { control } = await ctx.call('webacl.resource.hasRights', { resourceUri, rights: { control: true }, - webId, + webId }); if (!control) throw new MoleculerError('Access denied ! user must have Control permission', 403, 'ACCESS_DENIED'); @@ -37,29 +37,29 @@ module.exports = { PREFIX acl: DELETE DATA { GRAPH <${this.settings.graphName}> { - ${processedRights.map((right) => `<${right.auth}> <${right.p}> <${right.o}> .`).join('\n')} + ${processedRights.map(right => `<${right.auth}> <${right.p}> <${right.o}> .`).join('\n')} } } `, - webId: 'system', + webId: 'system' }); - const defaultRightsUpdated = isContainer && processedRights.some((triple) => triple.auth.includes('#Default')); + const defaultRightsUpdated = isContainer && processedRights.some(triple => triple.auth.includes('#Default')); const removePublicRead = processedRights.some( - (triple) => triple.auth.includes('#Read') && triple.p === FULL_AGENTCLASS_URI && triple.o === FULL_FOAF_AGENT, + triple => triple.auth.includes('#Read') && triple.p === FULL_AGENTCLASS_URI && triple.o === FULL_FOAF_AGENT ); const removeDefaultPublicRead = isContainer && processedRights.some( - (triple) => - triple.auth.includes('#DefaultRead') && triple.p === FULL_AGENTCLASS_URI && triple.o === FULL_FOAF_AGENT, + triple => + triple.auth.includes('#DefaultRead') && triple.p === FULL_AGENTCLASS_URI && triple.o === FULL_FOAF_AGENT ); ctx.emit( 'webacl.resource.updated', { uri: resourceUri, webId, isContainer, defaultRightsUpdated, removePublicRead, removeDefaultPublicRead }, - { meta: { webId: null, dataset: null } }, + { meta: { webId: null, dataset: null } } ); - }, - }, + } + } }; diff --git a/src/middleware/packages/webacl/services/resource/actions/setRights.js b/src/middleware/packages/webacl/services/resource/actions/setRights.js index 0ee8cd7b2..cdd2467c8 100644 --- a/src/middleware/packages/webacl/services/resource/actions/setRights.js +++ b/src/middleware/packages/webacl/services/resource/actions/setRights.js @@ -6,7 +6,7 @@ const { convertBodyToTriples, filterTriplesForResource, FULL_AGENTCLASS_URI, - FULL_FOAF_AGENT, + FULL_FOAF_AGENT } = require('../../../utils'); module.exports = { @@ -25,7 +25,7 @@ module.exports = { await ctx.call('webacl.resource.setRights', { resourceUri: urlJoin(this.settings.baseUrl, ...slugParts), - newRights, + newRights }); ctx.meta.$statusCode = 204; @@ -36,7 +36,7 @@ module.exports = { resourceUri: { type: 'string' }, webId: { type: 'string', optional: true }, // newRights is an array of objects of the form { auth: 'http://localhost:3000/_acl/container29#Control', p: 'http://www.w3.org/ns/auth/acl#agent', o: 'https://data.virtual-assembly.org/users/sebastien.rosset' } - newRights: { type: 'array', optional: false, min: 1 }, + newRights: { type: 'array', optional: false, min: 1 } // minimum is one right : We cannot leave a resource without rights. }, async handler(ctx) { @@ -50,13 +50,13 @@ module.exports = { const { control } = await ctx.call('webacl.resource.hasRights', { resourceUri, rights: { control: true }, - webId, + webId }); if (!control) throw new MoleculerError('Access denied ! user must have Control permission', 403, 'ACCESS_DENIED'); // filter out all the newRights that are not for the resource const aclUri = getAclUriFromResourceUri(this.settings.baseUrl, resourceUri); - newRights = newRights.filter((a) => filterTriplesForResource(a, aclUri, isContainer)); + newRights = newRights.filter(a => filterTriplesForResource(a, aclUri, isContainer)); if (newRights.length === 0) throw new MoleculerError('The rights cannot be changed because they are incorrect', 400, 'BAD_REQUEST'); @@ -66,15 +66,15 @@ module.exports = { resourceUri, this.settings.baseUrl, this.settings.graphName, - isContainer, + isContainer ); // find the difference between newRights and currentPerms. add only what is not existent yet. and remove those that are not needed anymore const differenceAdd = newRights.filter( - (x) => !currentPerms.some((y) => x.auth === y.auth && x.o === y.o && x.p === y.p), + x => !currentPerms.some(y => x.auth === y.auth && x.o === y.o && x.p === y.p) ); const differenceDelete = currentPerms.filter( - (x) => !newRights.some((y) => x.auth === y.auth && x.o === y.o && x.p === y.p), + x => !newRights.some(y => x.auth === y.auth && x.o === y.o && x.p === y.p) ); if (differenceAdd.length === 0 && differenceDelete.length === 0) return; @@ -108,31 +108,31 @@ module.exports = { // we do the 2 calls in one, so it is in the same transaction, and will rollback in case of failure. await ctx.call('triplestore.update', { query: `INSERT DATA { GRAPH <${this.settings.graphName}> { ${addRequest} } }; DELETE DATA { GRAPH <${this.settings.graphName}> { ${deleteRequest} } }`, - webId: 'system', + webId: 'system' }); const defaultRightsUpdated = isContainer && - (differenceAdd.some((triple) => triple.auth.includes('#Default')) || - differenceDelete.some((triple) => triple.auth.includes('#Default'))); + (differenceAdd.some(triple => triple.auth.includes('#Default')) || + differenceDelete.some(triple => triple.auth.includes('#Default'))); const addPublicRead = differenceAdd.some( - (triple) => triple.auth.includes('#Read') && triple.p === FULL_AGENTCLASS_URI && triple.o === FULL_FOAF_AGENT, + triple => triple.auth.includes('#Read') && triple.p === FULL_AGENTCLASS_URI && triple.o === FULL_FOAF_AGENT ); const removePublicRead = differenceDelete.some( - (triple) => triple.auth.includes('#Read') && triple.p === FULL_AGENTCLASS_URI && triple.o === FULL_FOAF_AGENT, + triple => triple.auth.includes('#Read') && triple.p === FULL_AGENTCLASS_URI && triple.o === FULL_FOAF_AGENT ); const addDefaultPublicRead = isContainer && differenceAdd.some( - (triple) => - triple.auth.includes('#DefaultRead') && triple.p === FULL_AGENTCLASS_URI && triple.o === FULL_FOAF_AGENT, + triple => + triple.auth.includes('#DefaultRead') && triple.p === FULL_AGENTCLASS_URI && triple.o === FULL_FOAF_AGENT ); const removeDefaultPublicRead = isContainer && differenceDelete.some( - (triple) => - triple.auth.includes('#DefaultRead') && triple.p === FULL_AGENTCLASS_URI && triple.o === FULL_FOAF_AGENT, + triple => + triple.auth.includes('#DefaultRead') && triple.p === FULL_AGENTCLASS_URI && triple.o === FULL_FOAF_AGENT ); const returnValues = { @@ -144,10 +144,10 @@ module.exports = { addPublicRead, removePublicRead, addDefaultPublicRead, - removeDefaultPublicRead, + removeDefaultPublicRead }; ctx.emit('webacl.resource.updated', returnValues, { meta: { webId: null, dataset: null } }); return returnValues; - }, - }, + } + } }; diff --git a/src/middleware/packages/webacl/services/resource/index.js b/src/middleware/packages/webacl/services/resource/index.js index cc3f7c232..f31385cb7 100644 --- a/src/middleware/packages/webacl/services/resource/index.js +++ b/src/middleware/packages/webacl/services/resource/index.js @@ -20,17 +20,17 @@ const { FULL_MODE_URI, FULL_TYPE_URI, ACL_NS, - getDatasetFromUri, + getDatasetFromUri } = require('../../utils'); -const filterAclsOnlyAgent = (acl) => agentPredicates.includes(acl.p.value); +const filterAclsOnlyAgent = acl => agentPredicates.includes(acl.p.value); module.exports = { name: 'webacl.resource', settings: { baseUrl: null, graphName: null, - podProvider: false, + podProvider: false }, dependencies: ['triplestore', 'jsonld'], actions: { @@ -48,7 +48,7 @@ module.exports = { api_addRights: addRights.api, api_hasRights: hasRights.api, api_getRights: getRights.api, - api_setRights: setRights.api, + api_setRights: setRights.api }, hooks: { before: { @@ -56,8 +56,8 @@ module.exports = { if (this.settings.podProvider && !ctx.meta.dataset && ctx.params.resourceUri) { ctx.meta.dataset = getDatasetFromUri(ctx.params.resourceUri); } - }, - }, + } + } }, methods: { // will return true if it is a container, false otherwise @@ -81,7 +81,7 @@ module.exports = { throw new MoleculerError( `Cannot get permissions of non-existing container or resource ${resourceUri} (webId ${ctx.meta.webId} / dataset ${ctx.meta.dataset})`, 404, - 'NOT_FOUND', + 'NOT_FOUND' ); } return false; @@ -106,8 +106,8 @@ module.exports = { } return document - .filter((a) => filterAclsOnlyAgent(a)) - .map((a) => { + .filter(a => filterAclsOnlyAgent(a)) + .map(a => { return { auth: a.auth.value, p: a.p.value, o: a.o.value }; }); }, @@ -127,6 +127,6 @@ module.exports = { cmd += `<${auth}> <${FULL_MODE_URI}> <${ACL_NS}${mode}>.\n`; cmd += `<${auth}> <${defaultAcl ? FULL_DEFAULT_URI : FULL_ACCESSTO_URI}> <${resUrl}>.\n`; return cmd; - }, - }, + } + } }; diff --git a/src/middleware/packages/webacl/utils.js b/src/middleware/packages/webacl/utils.js index 4c2c100f9..b1562b797 100644 --- a/src/middleware/packages/webacl/utils.js +++ b/src/middleware/packages/webacl/utils.js @@ -5,15 +5,15 @@ const { Parser } = require('n3'); const streamifyString = require('streamify-string'); const rdfParser = require('rdf-parse').default; -const RESOURCE_CONTAINERS_QUERY = (resource) => `SELECT ?container +const RESOURCE_CONTAINERS_QUERY = resource => `SELECT ?container WHERE { ?container ldp:contains <${resource}> . }`; -const getSlugFromUri = (str) => str.match(new RegExp(`.*/(.*)`))[1]; +const getSlugFromUri = str => str.match(new RegExp(`.*/(.*)`))[1]; -const getContainerFromUri = (str) => str.match(new RegExp(`(.*)/.*`))[1]; +const getContainerFromUri = str => str.match(new RegExp(`(.*)/.*`))[1]; // Transforms "http://localhost:3000/dataset/data" to "dataset" -const getDatasetFromUri = (uri) => { +const getDatasetFromUri = uri => { const path = new URL(uri).pathname; const parts = path.split('/'); if (parts.length > 1) return parts[1]; @@ -25,7 +25,7 @@ const findParentContainers = async (ctx, resource) => { return await ctx.call('triplestore.query', { query, accept: MIME_TYPES.SPARQL_JSON, - webId: 'system', + webId: 'system' }); }; @@ -55,10 +55,10 @@ const getUserGroups = async (ctx, user, graphName) => { const groups = await ctx.call('triplestore.query', { query, accept: MIME_TYPES.JSON, - webId: 'system', + webId: 'system' }); - return groups.map((g) => g.group.value); + return groups.map(g => g.group.value); }; const AUTHORIZATION_NODE_QUERY = (mode, accesToOrDefault, resource, graphName) => `SELECT ?auth ?p ?o @@ -75,16 +75,16 @@ const getAuthorizationNode = async (ctx, resourceUri, resourceAclUri, mode, grap mode, seachForDefault ? 'default' : 'accessTo', resourceUri, - graphName, + graphName )}`; const auths = await ctx.call('triplestore.query', { query, accept: MIME_TYPES.JSON, - webId: 'system', + webId: 'system' }); - return auths.map((a) => { + return auths.map(a => { a.auth.value = `${resourceAclUri}#${seachForDefault ? 'Default' : ''}${mode}`; return a; }); @@ -132,19 +132,19 @@ const filterAgentAcl = (acl, agentSearchParam, forOutput) => { function getUserAgentSearchParam(user, groups) { if (user === 'anon') { return { - foafAgent: true, + foafAgent: true }; } if (user === 'system') { return { - system: true, + system: true }; } return { foafAgent: true, authAgent: true, webId: user, - groups: groups, + groups: groups }; } @@ -167,7 +167,7 @@ async function aclGroupExists(groupUri, ctx, graphName) { <${groupUri}> a vcard:Group . } } `, - webId: 'system', + webId: 'system' }); } @@ -182,7 +182,7 @@ function filterAndConvertTriple(quad, property) { return { auth: quad.subject[property], p: quad.predicate[property], - o: quad.object[property], + o: quad.object[property] }; } return false; @@ -220,13 +220,13 @@ async function convertBodyToTriples(body, contentType) { const res = []; rdfParser .parse(textStream, { - contentType: 'application/ld+json', + contentType: 'application/ld+json' }) - .on('data', (quad) => { + .on('data', quad => { const q = filterAndConvertTriple(quad, 'value'); if (q) res.push(q); }) - .on('error', (error) => reject(error)) + .on('error', error => reject(error)) .on('end', () => { resolve(res); }); @@ -241,7 +241,7 @@ async function removeAgentGroupOrAgentFromAuthorizations(uri, isGroup, graphName await ctx.call('triplestore.update', { query: `PREFIX acl: DELETE WHERE { GRAPH <${graphName}> { ?auth ${isGroup ? 'acl:agentGroup' : 'acl:agent'} <${uri}> }}`, - webId: 'system', + webId: 'system' }); // removing the Authorizations that are now empty @@ -254,7 +254,7 @@ async function removeAgentGroupOrAgentFromAuthorizations(uri, isGroup, graphName FILTER NOT EXISTS { ?auth acl:agentGroup ?z2 } FILTER NOT EXISTS { ?auth acl:agentClass ?z3 } }`, - webId: 'system', + webId: 'system' }); } @@ -329,5 +329,5 @@ module.exports = { FULL_AGENT_GROUP, FULL_FOAF_AGENT, FULL_ACL_ANYAGENT, - isRemoteUri, + isRemoteUri }; diff --git a/src/middleware/packages/webhooks/service.js b/src/middleware/packages/webhooks/service.js index 359175c20..ff44837f6 100644 --- a/src/middleware/packages/webhooks/service.js +++ b/src/middleware/packages/webhooks/service.js @@ -10,11 +10,11 @@ const WebhooksService = { settings: { containerUri: null, allowedActions: [], - context: { '@vocab': 'http://semapps.org/ns/core#' }, + context: { '@vocab': 'http://semapps.org/ns/core#' } }, dependencies: ['api'], async started() { - this.settings.allowedActions.forEach((actionName) => { + this.settings.allowedActions.forEach(actionName => { if (!this.actions[actionName]) { throw new ServiceSchemaError(`Missing action "${actionName}" in service settings!`); } @@ -22,7 +22,7 @@ const WebhooksService = { const routes = await this.actions.getApiRoutes(); for (const route of routes) { await this.broker.call('api.addRoute', { - route, + route }); } }, @@ -56,9 +56,9 @@ const WebhooksService = { { '@type': 'Webhook', action, - user: userUri, + user: userUri }, - { parentCtx: ctx }, + { parentCtx: ctx } ); return webhook['@id']; @@ -73,8 +73,8 @@ const WebhooksService = { authorization: false, authentication: true, aliases: { - 'POST /:hash': 'webhooks.process', - }, + 'POST /:hash': 'webhooks.process' + } }, // Secured routes { @@ -84,11 +84,11 @@ const WebhooksService = { authorization: true, authentication: false, aliases: { - 'POST /': 'webhooks.generate', - }, - }, + 'POST /': 'webhooks.generate' + } + } ]; - }, + } }, queues: { webhooks: { @@ -99,11 +99,11 @@ const WebhooksService = { job.progress(100); return { - result, + result }; - }, - }, - }, + } + } + } }; module.exports = WebhooksService; diff --git a/src/middleware/packages/webid/service.js b/src/middleware/packages/webid/service.js index 012d1ba1e..68fe49cff 100644 --- a/src/middleware/packages/webid/service.js +++ b/src/middleware/packages/webid/service.js @@ -7,10 +7,10 @@ const WebIdService = { baseUrl: null, usersContainer: null, context: { - foaf: 'http://xmlns.com/foaf/0.1/', + foaf: 'http://xmlns.com/foaf/0.1/' }, defaultAccept: 'text/turtle', - podProvider: false, + podProvider: false }, dependencies: ['ldp.resource'], actions: { @@ -28,14 +28,14 @@ const WebIdService = { const resource = { '@context': { - '@vocab': 'http://xmlns.com/foaf/0.1/', + '@vocab': 'http://xmlns.com/foaf/0.1/' }, '@type': 'Person', nick, email, name, familyName, - homepage, + homepage }; // Create profile with system webId @@ -45,10 +45,10 @@ const WebIdService = { await ctx.call('ldp.resource.create', { resource: { '@id': webId, - ...resource, + ...resource }, contentType: MIME_TYPES.JSON, - webId: 'system', + webId: 'system' }); } else { if (!this.settings.usersContainer) throw new Error('The usersContainer setting is required'); @@ -57,7 +57,7 @@ const WebIdService = { slug: nick, containerUri: this.settings.usersContainer, contentType: MIME_TYPES.JSON, - webId: 'system', + webId: 'system' }); } @@ -65,7 +65,7 @@ const WebIdService = { resourceUri: webId, accept: MIME_TYPES.JSON, jsonContext: this.settings.context, - webId: 'system', + webId: 'system' }); ctx.emit('webid.created', newPerson, { meta: { webId: null, dataset: null } }); @@ -79,7 +79,7 @@ const WebIdService = { resourceUri: webId, accept: MIME_TYPES.JSON, jsonContext: this.settings.context, - webId, + webId }); } ctx.meta.$statusCode = 404; @@ -90,17 +90,17 @@ const WebIdService = { return await ctx.call('ldp.resource.put', { resource: { '@context': { - '@vocab': 'http://xmlns.com/foaf/0.1/', + '@vocab': 'http://xmlns.com/foaf/0.1/' }, '@type': 'Person', '@id': webId, - ...profileData, + ...profileData }, webId, contentType: MIME_TYPES.JSON, - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); - }, + } }, methods: { async getWebId(ctx) { @@ -112,10 +112,10 @@ const WebIdService = { return ctx.meta.webId || ctx.meta.tokenPayload.webId; } throw new Error( - 'webid.getWebId have to be call with ctx.params.userId or ctx.meta.webId or ctx.meta.tokenPayload.webId', + 'webid.getWebId have to be call with ctx.params.userId or ctx.meta.webId or ctx.meta.tokenPayload.webId' ); - }, - }, + } + } }; module.exports = WebIdService; diff --git a/src/middleware/tests/activitypub/collection.test.js b/src/middleware/tests/activitypub/collection.test.js index 4c1eaab6e..c55081727 100644 --- a/src/middleware/tests/activitypub/collection.test.js +++ b/src/middleware/tests/activitypub/collection.test.js @@ -28,10 +28,10 @@ describe('Handle collections', () => { '@type': 'Note', name: `Note #${i}`, content: `Contenu de ma note #${i}`, - published: `2021-01-0${i}T00:00:00.000Z`, + published: `2021-01-0${i}T00:00:00.000Z` }, - contentType: MIME_TYPES.JSON, - }), + contentType: MIME_TYPES.JSON + }) ); } expect(items).toHaveLength(10); @@ -41,11 +41,11 @@ describe('Handle collections', () => { await broker.call('activitypub.collection.create', { collectionUri, ordered: false, - summary: 'My non-ordered collection', + summary: 'My non-ordered collection' }); const collectionExist = await broker.call('activitypub.collection.exist', { - collectionUri, + collectionUri }); expect(collectionExist).toBeTruthy(); @@ -57,7 +57,7 @@ describe('Handle collections', () => { type: 'Collection', summary: 'My non-ordered collection', items: [], - totalItems: 0, + totalItems: 0 }); }); @@ -65,18 +65,18 @@ describe('Handle collections', () => { await broker.call('activitypub.collection.create', { collectionUri: orderedCollectionUri, ordered: true, - summary: 'My ordered collection', + summary: 'My ordered collection' }); const collectionExist = await broker.call('activitypub.collection.exist', { - collectionUri: orderedCollectionUri, + collectionUri: orderedCollectionUri }); expect(collectionExist).toBeTruthy(); const collection = await broker.call('activitypub.collection.get', { collectionUri: orderedCollectionUri, - sort: { predicate: 'as:published', order: 'DESC' }, + sort: { predicate: 'as:published', order: 'DESC' } }); expect(collection).toMatchObject({ @@ -84,18 +84,18 @@ describe('Handle collections', () => { type: 'OrderedCollection', summary: 'My ordered collection', orderedItems: [], - totalItems: 0, + totalItems: 0 }); }); test('Attach item to collection', async () => { await broker.call('activitypub.collection.attach', { collectionUri, - item: items[0], + item: items[0] }); let collection = await broker.call('activitypub.collection.get', { - collectionUri, + collectionUri }); expect(collection).toMatchObject({ @@ -103,12 +103,12 @@ describe('Handle collections', () => { type: 'Collection', summary: 'My non-ordered collection', items: [items[0]], - totalItems: 1, + totalItems: 1 }); collection = await broker.call('activitypub.collection.get', { collectionUri, - dereferenceItems: true, + dereferenceItems: true }); expect(collection).toMatchObject({ @@ -120,21 +120,21 @@ describe('Handle collections', () => { id: items[0], type: 'Note', content: 'Contenu de ma note #0', - name: 'Note #0', - }, + name: 'Note #0' + } ], - totalItems: 1, + totalItems: 1 }); }); test('Detach item from collection', async () => { await broker.call('activitypub.collection.detach', { collectionUri, - item: items[0], + item: items[0] }); const collection = await broker.call('activitypub.collection.get', { - collectionUri, + collectionUri }); expect(collection).toMatchObject({ @@ -142,51 +142,51 @@ describe('Handle collections', () => { type: 'Collection', summary: 'My non-ordered collection', items: [], - totalItems: 0, + totalItems: 0 }); }); test('Handle order', async () => { await broker.call('activitypub.collection.attach', { collectionUri: orderedCollectionUri, - item: items[4], + item: items[4] }); await broker.call('activitypub.collection.attach', { collectionUri: orderedCollectionUri, - item: items[0], + item: items[0] }); await broker.call('activitypub.collection.attach', { collectionUri: orderedCollectionUri, - item: items[2], + item: items[2] }); await broker.call('activitypub.collection.attach', { collectionUri: orderedCollectionUri, - item: items[6], + item: items[6] }); let collection = await broker.call('activitypub.collection.get', { collectionUri: orderedCollectionUri, - sort: { predicate: 'as:published', order: 'DESC' }, + sort: { predicate: 'as:published', order: 'DESC' } }); expect(collection).toMatchObject({ id: orderedCollectionUri, orderedItems: [items[6], items[4], items[2], items[0]], - totalItems: 4, + totalItems: 4 }); collection = await broker.call('activitypub.collection.get', { collectionUri: orderedCollectionUri, - sort: { predicate: 'as:published', order: 'ASC' }, + sort: { predicate: 'as:published', order: 'ASC' } }); expect(collection).toMatchObject({ id: orderedCollectionUri, orderedItems: [items[0], items[2], items[4], items[6]], - totalItems: 4, + totalItems: 4 }); }); @@ -194,26 +194,26 @@ describe('Handle collections', () => { for (let i = 0; i < 10; i++) { await broker.call('activitypub.collection.attach', { collectionUri, - item: items[i], + item: items[i] }); } let collection = await broker.call('activitypub.collection.get', { collectionUri, - itemsPerPage: 4, + itemsPerPage: 4 }); expect(collection).toMatchObject({ id: collectionUri, first: `${collectionUri}?page=1`, last: `${collectionUri}?page=3`, - totalItems: 10, + totalItems: 10 }); collection = await broker.call('activitypub.collection.get', { collectionUri, itemsPerPage: 4, - page: 1, + page: 1 }); expect(collection).toMatchObject({ @@ -222,7 +222,7 @@ describe('Handle collections', () => { partOf: collectionUri, prev: undefined, next: `${collectionUri}?page=2`, - totalItems: 10, + totalItems: 10 }); expect(collection.items).toHaveLength(4); }); diff --git a/src/middleware/tests/activitypub/follow.test.js b/src/middleware/tests/activitypub/follow.test.js index 529550104..92344a775 100644 --- a/src/middleware/tests/activitypub/follow.test.js +++ b/src/middleware/tests/activitypub/follow.test.js @@ -6,7 +6,7 @@ jest.setTimeout(50000); const NUM_USERS = 2; -describe.each(['single-server', 'multi-server'])('In mode %s, posting to followers', (mode) => { +describe.each(['single-server', 'multi-server'])('In mode %s, posting to followers', mode => { let broker; const actors = []; let alice; @@ -53,12 +53,12 @@ describe.each(['single-server', 'multi-server'])('In mode %s, posting to followe actor: bob.id, type: ACTIVITY_TYPES.FOLLOW, object: alice.id, - to: [alice.id, `${bob.id}/followers`], + to: [alice.id, `${bob.id}/followers`] }); await waitForExpect(async () => { await expect( - alice.call('activitypub.collection.includes', { collectionUri: alice.followers, itemUri: bob.id }), + alice.call('activitypub.collection.includes', { collectionUri: alice.followers, itemUri: bob.id }) ).resolves.toBeTruthy(); }); @@ -66,14 +66,14 @@ describe.each(['single-server', 'multi-server'])('In mode %s, posting to followe const inbox = await bob.call('activitypub.collection.get', { collectionUri: bob.inbox, page: 1, - webId: bob.id, + webId: bob.id }); expect(inbox).not.toBeNull(); expect(inbox.orderedItems).toHaveLength(1); expect(inbox.orderedItems[0]).toMatchObject({ type: ACTIVITY_TYPES.ACCEPT, actor: alice.id, - object: followActivity.id, + object: followActivity.id }); }); }); @@ -86,28 +86,28 @@ describe.each(['single-server', 'multi-server'])('In mode %s, posting to followe name: 'Hello World', attributedTo: alice.id, to: [alice.followers], - content: 'My first message, happy to be part of the fediverse !', + content: 'My first message, happy to be part of the fediverse !' }); expect(createActivity).toMatchObject({ type: ACTIVITY_TYPES.CREATE, object: { type: OBJECT_TYPES.NOTE, - name: 'Hello World', - }, + name: 'Hello World' + } }); await waitForExpect(async () => { const inbox = await bob.call('activitypub.collection.get', { collectionUri: bob.inbox, page: 1, - webId: bob.id, + webId: bob.id }); expect(inbox).not.toBeNull(); expect(inbox.orderedItems).toHaveLength(2); expect(inbox.orderedItems[0]).toMatchObject({ - id: createActivity.id, + id: createActivity.id }); }); }); @@ -119,12 +119,12 @@ describe.each(['single-server', 'multi-server'])('In mode %s, posting to followe actor: bob.id, type: ACTIVITY_TYPES.UNDO, object: followActivity.id, - to: [alice.id, `${bob.id}/followers`], + to: [alice.id, `${bob.id}/followers`] }); await waitForExpect(async () => { await expect( - alice.call('activitypub.collection.includes', { collectionUri: alice.followers, itemUri: bob.id }), + alice.call('activitypub.collection.includes', { collectionUri: alice.followers, itemUri: bob.id }) ).resolves.toBeFalsy(); }); }); diff --git a/src/middleware/tests/activitypub/inbox.test.js b/src/middleware/tests/activitypub/inbox.test.js index 721b6ac86..eafbb5e73 100644 --- a/src/middleware/tests/activitypub/inbox.test.js +++ b/src/middleware/tests/activitypub/inbox.test.js @@ -24,7 +24,7 @@ describe('Permissions are correctly set on inbox', () => { username: 'srosset81', email: 'sebastien@test.com', password: 'test', - name: 'Sébastien', + name: 'Sébastien' }); sebastien = await broker.call('activitypub.actor.awaitCreateComplete', { actorUri: sebastienUri }); @@ -33,7 +33,7 @@ describe('Permissions are correctly set on inbox', () => { username: 'simonlouvet', email: 'simon@test.com', password: 'test', - name: 'Simon', + name: 'Simon' }); simon = await broker2.call('activitypub.actor.awaitCreateComplete', { actorUri: simonUri }); @@ -46,7 +46,7 @@ describe('Permissions are correctly set on inbox', () => { inbox: `${sebastienUri}/inbox`, outbox: `${sebastienUri}/outbox`, followers: `${sebastienUri}/followers`, - following: `${sebastienUri}/following`, + following: `${sebastienUri}/following` }); }); @@ -56,7 +56,7 @@ describe('Permissions are correctly set on inbox', () => { '@context': 'https://www.w3.org/ns/activitystreams', type: OBJECT_TYPES.NOTE, name: 'Private message to friend', - to: simon.id, + to: simon.id }); // Get inbox as recipient @@ -64,7 +64,7 @@ describe('Permissions are correctly set on inbox', () => { const outbox = await broker.call('activitypub.collection.get', { collectionUri: simon.inbox, page: 1, - webId: simon.id, + webId: simon.id }); expect(outbox.orderedItems).toHaveLength(1); expect(outbox.orderedItems[0]).toMatchObject({ @@ -72,8 +72,8 @@ describe('Permissions are correctly set on inbox', () => { type: ACTIVITY_TYPES.CREATE, object: { type: OBJECT_TYPES.NOTE, - name: 'Private message to friend', - }, + name: 'Private message to friend' + } }); }); @@ -82,7 +82,7 @@ describe('Permissions are correctly set on inbox', () => { const outbox = await broker.call('activitypub.collection.get', { collectionUri: simon.inbox, page: 1, - webId: sebastien.id, + webId: sebastien.id }); expect(outbox.orderedItems).toHaveLength(1); expect(outbox.orderedItems[0]).toMatchObject({ @@ -90,8 +90,8 @@ describe('Permissions are correctly set on inbox', () => { type: ACTIVITY_TYPES.CREATE, object: { type: OBJECT_TYPES.NOTE, - name: 'Private message to friend', - }, + name: 'Private message to friend' + } }); }); @@ -100,7 +100,7 @@ describe('Permissions are correctly set on inbox', () => { const outbox = await broker.call('activitypub.collection.get', { collectionUri: sebastien.inbox, page: 1, - webId: 'anon', + webId: 'anon' }); expect(outbox.totalItems).toBe(0); }); @@ -112,7 +112,7 @@ describe('Permissions are correctly set on inbox', () => { '@context': 'https://www.w3.org/ns/activitystreams', type: OBJECT_TYPES.NOTE, name: 'Public message', - to: [PUBLIC_URI, simon.id], + to: [PUBLIC_URI, simon.id] }); // Get inbox as recipient @@ -120,7 +120,7 @@ describe('Permissions are correctly set on inbox', () => { const outbox = await broker.call('activitypub.collection.get', { collectionUri: simon.inbox, page: 1, - webId: simon.id, + webId: simon.id }); expect(outbox.orderedItems).toHaveLength(2); expect(outbox.orderedItems[0]).toMatchObject({ @@ -128,8 +128,8 @@ describe('Permissions are correctly set on inbox', () => { type: ACTIVITY_TYPES.CREATE, object: { type: OBJECT_TYPES.NOTE, - name: 'Public message', - }, + name: 'Public message' + } }); }); @@ -138,7 +138,7 @@ describe('Permissions are correctly set on inbox', () => { const outbox = await broker.call('activitypub.collection.get', { collectionUri: simon.inbox, page: 1, - webId: sebastien.id, + webId: sebastien.id }); expect(outbox.orderedItems).toHaveLength(2); expect(outbox.orderedItems[0]).toMatchObject({ @@ -146,8 +146,8 @@ describe('Permissions are correctly set on inbox', () => { type: ACTIVITY_TYPES.CREATE, object: { type: OBJECT_TYPES.NOTE, - name: 'Public message', - }, + name: 'Public message' + } }); }); @@ -156,7 +156,7 @@ describe('Permissions are correctly set on inbox', () => { const outbox = await broker.call('activitypub.collection.get', { collectionUri: simon.inbox, page: 1, - webId: 'anon', + webId: 'anon' }); expect(outbox.orderedItems).toHaveLength(1); expect(outbox.orderedItems[0]).toMatchObject({ @@ -164,8 +164,8 @@ describe('Permissions are correctly set on inbox', () => { type: ACTIVITY_TYPES.CREATE, object: { type: OBJECT_TYPES.NOTE, - name: 'Public message', - }, + name: 'Public message' + } }); }); }); diff --git a/src/middleware/tests/activitypub/initialize.js b/src/middleware/tests/activitypub/initialize.js index 0c3392a9e..a8bf2cd5b 100644 --- a/src/middleware/tests/activitypub/initialize.js +++ b/src/middleware/tests/activitypub/initialize.js @@ -17,9 +17,9 @@ const initialize = async (port, mainDataset, accountsDataset) => { logger: { type: 'Console', options: { - level: 'error', - }, - }, + level: 'error' + } + } }); // Remove all actors keys @@ -33,29 +33,29 @@ const initialize = async (port, mainDataset, accountsDataset) => { url: CONFIG.SPARQL_ENDPOINT, user: CONFIG.JENA_USER, password: CONFIG.JENA_PASSWORD, - mainDataset, + mainDataset }, containers, void: false, mirror: false, api: { - port, - }, - }, + port + } + } }); await broker.createService(AuthLocalService, { settings: { baseUrl, jwtPath: path.resolve(__dirname, './jwt'), - accountsDataset, - }, + accountsDataset + } }); broker.createService(WebIdService, { settings: { - usersContainer: `${baseUrl}actors/`, - }, + usersContainer: `${baseUrl}actors/` + } }); // Drop all existing triples, then restart broker so that default containers are recreated @@ -71,27 +71,27 @@ const initialize = async (port, mainDataset, accountsDataset) => { resourceUri: `${baseUrl}objects`, additionalRights: { anon: { - write: true, - }, - }, + write: true + } + } }); await broker.call('webacl.resource.addRights', { webId: 'system', resourceUri: `${baseUrl}actors`, additionalRights: { anon: { - write: true, - }, - }, + write: true + } + } }); await broker.call('webacl.resource.addRights', { webId: 'system', resourceUri: `${baseUrl}activities`, additionalRights: { anon: { - write: true, - }, - }, + write: true + } + } }); return broker; diff --git a/src/middleware/tests/activitypub/object.test.js b/src/middleware/tests/activitypub/object.test.js index 267e9f0a9..9b0eeb215 100644 --- a/src/middleware/tests/activitypub/object.test.js +++ b/src/middleware/tests/activitypub/object.test.js @@ -24,7 +24,7 @@ describe('Create/Update/Delete objects', () => { username: 'srosset81', email: 'sebastien@test.com', password: 'test', - name: 'Sébastien', + name: 'Sébastien' }); sebastien = await broker.call('activitypub.actor.awaitCreateComplete', { actorUri: sebastienUri }); @@ -40,7 +40,7 @@ describe('Create/Update/Delete objects', () => { name: 'My first article', attributedTo: sebastien.id, to: sebastien.followers, - content: 'My first article, I hope there is no tipo', + content: 'My first article, I hope there is no tipo' }); expect(createActivity).toMatchObject({ @@ -49,9 +49,9 @@ describe('Create/Update/Delete objects', () => { object: { type: OBJECT_TYPES.ARTICLE, name: 'My first article', - content: 'My first article, I hope there is no tipo', + content: 'My first article, I hope there is no tipo' }, - to: sebastien.followers, + to: sebastien.followers }); expect(createActivity.object).toHaveProperty('id'); @@ -59,7 +59,7 @@ describe('Create/Update/Delete objects', () => { await waitForExpect(async () => { await expect( - broker.call('activitypub.collection.includes', { collectionUri: sebastien.outbox, itemUri: createActivity.id }), + broker.call('activitypub.collection.includes', { collectionUri: sebastien.outbox, itemUri: createActivity.id }) ).resolves.toBeTruthy(); }); @@ -68,7 +68,7 @@ describe('Create/Update/Delete objects', () => { // Check the object has been created in the container const object = await broker.call('ldp.resource.get', { resourceUri: objectUri, - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(object).toHaveProperty('type', OBJECT_TYPES.ARTICLE); expect(object).toHaveProperty('id', objectUri); @@ -83,9 +83,9 @@ describe('Create/Update/Delete objects', () => { object: { id: objectUri, type: OBJECT_TYPES.ARTICLE, - content: 'My first article, I hope there is no typo', + content: 'My first article, I hope there is no typo' }, - to: sebastien.followers, + to: sebastien.followers }); expect(updateActivity).toMatchObject({ @@ -94,9 +94,9 @@ describe('Create/Update/Delete objects', () => { object: { id: objectUri, type: OBJECT_TYPES.ARTICLE, - content: 'My first article, I hope there is no typo', + content: 'My first article, I hope there is no typo' }, - to: sebastien.followers, + to: sebastien.followers }); expect(updateActivity.object).not.toHaveProperty('current'); expect(updateActivity.object).not.toHaveProperty('name'); @@ -104,12 +104,12 @@ describe('Create/Update/Delete objects', () => { // Check the object has been updated const object = await broker.call('ldp.resource.get', { resourceUri: objectUri, - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(object).toMatchObject({ id: objectUri, type: OBJECT_TYPES.ARTICLE, - content: 'My first article, I hope there is no typo', + content: 'My first article, I hope there is no typo' }); }); @@ -118,15 +118,15 @@ describe('Create/Update/Delete objects', () => { collectionUri: sebastien.outbox, '@context': 'https://www.w3.org/ns/activitystreams', type: ACTIVITY_TYPES.DELETE, - object: objectUri, + object: objectUri }); await waitForExpect(async () => { await expect( broker.call('ldp.resource.get', { resourceUri: objectUri, - accept: MIME_TYPES.JSON, - }), + accept: MIME_TYPES.JSON + }) ).rejects.toThrow(`Cannot get permissions of non-existing container or resource ${objectUri}`); }); }); diff --git a/src/middleware/tests/activitypub/outbox.test.js b/src/middleware/tests/activitypub/outbox.test.js index 2f0a76e71..eee49899d 100644 --- a/src/middleware/tests/activitypub/outbox.test.js +++ b/src/middleware/tests/activitypub/outbox.test.js @@ -24,7 +24,7 @@ describe('Permissions are correctly set on outbox', () => { username: 'srosset81', email: 'sebastien@test.com', password: 'test', - name: 'Sébastien', + name: 'Sébastien' }); sebastien = await broker.call('activitypub.actor.awaitCreateComplete', { actorUri: sebastienUri }); @@ -33,7 +33,7 @@ describe('Permissions are correctly set on outbox', () => { username: 'simonlouvet', email: 'simon@test.com', password: 'test', - name: 'Simon', + name: 'Simon' }); simon = await broker2.call('activitypub.actor.awaitCreateComplete', { actorUri: simonUri }); @@ -46,7 +46,7 @@ describe('Permissions are correctly set on outbox', () => { inbox: `${sebastienUri}/inbox`, outbox: `${sebastienUri}/outbox`, followers: `${sebastienUri}/followers`, - following: `${sebastienUri}/following`, + following: `${sebastienUri}/following` }); }); @@ -55,7 +55,7 @@ describe('Permissions are correctly set on outbox', () => { collectionUri: sebastien.outbox, '@context': 'https://www.w3.org/ns/activitystreams', type: OBJECT_TYPES.NOTE, - name: 'Private message to self', + name: 'Private message to self' }); // Get outbox as self @@ -63,7 +63,7 @@ describe('Permissions are correctly set on outbox', () => { const outbox = await broker.call('activitypub.collection.get', { collectionUri: sebastien.outbox, page: 1, - webId: sebastien.id, + webId: sebastien.id }); expect(outbox.orderedItems).toHaveLength(1); expect(outbox.orderedItems[0]).toMatchObject({ @@ -71,8 +71,8 @@ describe('Permissions are correctly set on outbox', () => { type: ACTIVITY_TYPES.CREATE, object: { type: OBJECT_TYPES.NOTE, - name: 'Private message to self', - }, + name: 'Private message to self' + } }); }); @@ -81,7 +81,7 @@ describe('Permissions are correctly set on outbox', () => { const outbox = await broker.call('activitypub.collection.get', { collectionUri: sebastien.outbox, page: 1, - webId: 'anon', + webId: 'anon' }); expect(outbox.orderedItems).toHaveLength(0); }); @@ -93,7 +93,7 @@ describe('Permissions are correctly set on outbox', () => { '@context': 'https://www.w3.org/ns/activitystreams', type: OBJECT_TYPES.NOTE, name: 'Private message to friend', - to: simon.id, + to: simon.id }); // Get outbox as friend @@ -101,7 +101,7 @@ describe('Permissions are correctly set on outbox', () => { const outbox = await broker.call('activitypub.collection.get', { collectionUri: sebastien.outbox, page: 1, - webId: simon.id, + webId: simon.id }); expect(outbox.orderedItems).toHaveLength(1); expect(outbox.orderedItems[0]).toMatchObject({ @@ -109,8 +109,8 @@ describe('Permissions are correctly set on outbox', () => { type: ACTIVITY_TYPES.CREATE, object: { type: OBJECT_TYPES.NOTE, - name: 'Private message to friend', - }, + name: 'Private message to friend' + } }); }); @@ -119,7 +119,7 @@ describe('Permissions are correctly set on outbox', () => { const outbox = await broker.call('activitypub.collection.get', { collectionUri: sebastien.outbox, page: 1, - webId: 'anon', + webId: 'anon' }); expect(outbox.orderedItems).toHaveLength(0); }); @@ -131,7 +131,7 @@ describe('Permissions are correctly set on outbox', () => { '@context': 'https://www.w3.org/ns/activitystreams', type: OBJECT_TYPES.NOTE, name: 'Public message', - to: PUBLIC_URI, + to: PUBLIC_URI }); // Get outbox as friend @@ -139,7 +139,7 @@ describe('Permissions are correctly set on outbox', () => { const outbox = await broker.call('activitypub.collection.get', { collectionUri: sebastien.outbox, page: 1, - webId: simon.id, + webId: simon.id }); expect(outbox.orderedItems).toHaveLength(2); expect(outbox.orderedItems[0]).toMatchObject({ @@ -147,8 +147,8 @@ describe('Permissions are correctly set on outbox', () => { type: ACTIVITY_TYPES.CREATE, object: { type: OBJECT_TYPES.NOTE, - name: 'Public message', - }, + name: 'Public message' + } }); }); @@ -157,7 +157,7 @@ describe('Permissions are correctly set on outbox', () => { const outbox = await broker.call('activitypub.collection.get', { collectionUri: sebastien.outbox, page: 1, - webId: 'anon', + webId: 'anon' }); expect(outbox.orderedItems).toHaveLength(1); expect(outbox.orderedItems[0]).toMatchObject({ @@ -165,8 +165,8 @@ describe('Permissions are correctly set on outbox', () => { type: ACTIVITY_TYPES.CREATE, object: { type: OBJECT_TYPES.NOTE, - name: 'Public message', - }, + name: 'Public message' + } }); }); }); diff --git a/src/middleware/tests/interop/initialize.js b/src/middleware/tests/interop/initialize.js index 5321f134a..f1a095649 100644 --- a/src/middleware/tests/interop/initialize.js +++ b/src/middleware/tests/interop/initialize.js @@ -14,26 +14,26 @@ const { clearDataset } = require('../utils'); const containers = [ { path: '/resources', - acceptedTypes: ['pair:Resource'], + acceptedTypes: ['pair:Resource'] }, { path: '/protected-resources', acceptedTypes: ['pair:Resource'], permissions: {}, - newResourcesPermissions: {}, + newResourcesPermissions: {} }, { path: '/actors', acceptedTypes: [ACTOR_TYPES.PERSON], excludeFromMirror: true, - dereference: ['sec:publicKey', 'as:endpoints'], + dereference: ['sec:publicKey', 'as:endpoints'] }, { path: '/applications', acceptedTypes: [ACTOR_TYPES.APPLICATION], excludeFromMirror: true, - dereference: ['sec:publicKey', 'as:endpoints'], - }, + dereference: ['sec:publicKey', 'as:endpoints'] + } ]; const initialize = async (port, mainDataset, accountsDataset, serverToMirror) => { @@ -52,9 +52,9 @@ const initialize = async (port, mainDataset, accountsDataset, serverToMirror) => logger: { type: 'Console', options: { - level: 'warn', - }, - }, + level: 'warn' + } + } }); await broker.createService(CoreService, { @@ -65,14 +65,14 @@ const initialize = async (port, mainDataset, accountsDataset, serverToMirror) => url: CONFIG.SPARQL_ENDPOINT, user: CONFIG.JENA_USER, password: CONFIG.JENA_PASSWORD, - mainDataset, + mainDataset }, containers, api: { - port, + port }, - mirror: serverToMirror ? { servers: [serverToMirror] } : true, - }, + mirror: serverToMirror ? { servers: [serverToMirror] } : true + } }); await broker.createService(RelayService); @@ -80,8 +80,8 @@ const initialize = async (port, mainDataset, accountsDataset, serverToMirror) => if (serverToMirror) { await broker.createService(MirrorService, { settings: { - servers: [serverToMirror], - }, + servers: [serverToMirror] + } }); } @@ -89,14 +89,14 @@ const initialize = async (port, mainDataset, accountsDataset, serverToMirror) => settings: { baseUrl, jwtPath: path.resolve(__dirname, './jwt'), - accountsDataset, - }, + accountsDataset + } }); await broker.createService(WebIdService, { settings: { - usersContainer: `${baseUrl}actors/`, - }, + usersContainer: `${baseUrl}actors/` + } }); await broker.createService(InferenceService, { @@ -104,8 +104,8 @@ const initialize = async (port, mainDataset, accountsDataset, serverToMirror) => baseUrl, acceptFromRemoteServers: true, offerToRemoteServers: true, - ontologies: defaultOntologies, - }, + ontologies: defaultOntologies + } }); await broker.start(); @@ -117,9 +117,9 @@ const initialize = async (port, mainDataset, accountsDataset, serverToMirror) => additionalRights: { anon: { read: true, - write: true, - }, - }, + write: true + } + } }); await broker.call('webacl.resource.addRights', { @@ -128,9 +128,9 @@ const initialize = async (port, mainDataset, accountsDataset, serverToMirror) => additionalRights: { anon: { read: true, - write: true, - }, - }, + write: true + } + } }); return broker; diff --git a/src/middleware/tests/interop/mirror-protected.test.js b/src/middleware/tests/interop/mirror-protected.test.js index 7b0efa003..63aa558f0 100644 --- a/src/middleware/tests/interop/mirror-protected.test.js +++ b/src/middleware/tests/interop/mirror-protected.test.js @@ -17,7 +17,7 @@ beforeAll(async () => { // Wait for Relay actor creation, or server2 won't be able to mirror server1 await server1.call('activitypub.actor.awaitCreateComplete', { - actorUri: relay1, + actorUri: relay1 }); server2 = await initialize(3002, 'testData2', 'settings2', 'http://localhost:3001'); @@ -36,8 +36,8 @@ describe('Resource on server1 is shared with user on server2', () => { await expect( server1.call('activitypub.collection.includes', { collectionUri: urlJoin(relay1, 'followers'), - itemUri: relay2, - }), + itemUri: relay2 + }) ).resolves.toBeTruthy(); }); }); @@ -47,7 +47,7 @@ describe('Resource on server1 is shared with user on server2', () => { username: 'srosset81', email: 'sebastien@test.com', password: 'test', - name: 'Sébastien', + name: 'Sébastien' }); user2 = await server2.call('activitypub.actor.awaitCreateComplete', { actorUri: webId }); @@ -55,14 +55,14 @@ describe('Resource on server1 is shared with user on server2', () => { resourceUri = await server1.call('ldp.container.post', { resource: { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@type': 'Resource', - label: 'My protected resource', + label: 'My protected resource' }, contentType: MIME_TYPES.JSON, containerUri: 'http://localhost:3001/protected-resources', - webId: 'system', + webId: 'system' }); await server1.call('webacl.resource.addRights', { @@ -70,17 +70,17 @@ describe('Resource on server1 is shared with user on server2', () => { additionalRights: { user: { uri: user2.id, - read: true, - }, + read: true + } }, - webId: 'system', + webId: 'system' }); await waitForExpect(async () => { const inbox = await server1.call('activitypub.collection.get', { collectionUri: `${relay1}/outbox`, page: 1, - webId: relay1, + webId: relay1 }); expect(inbox).not.toBeNull(); @@ -89,9 +89,9 @@ describe('Resource on server1 is shared with user on server2', () => { actor: relay1, object: { type: ACTIVITY_TYPES.CREATE, - object: resourceUri, + object: resourceUri }, - to: user2.id, + to: user2.id }); }); }); @@ -102,17 +102,17 @@ describe('Resource on server1 is shared with user on server2', () => { rights: { user: { uri: user2.id, - read: true, - }, + read: true + } }, - webId: 'system', + webId: 'system' }); await waitForExpect(async () => { const inbox = await server1.call('activitypub.collection.get', { collectionUri: `${relay1}/outbox`, page: 1, - webId: relay1, + webId: relay1 }); expect(inbox).not.toBeNull(); @@ -121,9 +121,9 @@ describe('Resource on server1 is shared with user on server2', () => { actor: relay1, object: { type: ACTIVITY_TYPES.DELETE, - object: resourceUri, + object: resourceUri }, - to: user2.id, + to: user2.id }); }); }); diff --git a/src/middleware/tests/interop/mirror.test.js b/src/middleware/tests/interop/mirror.test.js index 9906a70df..7c8f07c87 100644 --- a/src/middleware/tests/interop/mirror.test.js +++ b/src/middleware/tests/interop/mirror.test.js @@ -17,7 +17,7 @@ beforeAll(async () => { // Wait for Relay actor creation, or server2 won't be able to mirror server1 await server1.call('activitypub.actor.awaitCreateComplete', { - actorUri: relay1, + actorUri: relay1 }); server2 = await initialize(3002, 'testData2', 'settings2', 'http://localhost:3001'); @@ -35,8 +35,8 @@ describe('Server2 mirror server1', () => { await expect( server1.call('activitypub.collection.includes', { collectionUri: urlJoin(relay1, 'followers'), - itemUri: relay2, - }), + itemUri: relay2 + }) ).resolves.toBeTruthy(); }); }); @@ -44,7 +44,7 @@ describe('Server2 mirror server1', () => { test('Server1 resources container is mirrored on server2', async () => { await waitForExpect(async () => { await expect( - server2.call('ldp.container.exist', { containerUri: 'http://localhost:3001/resources' }), + server2.call('ldp.container.exist', { containerUri: 'http://localhost:3001/resources' }) ).resolves.toBeTruthy(); }); }); @@ -53,18 +53,18 @@ describe('Server2 mirror server1', () => { resourceUri = await server1.call('ldp.container.post', { resource: { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@type': 'Resource', - label: 'My resource', + label: 'My resource' }, contentType: MIME_TYPES.JSON, - containerUri: 'http://localhost:3001/resources', + containerUri: 'http://localhost:3001/resources' }); await waitForExpect(async () => { await expect( - server2.call('ldp.container.includes', { containerUri: 'http://localhost:3001/resources', resourceUri }), + server2.call('ldp.container.includes', { containerUri: 'http://localhost:3001/resources', resourceUri }) ).resolves.toBeTruthy(); }); @@ -72,7 +72,7 @@ describe('Server2 mirror server1', () => { await expect(server2.call('ldp.remote.get', { resourceUri, strategy: 'cacheOnly' })).resolves.toMatchObject({ id: resourceUri, type: 'pair:Resource', - 'pair:label': 'My resource', + 'pair:label': 'My resource' }); }); }); @@ -81,20 +81,20 @@ describe('Server2 mirror server1', () => { await server1.call('ldp.resource.put', { resource: { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@id': resourceUri, '@type': 'Resource', - label: 'My resource updated', + label: 'My resource updated' }, - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }); await waitForExpect(async () => { await expect(server2.call('ldp.remote.get', { resourceUri, strategy: 'cacheOnly' })).resolves.toMatchObject({ id: resourceUri, type: 'pair:Resource', - 'pair:label': 'My resource updated', + 'pair:label': 'My resource updated' }); }); }); @@ -105,19 +105,19 @@ describe('Server2 mirror server1', () => { sparqlUpdate: ` PREFIX ldp: INSERT DATA { ldp:contains <${resourceUri}>. }; - `, + ` }); await waitForExpect(async () => { await expect( - server2.call('ldp.container.includes', { containerUri: 'http://localhost:3002/resources', resourceUri }), + server2.call('ldp.container.includes', { containerUri: 'http://localhost:3002/resources', resourceUri }) ).resolves.toBeTruthy(); }); // Since server1 is mirrored by server2, we don't need to mark it as singleMirroredResource await waitForExpect(async () => { await expect(server2.call('ldp.remote.get', { resourceUri, strategy: 'cacheOnly' })).resolves.not.toHaveProperty( - 'semapps:singleMirroredResource', + 'semapps:singleMirroredResource' ); }); }); @@ -127,7 +127,7 @@ describe('Server2 mirror server1', () => { await waitForExpect(async () => { await expect( - server2.call('ldp.container.includes', { containerUri: 'http://localhost:3001/resources', resourceUri }), + server2.call('ldp.container.includes', { containerUri: 'http://localhost:3001/resources', resourceUri }) ).resolves.toBeFalsy(); }); diff --git a/src/middleware/tests/interop/patch-remote.test.js b/src/middleware/tests/interop/patch-remote.test.js index 053e49646..1ef72d3fd 100644 --- a/src/middleware/tests/interop/patch-remote.test.js +++ b/src/middleware/tests/interop/patch-remote.test.js @@ -24,18 +24,18 @@ describe('Server2 imports a single resource from server1', () => { resourceUri = await server1.call('ldp.container.post', { resource: { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@type': 'Resource', - label: 'My resource', + label: 'My resource' }, contentType: MIME_TYPES.JSON, - containerUri: 'http://localhost:3001/resources', + containerUri: 'http://localhost:3001/resources' }); await waitForExpect(async () => { await expect( - server1.call('ldp.container.includes', { containerUri: 'http://localhost:3001/resources', resourceUri }), + server1.call('ldp.container.includes', { containerUri: 'http://localhost:3001/resources', resourceUri }) ).resolves.toBeTruthy(); }); }); @@ -46,12 +46,12 @@ describe('Server2 imports a single resource from server1', () => { sparqlUpdate: ` PREFIX ldp: INSERT DATA { ldp:contains <${resourceUri}>. }; - `, + ` }); await waitForExpect(async () => { await expect( - server2.call('ldp.container.includes', { containerUri: 'http://localhost:3002/resources', resourceUri }), + server2.call('ldp.container.includes', { containerUri: 'http://localhost:3002/resources', resourceUri }) ).resolves.toBeTruthy(); }); @@ -60,7 +60,7 @@ describe('Server2 imports a single resource from server1', () => { id: resourceUri, type: 'pair:Resource', 'pair:label': 'My resource', - 'semapps:singleMirroredResource': 'http://localhost:3001', + 'semapps:singleMirroredResource': 'http://localhost:3001' }); }); }); @@ -69,13 +69,13 @@ describe('Server2 imports a single resource from server1', () => { await server1.call('ldp.resource.put', { resource: { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@id': resourceUri, '@type': 'Resource', - label: 'My resource updated', + label: 'My resource updated' }, - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }); // Force call of updateSingleMirroredResources @@ -86,7 +86,7 @@ describe('Server2 imports a single resource from server1', () => { id: resourceUri, type: 'pair:Resource', 'pair:label': 'My resource updated', - 'semapps:singleMirroredResource': 'http://localhost:3001', + 'semapps:singleMirroredResource': 'http://localhost:3001' }); }); }); diff --git a/src/middleware/tests/interop/remote-inference.test.js b/src/middleware/tests/interop/remote-inference.test.js index 8a011a9b9..0abcc48b8 100644 --- a/src/middleware/tests/interop/remote-inference.test.js +++ b/src/middleware/tests/interop/remote-inference.test.js @@ -25,36 +25,36 @@ describe('An inference is added between server1 et server2', () => { resourceUri1 = await server1.call('ldp.container.post', { resource: { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@type': 'Resource', - label: 'My parent resource', + label: 'My parent resource' }, contentType: MIME_TYPES.JSON, - containerUri: 'http://localhost:3001/resources', + containerUri: 'http://localhost:3001/resources' }); resourceUri2 = await server2.call('ldp.container.post', { resource: { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@type': 'Resource', label: 'My child resource', partOf: { - '@id': resourceUri1, - }, + '@id': resourceUri1 + } }, contentType: MIME_TYPES.JSON, - containerUri: 'http://localhost:3002/resources', + containerUri: 'http://localhost:3002/resources' }); await waitForExpect(async () => { await expect( - server1.call('ldp.resource.get', { resourceUri: resourceUri1, accept: MIME_TYPES.JSON }), + server1.call('ldp.resource.get', { resourceUri: resourceUri1, accept: MIME_TYPES.JSON }) ).resolves.toMatchObject({ id: resourceUri1, - 'pair:hasPart': resourceUri2, + 'pair:hasPart': resourceUri2 }); }); }); @@ -66,17 +66,17 @@ describe('An inference is added between server1 et server2', () => { triple( namedNode(resourceUri1), namedNode('http://virtual-assembly.org/ontologies/pair#hasInspired'), - namedNode(resourceUri2), - ), - ], + namedNode(resourceUri2) + ) + ] }); await waitForExpect(async () => { await expect( - server2.call('ldp.resource.get', { resourceUri: resourceUri2, accept: MIME_TYPES.JSON }), + server2.call('ldp.resource.get', { resourceUri: resourceUri2, accept: MIME_TYPES.JSON }) ).resolves.toMatchObject({ id: resourceUri2, - 'pair:inspiredBy': resourceUri1, + 'pair:inspiredBy': resourceUri1 }); }); }); @@ -86,21 +86,21 @@ describe('An inference is added between server1 et server2', () => { await server2.call('ldp.resource.put', { resource: { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@id': resourceUri2, '@type': 'Resource', label: 'My child resource', partOf: { - '@id': resourceUri1, - }, + '@id': resourceUri1 + } }, - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }); await waitForExpect(async () => { await expect( - server1.call('ldp.resource.get', { resourceUri: resourceUri1, accept: MIME_TYPES.JSON }), + server1.call('ldp.resource.get', { resourceUri: resourceUri1, accept: MIME_TYPES.JSON }) ).resolves.not.toHaveProperty('pair:hasInspired'); }); }); @@ -110,7 +110,7 @@ describe('An inference is added between server1 et server2', () => { await waitForExpect(async () => { await expect( - server1.call('ldp.resource.get', { resourceUri: resourceUri1, accept: MIME_TYPES.JSON }), + server1.call('ldp.resource.get', { resourceUri: resourceUri1, accept: MIME_TYPES.JSON }) ).resolves.not.toHaveProperty('pair:hasPart'); }); }); diff --git a/src/middleware/tests/ldp/api.test.js b/src/middleware/tests/ldp/api.test.js index 18e416c50..2a019c627 100644 --- a/src/middleware/tests/ldp/api.test.js +++ b/src/middleware/tests/ldp/api.test.js @@ -18,9 +18,9 @@ const broker = new ServiceBroker({ logger: { type: 'Console', options: { - level: 'error', - }, - }, + level: 'error' + } + } }); let expressMocked = undefined; @@ -33,36 +33,36 @@ beforeAll(async () => { url: CONFIG.SPARQL_ENDPOINT, user: CONFIG.JENA_USER, password: CONFIG.JENA_PASSWORD, - mainDataset: CONFIG.MAIN_DATASET, + mainDataset: CONFIG.MAIN_DATASET }, ontologies, jsonContext: getPrefixJSON(ontologies), containers: [ { path: '/resources', - dereference: ['pair:hasLocation'], - }, + dereference: ['pair:hasLocation'] + } ], api: false, activitypub: false, mirror: false, void: false, - webfinger: false, - }, + webfinger: false + } }); await broker.createService(AuthLocalService, { settings: { baseUrl: CONFIG.HOME_URL, jwtPath: path.resolve(__dirname, '../jwt'), - accountsDataset: CONFIG.SETTINGS_DATASET, - }, + accountsDataset: CONFIG.SETTINGS_DATASET + } }); await broker.createService(WebIdService, { settings: { - usersContainer: `${CONFIG.HOME_URL}users`, - }, + usersContainer: `${CONFIG.HOME_URL}users` + } }); const app = express(); @@ -72,8 +72,8 @@ beforeAll(async () => { server: false, cors: { origin: '*', - exposedHeaders: '*', - }, + exposedHeaders: '*' + } }, methods: { authenticate(ctx, route, req, res) { @@ -81,8 +81,8 @@ beforeAll(async () => { }, authorize(ctx, route, req, res) { return Promise.resolve(ctx); - }, - }, + } + } }); app.use(apiGateway.express()); @@ -98,9 +98,9 @@ beforeAll(async () => { resourceUri: `${CONFIG.HOME_URL}resources`, additionalRights: { anon: { - write: true, - }, - }, + write: true + } + } }); expressMocked = supertest(app); @@ -119,11 +119,11 @@ describe('CRUD Project', () => { .post(containerUrl) .send({ '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@type': 'Project', description: 'myProject', - label: 'myLabel', + label: 'myLabel' }) .set('content-type', 'application/ld+json'); @@ -152,9 +152,9 @@ describe('CRUD Project', () => { test('Replace one project', async () => { const body = { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, - description: 'myProjectUpdated', + description: 'myProjectUpdated' }; await expressMocked @@ -214,7 +214,7 @@ describe('CRUD Project', () => { .set('Accept', 'application/ld+json'); expect(response.body['pair:hasLocation']).toMatchObject({ '@type': 'pair:Place', - 'pair:label': 'Paris', + 'pair:label': 'Paris' }); expect(response.body['pair:description']).toBe('myProjectPatched'); }, 20000); diff --git a/src/middleware/tests/ldp/container-options.test.js b/src/middleware/tests/ldp/container-options.test.js index 25e588e8b..a2a5fd460 100644 --- a/src/middleware/tests/ldp/container-options.test.js +++ b/src/middleware/tests/ldp/container-options.test.js @@ -19,8 +19,8 @@ describe('Container options', () => { const jsonContext = [ 'https://www.w3.org/ns/activitystreams', { - schema: 'http://schema.org/', - }, + schema: 'http://schema.org/' + } ]; const resourceUri = await broker.call('ldp.container.post', { @@ -35,12 +35,12 @@ describe('Container options', () => { 'schema:streetAddress': 'Rue du Général Paton', 'schema:postalCode': '28190', 'schema:addressLocality': 'Pontgouin', - 'schema:addressCountry': 'France', - }, - }, + 'schema:addressCountry': 'France' + } + } }, contentType: MIME_TYPES.JSON, - containerUri: `${CONFIG.HOME_URL}resources`, + containerUri: `${CONFIG.HOME_URL}resources` }); // Get resource without dereference @@ -48,12 +48,12 @@ describe('Container options', () => { broker.call('ldp.resource.get', { resourceUri, accept: MIME_TYPES.JSON, - jsonContext, - }), + jsonContext + }) ).resolves.toMatchObject({ '@context': jsonContext, type: 'Event', - location: {}, + location: {} }); // Get resource with partial dereference @@ -62,16 +62,16 @@ describe('Container options', () => { resourceUri, dereference: ['as:location'], accept: MIME_TYPES.JSON, - jsonContext: jsonContext, - }), + jsonContext: jsonContext + }) ).resolves.toMatchObject({ '@context': jsonContext, type: 'Event', location: { type: 'Place', name: 'Chantilly', - 'schema:address': {}, - }, + 'schema:address': {} + } }); // Get resource with full dereference @@ -80,8 +80,8 @@ describe('Container options', () => { resourceUri, dereference: ['as:location/schema:address'], accept: MIME_TYPES.JSON, - jsonContext, - }), + jsonContext + }) ).resolves.toMatchObject({ '@context': jsonContext, type: 'Event', @@ -93,9 +93,9 @@ describe('Container options', () => { 'schema:streetAddress': 'Rue du Général Paton', 'schema:postalCode': '28190', 'schema:addressLocality': 'Pontgouin', - 'schema:addressCountry': 'France', - }, - }, + 'schema:addressCountry': 'France' + } + } }); }); @@ -103,18 +103,18 @@ describe('Container options', () => { const organizationUri = await broker.call('ldp.container.post', { resource: { '@context': { - pair: 'http://virtual-assembly.org/ontologies/pair#', + pair: 'http://virtual-assembly.org/ontologies/pair#' }, '@type': 'Organization', 'pair:description': 'myOrga', 'pair:label': 'myTitle', 'pair:hasLocation': { '@type': 'pair:Place', - 'pair:description': 'myPlace', - }, + 'pair:description': 'myPlace' + } }, contentType: MIME_TYPES.JSON, - containerUri: `${CONFIG.HOME_URL}organizations`, + containerUri: `${CONFIG.HOME_URL}organizations` }); orga1 = await broker.call('ldp.resource.get', { resourceUri: organizationUri, accept: MIME_TYPES.JSON }); @@ -123,7 +123,7 @@ describe('Container options', () => { const place = await broker.call('ldp.resource.get', { resourceUri: orga1['pair:hasLocation']['@id'], - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(place['pair:description']).toBe('myPlace'); }); @@ -134,11 +134,11 @@ describe('Container options', () => { ...orga1, 'pair:hasLocation': { '@type': 'pair:Place', - 'pair:description': 'myPlace2', + 'pair:description': 'myPlace2' }, - 'pair:description': 'myOrga2', + 'pair:description': 'myOrga2' }, - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }); const orga1Updated = await broker.call('ldp.resource.get', { resourceUri: orga1['@id'], accept: MIME_TYPES.JSON }); @@ -147,21 +147,21 @@ describe('Container options', () => { const place = await broker.call('ldp.resource.get', { resourceUri: orga1Updated['pair:hasLocation']['@id'], - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(place['pair:description']).toBe('myPlace2'); }, 20000); test('Delete resource with disassembly', async () => { await broker.call('ldp.resource.delete', { - resourceUri: orga1['@id'], + resourceUri: orga1['@id'] }); let error; try { await broker.call('ldp.resource.get', { resourceUri: orga1['pair:hasLocation']['@id'], - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); } catch (e) { error = e; diff --git a/src/middleware/tests/ldp/container.test.js b/src/middleware/tests/ldp/container.test.js index b7a1576d7..55bdb363e 100644 --- a/src/middleware/tests/ldp/container.test.js +++ b/src/middleware/tests/ldp/container.test.js @@ -19,19 +19,19 @@ describe('LDP container tests', () => { test('Ensure container created in LdpService settings exists', async () => { await expect(broker.call('ldp.container.exist', { containerUri: `${CONFIG.HOME_URL}resources` })).resolves.toBe( - true, + true ); }); test('Create a new container', async () => { await expect(broker.call('ldp.container.exist', { containerUri: `${CONFIG.HOME_URL}objects` })).resolves.toBe( - false, + false ); await broker.call( 'ldp.container.create', { containerUri: `${CONFIG.HOME_URL}objects` }, - { meta: { webId: 'system' } }, + { meta: { webId: 'system' } } ); await expect(broker.call('ldp.container.exist', { containerUri: `${CONFIG.HOME_URL}objects` })).resolves.toBe(true); @@ -39,11 +39,11 @@ describe('LDP container tests', () => { await expect( broker.call('ldp.container.get', { containerUri: `${CONFIG.HOME_URL}objects`, - accept: MIME_TYPES.JSON, - }), + accept: MIME_TYPES.JSON + }) ).resolves.toMatchObject({ '@id': `${CONFIG.HOME_URL}objects`, - '@type': ['ldp:Container', 'ldp:BasicContainer'], + '@type': ['ldp:Container', 'ldp:BasicContainer'] }); }); @@ -53,18 +53,18 @@ describe('LDP container tests', () => { contentType: MIME_TYPES.JSON, resource: { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@type': 'Project', - label: 'My project', - }, + label: 'My project' + } }); await expect( broker.call('ldp.container.get', { containerUri: `${CONFIG.HOME_URL}resources`, - accept: MIME_TYPES.JSON, - }), + accept: MIME_TYPES.JSON + }) ).resolves.toMatchObject({ '@context': getPrefixJSON(ontologies), '@id': `${CONFIG.HOME_URL}resources`, @@ -73,9 +73,9 @@ describe('LDP container tests', () => { { '@id': resourceUri, '@type': 'pair:Project', - 'pair:label': 'My project', - }, - ], + 'pair:label': 'My project' + } + ] }); }); @@ -86,12 +86,12 @@ describe('LDP container tests', () => { contentType: MIME_TYPES.JSON, resource: { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@type': 'Project', - label: 'My project', - }, - }), + label: 'My project' + } + }) ).rejects.toThrow(); }); @@ -99,8 +99,8 @@ describe('LDP container tests', () => { await expect( broker.call('ldp.container.attach', { containerUri: `${CONFIG.HOME_URL}unknownContainer`, - resourceUri, - }), + resourceUri + }) ).rejects.toThrow('Cannot attach to a non-existing container'); }); @@ -110,12 +110,12 @@ describe('LDP container tests', () => { containerUri: `${CONFIG.HOME_URL}resources`, accept: MIME_TYPES.JSON, jsonContext: { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', - }, - }), + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' + } + }) ).resolves.toMatchObject({ '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@id': `${CONFIG.HOME_URL}resources`, '@type': ['http://www.w3.org/ns/ldp#Container', 'http://www.w3.org/ns/ldp#BasicContainer'], @@ -123,9 +123,9 @@ describe('LDP container tests', () => { { '@id': resourceUri, '@type': 'Project', - label: 'My project', - }, - ], + label: 'My project' + } + ] }); }); @@ -135,30 +135,30 @@ describe('LDP container tests', () => { contentType: MIME_TYPES.JSON, resource: { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@type': 'Project', - label: 'My project 2', - }, + label: 'My project 2' + } }); // Get without filters param await expect( broker.call('ldp.container.get', { containerUri: `${CONFIG.HOME_URL}resources`, - accept: MIME_TYPES.JSON, - }), + accept: MIME_TYPES.JSON + }) ).resolves.toMatchObject({ '@id': `${CONFIG.HOME_URL}resources`, '@type': ['ldp:Container', 'ldp:BasicContainer'], 'ldp:contains': [ { - 'pair:label': 'My project 2', + 'pair:label': 'My project 2' }, { - 'pair:label': 'My project', - }, - ], + 'pair:label': 'My project' + } + ] }); // Get with filters param @@ -167,53 +167,53 @@ describe('LDP container tests', () => { containerUri: `${CONFIG.HOME_URL}resources`, accept: MIME_TYPES.JSON, filters: { - 'pair:label': 'My project 2', - }, - }), + 'pair:label': 'My project 2' + } + }) ).resolves.toMatchObject({ '@id': `${CONFIG.HOME_URL}resources`, '@type': ['ldp:Container', 'ldp:BasicContainer'], 'ldp:contains': [ { - 'pair:label': 'My project 2', - }, - ], + 'pair:label': 'My project 2' + } + ] }); }); test('Detach a resource from a container', async () => { await broker.call('ldp.container.detach', { containerUri: `${CONFIG.HOME_URL}resources`, - resourceUri, + resourceUri }); // Project 1 should have disappeared from the container await expect( broker.call('ldp.container.get', { containerUri: `${CONFIG.HOME_URL}resources`, - accept: MIME_TYPES.JSON, - }), + accept: MIME_TYPES.JSON + }) ).resolves.toMatchObject({ '@context': getPrefixJSON(ontologies), '@id': `${CONFIG.HOME_URL}resources`, '@type': ['ldp:Container', 'ldp:BasicContainer'], 'ldp:contains': [ { - 'pair:label': 'My project 2', - }, - ], + 'pair:label': 'My project 2' + } + ] }); }); test('Clear container', async () => { await broker.call('ldp.container.clear', { - containerUri: `${CONFIG.HOME_URL}resources`, + containerUri: `${CONFIG.HOME_URL}resources` }); // Container should now be empty const container = await broker.call('ldp.container.get', { containerUri: `${CONFIG.HOME_URL}resources`, - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(container['ldp:contains']).toHaveLength(0); diff --git a/src/middleware/tests/ldp/initialize.js b/src/middleware/tests/ldp/initialize.js index 53d9223ab..b1d7da7d7 100644 --- a/src/middleware/tests/ldp/initialize.js +++ b/src/middleware/tests/ldp/initialize.js @@ -12,23 +12,23 @@ const ontologies = require('../ontologies'); const containers = [ { path: '/resources', - dereference: ['pair:hasLocation', 'pair:hasTopic', 'petr:openingTimesDay'], + dereference: ['pair:hasLocation', 'pair:hasTopic', 'petr:openingTimesDay'] }, { path: '/resources2', - dereference: ['pair:hasLocation/pair:hasPostalAddress', 'pair:hasTopic', 'petr:openingTimesDay'], + dereference: ['pair:hasLocation/pair:hasPostalAddress', 'pair:hasTopic', 'petr:openingTimesDay'] }, { path: '/organizations', dereference: ['pair:hasLocation/pair:hasPostalAddress'], - disassembly: [{ path: 'pair:hasLocation', container: `${CONFIG.HOME_URL}places` }], + disassembly: [{ path: 'pair:hasLocation', container: `${CONFIG.HOME_URL}places` }] }, { - path: '/places', + path: '/places' }, { - path: '/themes', - }, + path: '/themes' + } ]; const initialize = async () => { @@ -37,9 +37,9 @@ const initialize = async () => { logger: { type: 'Console', options: { - level: 'error', - }, - }, + level: 'error' + } + } }); await broker.createService(CoreService, { @@ -50,7 +50,7 @@ const initialize = async () => { url: CONFIG.SPARQL_ENDPOINT, user: CONFIG.JENA_USER, password: CONFIG.JENA_PASSWORD, - mainDataset: CONFIG.MAIN_DATASET, + mainDataset: CONFIG.MAIN_DATASET }, ontologies, jsonContext: getPrefixJSON(ontologies), @@ -58,22 +58,22 @@ const initialize = async () => { activitypub: false, mirror: false, void: false, - webfinger: false, - }, + webfinger: false + } }); await broker.createService(AuthLocalService, { settings: { baseUrl: CONFIG.HOME_URL, jwtPath: path.resolve(__dirname, '../jwt'), - accountsDataset: CONFIG.SETTINGS_DATASET, - }, + accountsDataset: CONFIG.SETTINGS_DATASET + } }); await broker.createService(WebIdService, { settings: { - usersContainer: `${CONFIG.HOME_URL}users`, - }, + usersContainer: `${CONFIG.HOME_URL}users` + } }); // Drop all existing triples, then restart broker so that default containers are recreated @@ -88,18 +88,18 @@ const initialize = async () => { resourceUri: `${CONFIG.HOME_URL}resources`, additionalRights: { anon: { - write: true, - }, - }, + write: true + } + } }); await broker.call('webacl.resource.addRights', { webId: 'system', resourceUri: `${CONFIG.HOME_URL}resources2`, additionalRights: { anon: { - write: true, - }, - }, + write: true + } + } }); await broker.call('webacl.resource.addRights', { @@ -107,9 +107,9 @@ const initialize = async () => { resourceUri: `${CONFIG.HOME_URL}organizations`, additionalRights: { anon: { - write: true, - }, - }, + write: true + } + } }); await broker.call('webacl.resource.addRights', { @@ -117,9 +117,9 @@ const initialize = async () => { resourceUri: `${CONFIG.HOME_URL}places`, additionalRights: { anon: { - write: true, - }, - }, + write: true + } + } }); await broker.call('webacl.resource.addRights', { @@ -127,9 +127,9 @@ const initialize = async () => { resourceUri: `${CONFIG.HOME_URL}themes`, additionalRights: { anon: { - write: true, - }, - }, + write: true + } + } }); return broker; diff --git a/src/middleware/tests/ldp/resource.test.js b/src/middleware/tests/ldp/resource.test.js index a87d8f7ab..190e007cf 100644 --- a/src/middleware/tests/ldp/resource.test.js +++ b/src/middleware/tests/ldp/resource.test.js @@ -21,31 +21,31 @@ describe('Resource CRUD operations', () => { const resourceUri = await broker.call('ldp.container.post', { resource: { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@type': 'Project', description: 'myProject', label: 'myTitle', affiliates: [ { - '@id': 'http://localhost:3000/users/guillaume', + '@id': 'http://localhost:3000/users/guillaume' }, { - '@id': 'http://localhost:3000/users/sebastien', - }, + '@id': 'http://localhost:3000/users/sebastien' + } ], hasLocation: { label: 'Paris', - description: 'The place to be', - }, + description: 'The place to be' + } }, contentType: MIME_TYPES.JSON, - containerUri: `${CONFIG.HOME_URL}resources`, + containerUri: `${CONFIG.HOME_URL}resources` }); project1 = await broker.call('ldp.resource.get', { resourceUri, - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(project1['pair:description']).toBe('myProject'); }, 20000); @@ -53,7 +53,7 @@ describe('Resource CRUD operations', () => { test('Get resource in JSON-LD format', async () => { const newProject = await broker.call('ldp.resource.get', { accept: MIME_TYPES.JSON, - resourceUri: project1['@id'], + resourceUri: project1['@id'] }); expect(newProject['pair:description']).toBe('myProject'); }, 20000); @@ -61,7 +61,7 @@ describe('Resource CRUD operations', () => { test('Get resource in turtle format', async () => { const newProject = await broker.call('ldp.resource.get', { accept: MIME_TYPES.TURTLE, - resourceUri: project1['@id'], + resourceUri: project1['@id'] }); expect(newProject).toMatch(new RegExp(`<${project1['@id']}>`)); expect(newProject).toMatch(new RegExp(`a.*pair:Project`)); @@ -72,18 +72,18 @@ describe('Resource CRUD operations', () => { test('Get resource in triple format', async () => { const newProject = await broker.call('ldp.resource.get', { accept: MIME_TYPES.TRIPLE, - resourceUri: project1['@id'], + resourceUri: project1['@id'] }); expect(newProject).toMatch( new RegExp( - `<${project1['@id']}>.*.*`, - ), + `<${project1['@id']}>.*.*` + ) ); expect(newProject).toMatch( - new RegExp(`<${project1['@id']}>.*.*"myProject"`), + new RegExp(`<${project1['@id']}>.*.*"myProject"`) ); expect(newProject).toMatch( - new RegExp(`<${project1['@id']}>.*.*"myTitle"`), + new RegExp(`<${project1['@id']}>.*.*"myTitle"`) ); }, 20000); @@ -91,34 +91,34 @@ describe('Resource CRUD operations', () => { await broker.call('ldp.resource.put', { resource: { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@id': project1['@id'], description: 'myProjectUpdatedAgain', affiliates: { - '@id': 'http://localhost:3000/users/pierre', + '@id': 'http://localhost:3000/users/pierre' }, hasLocation: { - label: 'Nantes', - }, + label: 'Nantes' + } }, accept: MIME_TYPES.JSON, - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }); const updatedProject = await broker.call('ldp.resource.get', { resourceUri: project1['@id'], - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(updatedProject).toMatchObject({ 'pair:description': 'myProjectUpdatedAgain', 'pair:affiliates': { - '@id': 'http://localhost:3000/users/pierre', + '@id': 'http://localhost:3000/users/pierre' }, 'pair:hasLocation': { - 'pair:label': 'Nantes', - }, + 'pair:label': 'Nantes' + } }); expect(updatedProject['pair:label']).toBeUndefined(); expect(updatedProject['pair:hasLocation']['pair:description']).toBeUndefined(); @@ -128,188 +128,188 @@ describe('Resource CRUD operations', () => { const resourceUpdated = { '@context': { petr: 'https://data.petr-msb.data-players.com/ontology#', - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@id': project1['@id'], description: 'myProjectUpdatedAgain', affiliates: { - '@id': 'http://localhost:3000/users/pierre', + '@id': 'http://localhost:3000/users/pierre' }, hasLocation: [ { - label: 'Nantes', + label: 'Nantes' }, { - label: 'Compiegne', - }, - ], + label: 'Compiegne' + } + ] }; await broker.call('ldp.resource.put', { resource: resourceUpdated, accept: MIME_TYPES.JSON, - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }); let updatedProject = await broker.call('ldp.resource.get', { resourceUri: project1['@id'], - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(updatedProject).toMatchObject({ 'pair:description': 'myProjectUpdatedAgain', 'pair:affiliates': { - '@id': 'http://localhost:3000/users/pierre', + '@id': 'http://localhost:3000/users/pierre' }, 'pair:hasLocation': [ { - 'pair:label': 'Nantes', + 'pair:label': 'Nantes' }, { - 'pair:label': 'Compiegne', - }, - ], + 'pair:label': 'Compiegne' + } + ] }); expect(updatedProject['pair:label']).toBeUndefined(); expect(updatedProject['pair:hasLocation']['pair:description']).toBeUndefined(); resourceUpdated.hasLocation = [ { - label: 'Compiegne', - }, + label: 'Compiegne' + } ]; await broker.call('ldp.resource.put', { resource: resourceUpdated, accept: MIME_TYPES.JSON, - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }); updatedProject = await broker.call('ldp.resource.get', { resourceUri: project1['@id'], - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(updatedProject).toMatchObject({ 'pair:description': 'myProjectUpdatedAgain', 'pair:affiliates': { - '@id': 'http://localhost:3000/users/pierre', + '@id': 'http://localhost:3000/users/pierre' }, 'pair:hasLocation': { - 'pair:label': 'Compiegne', - }, + 'pair:label': 'Compiegne' + } }); resourceUpdated.hasLocation = [ { - label: 'Compiegne', + label: 'Compiegne' }, { - label: 'Nantes', + label: 'Nantes' }, { - label: 'Oloron', - }, + label: 'Oloron' + } ]; await broker.call('ldp.resource.put', { resource: resourceUpdated, accept: MIME_TYPES.JSON, - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }); updatedProject = await broker.call('ldp.resource.get', { resourceUri: project1['@id'], - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(updatedProject).toMatchObject({ 'pair:description': 'myProjectUpdatedAgain', 'pair:affiliates': { - '@id': 'http://localhost:3000/users/pierre', + '@id': 'http://localhost:3000/users/pierre' }, 'pair:hasLocation': [ { - 'pair:label': 'Compiegne', + 'pair:label': 'Compiegne' }, { - 'pair:label': 'Nantes', + 'pair:label': 'Nantes' }, { - 'pair:label': 'Oloron', - }, - ], + 'pair:label': 'Oloron' + } + ] }); resourceUpdated.hasLocation = [ { - label: 'Compiegne', + label: 'Compiegne' }, { - label: 'Compiegne', + label: 'Compiegne' }, { - label: 'Compiegne', - }, + label: 'Compiegne' + } ]; await broker.call('ldp.resource.put', { resource: resourceUpdated, accept: MIME_TYPES.JSON, - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }); updatedProject = await broker.call('ldp.resource.get', { resourceUri: project1['@id'], - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(updatedProject).toMatchObject({ 'pair:description': 'myProjectUpdatedAgain', 'pair:affiliates': { - '@id': 'http://localhost:3000/users/pierre', + '@id': 'http://localhost:3000/users/pierre' }, 'pair:hasLocation': { - 'pair:label': 'Compiegne', - }, + 'pair:label': 'Compiegne' + } }); resourceUpdated.hasLocation = [ { label: 'Compiegne', - description: 'the place to be', + description: 'the place to be' }, { label: 'Compiegne', - description: 'or not', - }, + description: 'or not' + } ]; await broker.call('ldp.resource.put', { resource: resourceUpdated, accept: MIME_TYPES.JSON, - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }); updatedProject = await broker.call('ldp.resource.get', { resourceUri: project1['@id'], - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(updatedProject).toMatchObject({ 'pair:description': 'myProjectUpdatedAgain', 'pair:affiliates': { - '@id': 'http://localhost:3000/users/pierre', + '@id': 'http://localhost:3000/users/pierre' }, 'pair:hasLocation': [ { 'pair:label': 'Compiegne', - 'pair:description': 'the place to be', + 'pair:description': 'the place to be' }, { 'pair:label': 'Compiegne', - 'pair:description': 'or not', - }, - ], + 'pair:description': 'or not' + } + ] }); resourceUpdated.hasLocation = undefined; @@ -317,68 +317,68 @@ describe('Resource CRUD operations', () => { await broker.call('ldp.resource.put', { resource: resourceUpdated, accept: MIME_TYPES.JSON, - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }); updatedProject = await broker.call('ldp.resource.get', { resourceUri: project1['@id'], - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(updatedProject['pair:hasLocation']).toBeUndefined(); resourceUpdated['petr:openingTimesDay'] = [ - { 'petr:endingTime': '2021-10-07T09:40:56.131Z', 'petr:startingTime': '2021-10-07T06:40:56.123Z' }, + { 'petr:endingTime': '2021-10-07T09:40:56.131Z', 'petr:startingTime': '2021-10-07T06:40:56.123Z' } ]; await broker.call('ldp.resource.put', { resource: resourceUpdated, accept: MIME_TYPES.JSON, - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }); updatedProject = await broker.call('ldp.resource.get', { resourceUri: project1['@id'], - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(updatedProject).toMatchObject({ 'pair:description': 'myProjectUpdatedAgain', 'petr:openingTimesDay': { 'petr:endingTime': '2021-10-07T09:40:56.131Z', - 'petr:startingTime': '2021-10-07T06:40:56.123Z', - }, + 'petr:startingTime': '2021-10-07T06:40:56.123Z' + } }); resourceUpdated['petr:openingTimesDay'] = [ { 'petr:endingTime': '2021-10-07T09:40:56.131Z', 'petr:startingTime': '2021-10-07T06:40:56.123Z' }, - { 'petr:startingTime': '2021-10-07T10:44:54.883Z', 'petr:endingTime': '2021-10-07T16:44:54.888Z' }, + { 'petr:startingTime': '2021-10-07T10:44:54.883Z', 'petr:endingTime': '2021-10-07T16:44:54.888Z' } ]; await broker.call('ldp.resource.put', { resource: resourceUpdated, accept: MIME_TYPES.JSON, - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }); updatedProject = await broker.call('ldp.resource.get', { resourceUri: project1['@id'], - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(updatedProject).toMatchObject({ 'pair:description': 'myProjectUpdatedAgain', 'petr:openingTimesDay': [ { 'petr:endingTime': '2021-10-07T09:40:56.131Z', 'petr:startingTime': '2021-10-07T06:40:56.123Z' }, - { 'petr:startingTime': '2021-10-07T10:44:54.883Z', 'petr:endingTime': '2021-10-07T16:44:54.888Z' }, - ], + { 'petr:startingTime': '2021-10-07T10:44:54.883Z', 'petr:endingTime': '2021-10-07T16:44:54.888Z' } + ] }); }, 20000); test('Post resource with multiple blank nodes with 2 imbrications blank nodes', async () => { const resourceToPost = { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@type': 'Project', description: 'myProject', @@ -386,55 +386,55 @@ describe('Resource CRUD operations', () => { hasLocation: { label: 'Paris', hasPostalAddress: { - addressCountry: 'France', - }, - }, + addressCountry: 'France' + } + } }; const resourceUri = await broker.call('ldp.container.post', { resource: resourceToPost, contentType: MIME_TYPES.JSON, - containerUri: `${CONFIG.HOME_URL}resources2`, + containerUri: `${CONFIG.HOME_URL}resources2` }); project2 = await broker.call('ldp.resource.get', { resourceUri, - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(project2).toMatchObject({ 'pair:hasLocation': { 'pair:label': 'Paris', 'pair:hasPostalAddress': { - 'pair:addressCountry': 'France', - }, - }, + 'pair:addressCountry': 'France' + } + } }); resourceToPost.hasLocation = [ { label: 'Paris', hasPostalAddress: { - addressCountry: 'France', - }, + addressCountry: 'France' + } }, { label: 'Paris', hasPostalAddress: { - addressCountry: 'USA', - }, - }, + addressCountry: 'USA' + } + } ]; const resourceUri3 = await broker.call('ldp.container.post', { resource: resourceToPost, contentType: MIME_TYPES.JSON, - containerUri: `${CONFIG.HOME_URL}resources2`, + containerUri: `${CONFIG.HOME_URL}resources2` }); const project3 = await broker.call('ldp.resource.get', { resourceUri: resourceUri3, - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(project3).toMatchObject({ @@ -442,58 +442,58 @@ describe('Resource CRUD operations', () => { { 'pair:label': 'Paris', 'pair:hasPostalAddress': { - 'pair:addressCountry': 'France', - }, + 'pair:addressCountry': 'France' + } }, { 'pair:label': 'Paris', 'pair:hasPostalAddress': { - 'pair:addressCountry': 'USA', - }, - }, - ], + 'pair:addressCountry': 'USA' + } + } + ] }); resourceToPost.hasLocation = [ { label: 'Paris', hasPostalAddress: { - addressCountry: 'France', - }, + addressCountry: 'France' + } }, { label: 'Paris', hasPostalAddress: { - addressCountry: 'France', - }, - }, + addressCountry: 'France' + } + } ]; const resourceUri4 = await broker.call('ldp.container.post', { resource: resourceToPost, contentType: MIME_TYPES.JSON, - containerUri: `${CONFIG.HOME_URL}resources2`, + containerUri: `${CONFIG.HOME_URL}resources2` }); const project4 = await broker.call('ldp.resource.get', { resourceUri: resourceUri4, - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(project4).toMatchObject({ 'pair:hasLocation': { 'pair:label': 'Paris', 'pair:hasPostalAddress': { - 'pair:addressCountry': 'France', - }, - }, + 'pair:addressCountry': 'France' + } + } }); }, 20000); test('Put resource with multiple blank nodes with 2 imbrications blank nodes', async () => { const resourceUpdated = { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@id': project2['@id'], description: 'myProjectUpdatedAgain', @@ -501,27 +501,27 @@ describe('Resource CRUD operations', () => { { label: 'Paris', hasPostalAddress: { - addressCountry: 'France', - }, + addressCountry: 'France' + } }, { label: 'Paris', hasPostalAddress: { - addressCountry: 'USA', - }, - }, - ], + addressCountry: 'USA' + } + } + ] }; await broker.call('ldp.resource.put', { resource: resourceUpdated, accept: MIME_TYPES.JSON, - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }); let updatedProject = await broker.call('ldp.resource.get', { resourceUri: project2['@id'], - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(updatedProject).toMatchObject({ @@ -530,42 +530,42 @@ describe('Resource CRUD operations', () => { { 'pair:label': 'Paris', 'pair:hasPostalAddress': { - 'pair:addressCountry': 'France', - }, + 'pair:addressCountry': 'France' + } }, { 'pair:label': 'Paris', 'pair:hasPostalAddress': { - 'pair:addressCountry': 'USA', - }, - }, - ], + 'pair:addressCountry': 'USA' + } + } + ] }); resourceUpdated.hasLocation = [ { label: 'Paris', hasPostalAddress: { - addressCountry: 'France', - }, + addressCountry: 'France' + } }, { label: 'Paris', hasPostalAddress: { - addressCountry: 'France', - }, - }, + addressCountry: 'France' + } + } ]; await broker.call('ldp.resource.put', { resource: resourceUpdated, accept: MIME_TYPES.JSON, - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }); updatedProject = await broker.call('ldp.resource.get', { resourceUri: project2['@id'], - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(updatedProject).toMatchObject({ @@ -573,9 +573,9 @@ describe('Resource CRUD operations', () => { 'pair:hasLocation': { 'pair:label': 'Paris', 'pair:hasPostalAddress': { - 'pair:addressCountry': 'France', - }, - }, + 'pair:addressCountry': 'France' + } + } }); }, 20000); @@ -585,54 +585,54 @@ describe('Resource CRUD operations', () => { containerUri: 'http://localhost:3000/themes', resource: { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@type': 'pair:Theme', - label: 'Permaculture', + label: 'Permaculture' }, contentType: MIME_TYPES.JSON, - slug: 'Permaculture', + slug: 'Permaculture' }); // Add a relation to the theme await broker.call('ldp.resource.put', { resource: { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@type': 'Project', '@id': project1['@id'], label: 'myTitle', hasTopic: { - '@id': themeUri, - }, + '@id': themeUri + } }, - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }); // Remove the relation to the theme await broker.call('ldp.resource.put', { resource: { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@type': 'Project', '@id': project1['@id'], - label: 'myTitle', + label: 'myTitle' }, - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }); // Ensure the theme has not been deleted const theme = await broker.call('ldp.resource.get', { resourceUri: themeUri, - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(theme).toMatchObject({ '@id': themeUri, '@type': 'pair:Theme', - 'pair:label': 'Permaculture', + 'pair:label': 'Permaculture' }); }, 20000); @@ -641,13 +641,13 @@ describe('Resource CRUD operations', () => { containerUri: `${CONFIG.HOME_URL}resources`, resource: { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@type': 'pair:Project', - label: 'SemanticApps', + label: 'SemanticApps' }, contentType: MIME_TYPES.JSON, - slug: 'SemApps', + slug: 'SemApps' }); await broker.call('ldp.resource.patch', { @@ -657,28 +657,28 @@ describe('Resource CRUD operations', () => { quad( namedNode(projectUri), namedNode('http://virtual-assembly.org/ontologies/pair#comment'), - literal('An open source toolbox to help you easily build semantic web applications'), - ), + literal('An open source toolbox to help you easily build semantic web applications') + ) ], triplesToRemove: [ quad( namedNode(projectUri), namedNode('http://virtual-assembly.org/ontologies/pair#label'), - literal('SemanticApps'), - ), + literal('SemanticApps') + ) ], - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }); const project = await broker.call('ldp.resource.get', { resourceUri: projectUri, - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(project).toMatchObject({ '@id': projectUri, 'pair:label': 'SemApps', - 'pair:comment': 'An open source toolbox to help you easily build semantic web applications', + 'pair:comment': 'An open source toolbox to help you easily build semantic web applications' }); }, 20000); @@ -687,13 +687,13 @@ describe('Resource CRUD operations', () => { containerUri: `${CONFIG.HOME_URL}resources`, resource: { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@type': 'pair:Project', - label: 'ActivityPods', + label: 'ActivityPods' }, contentType: MIME_TYPES.JSON, - slug: 'ActivityPods', + slug: 'ActivityPods' }); await broker.call('ldp.resource.patch', { @@ -702,21 +702,21 @@ describe('Resource CRUD operations', () => { quad( namedNode(projectUri), namedNode('http://virtual-assembly.org/ontologies/pair#hasLocation'), - blankNode('b_0'), + blankNode('b_0') ), quad( blankNode('b_0'), namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), - namedNode('http://virtual-assembly.org/ontologies/pair#Place'), + namedNode('http://virtual-assembly.org/ontologies/pair#Place') ), - quad(blankNode('b_0'), namedNode('http://virtual-assembly.org/ontologies/pair#label'), literal('Paris')), + quad(blankNode('b_0'), namedNode('http://virtual-assembly.org/ontologies/pair#label'), literal('Paris')) ], - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }); let project = await broker.call('ldp.resource.get', { resourceUri: projectUri, - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(project).toMatchObject({ @@ -724,8 +724,8 @@ describe('Resource CRUD operations', () => { 'pair:label': 'ActivityPods', 'pair:hasLocation': { '@type': 'pair:Place', - 'pair:label': 'Paris', - }, + 'pair:label': 'Paris' + } }); await broker.call('ldp.resource.patch', { @@ -734,21 +734,21 @@ describe('Resource CRUD operations', () => { quad( namedNode(projectUri), namedNode('http://virtual-assembly.org/ontologies/pair#hasLocation'), - blankNode('b_0'), + blankNode('b_0') ), quad( blankNode('b_0'), namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), - namedNode('http://virtual-assembly.org/ontologies/pair#Place'), + namedNode('http://virtual-assembly.org/ontologies/pair#Place') ), - quad(blankNode('b_0'), namedNode('http://virtual-assembly.org/ontologies/pair#label'), literal('Compiègne')), + quad(blankNode('b_0'), namedNode('http://virtual-assembly.org/ontologies/pair#label'), literal('Compiègne')) ], - contentType: MIME_TYPES.JSON, + contentType: MIME_TYPES.JSON }); project = await broker.call('ldp.resource.get', { resourceUri: projectUri, - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(project).toMatchObject({ @@ -757,26 +757,26 @@ describe('Resource CRUD operations', () => { 'pair:hasLocation': expect.arrayContaining([ { '@type': 'pair:Place', - 'pair:label': 'Paris', + 'pair:label': 'Paris' }, { '@type': 'pair:Place', - 'pair:label': 'Compiègne', - }, - ]), + 'pair:label': 'Compiègne' + } + ]) }); }, 20000); test('Delete resource', async () => { await broker.call('ldp.resource.delete', { - resourceUri: project1['@id'], + resourceUri: project1['@id'] }); await expect( broker.call('ldp.resource.get', { resourceUri: project1['@id'], - accept: MIME_TYPES.JSON, - }), + accept: MIME_TYPES.JSON + }) ).rejects.toThrow(`Cannot get permissions of non-existing container or resource ${project1['@id']}`); }, 20000); }); diff --git a/src/middleware/tests/utils.js b/src/middleware/tests/utils.js index 45bc02bab..37db0ec90 100644 --- a/src/middleware/tests/utils.js +++ b/src/middleware/tests/utils.js @@ -2,18 +2,18 @@ const urlJoin = require('url-join'); const fetch = require('node-fetch'); const CONFIG = require('./config'); -const clearDataset = async (dataset) => { +const clearDataset = async dataset => { return await fetch(urlJoin(CONFIG.SPARQL_ENDPOINT, dataset, 'update'), { method: 'POST', body: 'update=CLEAR+ALL', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Authorization: `Basic ${Buffer.from(`${CONFIG.JENA_USER}:${CONFIG.JENA_PASSWORD}`).toString('base64')}`, - 'X-SemappsUser': 'system', - }, + 'X-SemappsUser': 'system' + } }); }; module.exports = { - clearDataset, + clearDataset }; diff --git a/src/middleware/tests/webId/webId.test.js b/src/middleware/tests/webId/webId.test.js index 3cf3e5a0a..f70e02288 100644 --- a/src/middleware/tests/webId/webId.test.js +++ b/src/middleware/tests/webId/webId.test.js @@ -10,9 +10,9 @@ const broker = new ServiceBroker({ logger: { type: 'Console', options: { - level: 'error', - }, - }, + level: 'error' + } + } }); beforeAll(async () => { @@ -24,7 +24,7 @@ beforeAll(async () => { url: CONFIG.SPARQL_ENDPOINT, user: CONFIG.JENA_USER, password: CONFIG.JENA_PASSWORD, - mainDataset: CONFIG.MAIN_DATASET, + mainDataset: CONFIG.MAIN_DATASET }, ontologies, containers: ['/users'], @@ -32,13 +32,13 @@ beforeAll(async () => { mirror: false, void: false, webacl: false, - webfinger: false, - }, + webfinger: false + } }); broker.createService(WebIdService, { settings: { - usersContainer: `${CONFIG.HOME_URL}users/`, - }, + usersContainer: `${CONFIG.HOME_URL}users/` + } }); // Drop all existing triples, then restart broker so that default containers are recreated @@ -59,7 +59,7 @@ describe('WebId user creation', () => { nick: 'my-nick', name: 'jon', familyName: 'do', - homepage: 'http://example.org/myPage', + homepage: 'http://example.org/myPage' }; const webId = await broker.call('webid.create', profileData); diff --git a/src/middleware/tests/webacl/initialize.js b/src/middleware/tests/webacl/initialize.js index ffe067bb4..54f432b8c 100644 --- a/src/middleware/tests/webacl/initialize.js +++ b/src/middleware/tests/webacl/initialize.js @@ -16,9 +16,9 @@ const initialize = async () => { logger: { type: 'Console', options: { - level: 'error', - }, - }, + level: 'error' + } + } }); await broker.createService(CoreService, { @@ -29,29 +29,29 @@ const initialize = async () => { url: CONFIG.SPARQL_ENDPOINT, user: CONFIG.JENA_USER, password: CONFIG.JENA_PASSWORD, - mainDataset: CONFIG.MAIN_DATASET, + mainDataset: CONFIG.MAIN_DATASET }, ontologies, containers: ['/resources'], activitypub: false, mirror: false, void: false, - webfinger: false, - }, + webfinger: false + } }); await broker.createService(AuthLocalService, { settings: { baseUrl: CONFIG.HOME_URL, jwtPath: path.resolve(__dirname, '../jwt'), - accountsDataset: CONFIG.SETTINGS_DATASET, - }, + accountsDataset: CONFIG.SETTINGS_DATASET + } }); await broker.createService(WebIdService, { settings: { - usersContainer: `${CONFIG.HOME_URL}users`, - }, + usersContainer: `${CONFIG.HOME_URL}users` + } }); const app = express(); @@ -61,8 +61,8 @@ const initialize = async () => { server: false, cors: { origin: '*', - exposedHeaders: '*', - }, + exposedHeaders: '*' + } }, methods: { authenticate(ctx, route, req, res) { @@ -70,8 +70,8 @@ const initialize = async () => { }, authorize(ctx, route, req, res) { return Promise.resolve(ctx); - }, - }, + } + } }); app.use(apiGateway.express()); diff --git a/src/middleware/tests/webacl/resourceCRUD.test.js b/src/middleware/tests/webacl/resourceCRUD.test.js index d9af756ba..0dd815961 100644 --- a/src/middleware/tests/webacl/resourceCRUD.test.js +++ b/src/middleware/tests/webacl/resourceCRUD.test.js @@ -23,14 +23,14 @@ describe('middleware CRUD resource with perms', () => { const urlParamsPost = { resource: { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@type': 'Project', description: 'myProject', - label: 'myTitle', + label: 'myTitle' }, contentType: MIME_TYPES.JSON, - containerUri: `${CONFIG.HOME_URL}resources`, + containerUri: `${CONFIG.HOME_URL}resources` }; const resourceUri = await broker.call('ldp.container.post', urlParamsPost, { meta: { webId: 'anon' } }); } catch (e) { @@ -45,14 +45,14 @@ describe('middleware CRUD resource with perms', () => { const urlParamsPost = { resource: { '@context': { - '@vocab': 'http://virtual-assembly.org/ontologies/pair#', + '@vocab': 'http://virtual-assembly.org/ontologies/pair#' }, '@type': 'Project', description: 'myProject', - label: 'myTitle', + label: 'myTitle' }, contentType: MIME_TYPES.JSON, - containerUri: `${CONFIG.HOME_URL}resources`, + containerUri: `${CONFIG.HOME_URL}resources` }; const webId = 'http://a/user'; resourceUri = await broker.call('ldp.container.post', urlParamsPost, { meta: { webId } }); @@ -65,16 +65,16 @@ describe('middleware CRUD resource with perms', () => { read: true, write: true, append: true, - control: true, + control: true }, - webId, + webId }); expect(resourceRights).toMatchObject({ read: true, write: true, append: false, - control: true, + control: true }); } catch (e) { console.log(e); @@ -86,7 +86,7 @@ describe('middleware CRUD resource with perms', () => { try { const urlParamsPost = { resourceUri, - webId: 'http://a/user', + webId: 'http://a/user' }; await broker.call('ldp.resource.delete', urlParamsPost); @@ -98,7 +98,7 @@ describe('middleware CRUD resource with perms', () => { FILTER (?p IN (acl:accessTo, acl:default ) ) ?auth ?p2 ?o } }`, webId: 'system', - accept: MIME_TYPES.JSON, + accept: MIME_TYPES.JSON }); expect(result.length).toBe(0); diff --git a/src/middleware/tests/webacl/sparql-injection.test.js b/src/middleware/tests/webacl/sparql-injection.test.js index b8c148ca7..b04d5656d 100644 --- a/src/middleware/tests/webacl/sparql-injection.test.js +++ b/src/middleware/tests/webacl/sparql-injection.test.js @@ -23,12 +23,12 @@ describe('pentest for the ACL groups API', () => { await broker.call('webacl.group.addMember', { groupSlug: 'mygroup1', - memberUri: 'http://localhost:3000/users/info1', + memberUri: 'http://localhost:3000/users/info1' }); await broker.call('webacl.group.addMember', { groupSlug: 'mygroup1', memberUri: - 'http://localhost:3000/users/info2> } };CLEAR ALL;INSERT DATA{ GRAPH { } };CLEAR ALL;INSERT DATA{ GRAPH { { await broker.call('webacl.group.addMember', { groupSlug: 'mygroup1', - memberUri: 'http://localhost:3000/users/info1', + memberUri: 'http://localhost:3000/users/info1' }); await broker.call('webacl.group.addMember', { groupSlug: 'mygroup1', memberUri: - 'http://localhost:3000/users/info2\\x3C } };CLEAR ALL;INSERT DATA{ GRAPH { {