comments mostly

This commit is contained in:
Michael Puckett 2023-07-31 10:04:56 -04:00
parent f530d8b0d2
commit eefe61be16
75 changed files with 5021 additions and 4914 deletions

View File

@ -18,8 +18,10 @@ declare class Headers {
}
declare type BodyInit = Blob | ArrayBufferView | ArrayBuffer | string;
declare type ResponseBodyInit = BodyInit;
interface Body {
export interface Body {
readonly bodyUsed: boolean;
readonly status: number;
readonly url: string;
arrayBuffer(): Promise<ArrayBuffer>;
blob(): Promise<Blob>;
json(): Promise<JSON>;

View File

@ -1,10 +1,7 @@
/// <reference types="node" />
import * as AP from '@activity-kit/types';
import { AuthAdapter } from './Auth';
import { CryptoAdapter } from './Crypto';
import { DbAdapter } from './Db';
import { StorageAdapter } from './Storage';
import { FetchPolyfill } from './FetchPolyfill';
export { AuthAdapter } from './Auth';
export { DbAdapter, DbOptions } from './Db';
export { StorageAdapter } from './Storage';
@ -18,19 +15,3 @@ export type Adapters = {
storage: StorageAdapter;
crypto: CryptoAdapter;
};
export type CoreLibrary = AuthAdapter & DbAdapter & StorageAdapter & CryptoAdapter & {
fetch: FetchPolyfill;
getGuid: () => Promise<string>;
findEntityById: (this: CoreLibrary, id: URL) => Promise<AP.Entity | null>;
getActorByUserId: (this: CoreLibrary, userId: string) => Promise<AP.Actor | null>;
getPrivateKey: (this: CoreLibrary, actor: AP.Actor) => Promise<string>;
getStreamByName: (this: CoreLibrary, actor: AP.Actor, name: string) => Promise<AP.EitherCollection | null>;
fetchEntityById: (this: CoreLibrary, id: URL) => Promise<AP.Entity | null>;
queryById: (this: CoreLibrary, id: URL) => Promise<AP.Entity | null>;
expandEntity: (this: CoreLibrary, entity: AP.Entity) => Promise<AP.Entity>;
getCollectionItems: (this: CoreLibrary, entity: AP.Collection | AP.OrderedCollection) => AP.EntityReference[];
getPaginatedCollectionItems: (this: CoreLibrary, collection: AP.Collection | AP.OrderedCollection) => Promise<AP.EntityReference[]>;
expandCollection: (this: CoreLibrary, collection: AP.EitherCollection) => Promise<AP.EitherCollection>;
getRecipientUrls: (this: CoreLibrary, activity: AP.Activity) => Promise<URL[]>;
broadcast: (this: CoreLibrary, activity: AP.Activity, actor: AP.Actor) => Promise<unknown>;
};

View File

@ -1 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/adapters/index.ts"],"names":[],"mappings":";;;AASA,2BAA4C;AAAxB,+FAAA,SAAS,OAAA"}
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/adapters/index.ts"],"names":[],"mappings":";;;AAMA,2BAA4C;AAAxB,+FAAA,SAAS,OAAA"}

View File

@ -1,2 +1,3 @@
import { CoreLibrary } from './adapters';
export declare const broadcast: CoreLibrary['broadcast'];
import * as AP from '@activity-kit/types';
import { CoreLibrary } from '.';
export declare function broadcast(this: CoreLibrary, activity: AP.Activity, actor: AP.Actor): Promise<Record<string, number>>;

View File

@ -3,31 +3,20 @@ Object.defineProperty(exports, "__esModule", { value: true });
exports.broadcast = void 0;
const type_utilities_1 = require("@activity-kit/type-utilities");
const utilities_1 = require("@activity-kit/utilities");
const broadcast = async function broadcast(activity, actor) {
const publicActivity = (0, utilities_1.convertEntityToJson)((0, utilities_1.cleanProps)((0, utilities_1.applyContext)(activity)));
const recipients = await getRecipientInboxUrls.bind(this)(activity, actor);
const send = async (recipient) => {
return await signAndSendToForeignActorInbox.bind(this)(recipient, actor, publicActivity);
};
return Object.fromEntries(await Promise.all(recipients.map(send.bind(this))));
};
const getPrivateKey_1 = require("./util/getPrivateKey");
async function broadcast(activity, actor) {
const activityWithContext = (0, utilities_1.applyContext)(activity);
const cleanedActivity = (0, utilities_1.cleanProps)(activityWithContext);
const plainEntity = (0, utilities_1.convertEntityToJson)(cleanedActivity);
const recipientInboxUrls = await getRecipientInboxUrls.bind(this)(activity, actor);
const sendToRecipient = (recipientInboxUrl) => signAndSendToInboxUrl.call(this, recipientInboxUrl, actor, plainEntity);
const promises = recipientInboxUrls.map(sendToRecipient);
const resultEntries = await Promise.all(promises);
return Object.fromEntries(resultEntries);
}
exports.broadcast = broadcast;
async function signAndSendToForeignActorInbox(foreignActorInbox, actor, plainEntity) {
const actorId = (0, utilities_1.getId)(actor);
type_utilities_1.assert.exists(actorId);
const privateKey = await this.getPrivateKey(actor);
const { dateHeader, digestHeader, signatureHeader } = await this.getHttpSignature(foreignActorInbox, actorId, privateKey, plainEntity);
if (!digestHeader || !dateHeader || !signatureHeader) {
throw new Error('Failed to sign Activity');
}
const headers = {
[utilities_1.CONTENT_TYPE_HEADER]: utilities_1.ACTIVITYSTREAMS_CONTENT_TYPE,
[utilities_1.ACCEPT_HEADER]: utilities_1.ACTIVITYSTREAMS_CONTENT_TYPE,
Host: foreignActorInbox.hostname,
Date: dateHeader,
Digest: digestHeader,
Signature: signatureHeader,
};
async function signAndSendToInboxUrl(foreignActorInbox, actor, plainEntity) {
const headers = await getHeaders.bind(this)(actor, foreignActorInbox, plainEntity);
const statusCode = await this.fetch(foreignActorInbox.href, {
method: 'post',
body: JSON.stringify(plainEntity),
@ -41,6 +30,23 @@ async function signAndSendToForeignActorInbox(foreignActorInbox, actor, plainEnt
});
return [foreignActorInbox.href, statusCode];
}
async function getHeaders(actor, foreignActorInbox, plainEntity) {
const actorId = (0, utilities_1.getId)(actor);
type_utilities_1.assert.exists(actorId);
const privateKey = await getPrivateKey_1.getPrivateKey.bind(this)(actor);
const { dateHeader, digestHeader, signatureHeader } = await this.getHttpSignature(foreignActorInbox, actorId, privateKey, plainEntity);
if (!digestHeader || !dateHeader || !signatureHeader) {
throw new Error('Failed to sign Activity');
}
return {
[utilities_1.CONTENT_TYPE_HEADER]: utilities_1.ACTIVITYSTREAMS_CONTENT_TYPE,
[utilities_1.ACCEPT_HEADER]: utilities_1.ACTIVITYSTREAMS_CONTENT_TYPE,
Host: foreignActorInbox.hostname,
Date: dateHeader,
Digest: digestHeader,
Signature: signatureHeader,
};
}
async function getRecipientInboxUrls(activity, actor) {
const recipientUrls = await this.getRecipientUrls(activity);
const extractUrl = async (recipientUrl) => {
@ -48,7 +54,7 @@ async function getRecipientInboxUrls(activity, actor) {
if (recipientUrl.href === ((_a = (0, utilities_1.getId)(actor)) === null || _a === void 0 ? void 0 : _a.href)) {
return null;
}
const foundEntity = await this.fetchEntityById(recipientUrl);
const foundEntity = await this.queryById(recipientUrl);
if (!type_utilities_1.guard.isApActor(foundEntity)) {
return null;
}

View File

@ -1 +1 @@
{"version":3,"file":"broadcast.js","sourceRoot":"","sources":["../src/broadcast.ts"],"names":[],"mappings":";;;AACA,iEAA6D;AAC7D,uDASiC;AAS1B,MAAM,SAAS,GAA6B,KAAK,UAAU,SAAS,CAEzE,QAAqB,EACrB,KAAe;IAEf,MAAM,cAAc,GAAG,IAAA,+BAAmB,EACxC,IAAA,sBAAU,EAAC,IAAA,wBAAY,EAAC,QAAQ,CAAC,CAAC,CACnC,CAAC;IAEF,MAAM,UAAU,GAAG,MAAM,qBAAqB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;IAE3E,MAAM,IAAI,GAAG,KAAK,EAAE,SAAc,EAAE,EAAE;QACpC,OAAO,MAAM,8BAA8B,CAAC,IAAI,CAAC,IAAI,CAAC,CACpD,SAAS,EACT,KAAK,EACL,cAAc,CACf,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AAChF,CAAC,CAAC;AApBW,QAAA,SAAS,aAoBpB;AAQF,KAAK,UAAU,8BAA8B,CAE3C,iBAAsB,EACtB,KAAe,EACf,WAAoC;IAEpC,MAAM,OAAO,GAAG,IAAA,iBAAK,EAAC,KAAK,CAAC,CAAC;IAE7B,uBAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAEvB,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;IAEnD,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G,CAAC,UAAU,CAAC,CAAC,CAAC;IAE5E,MAAM,YAAY,GAAG,kBAAkB,CAAC,MAAM,CAAC,sBAAK,CAAC,KAAK,CAAC,CAAC;IAE5D,OAAO,IAAA,2BAAe,EAAC,YAAY,CAAC,CAAC;AACvC,CAAC"}

View File

@ -1,2 +1,3 @@
import { CoreLibrary } from './adapters';
export declare const expandCollection: CoreLibrary['expandCollection'];
import * as AP from '@activity-kit/types';
import { CoreLibrary } from '.';
export declare function expandCollection(this: CoreLibrary, collection: AP.EitherCollection): Promise<AP.EitherCollection>;

View File

@ -2,29 +2,38 @@
Object.defineProperty(exports, "__esModule", { value: true });
exports.expandCollection = void 0;
const type_utilities_1 = require("@activity-kit/type-utilities");
const expandCollection = async function expandCollection(collection) {
const items = this.getCollectionItems(collection);
const expandedItems = await Promise.all(items.map(async (item) => {
var _a;
if (type_utilities_1.guard.isApEntity(item)) {
return item;
}
return (_a = (await this.queryById(item))) !== null && _a !== void 0 ? _a : item;
}));
if (type_utilities_1.guard.isArray(collection.orderedItems) &&
collection.orderedItems.length) {
return {
...collection,
orderedItems: expandedItems,
};
async function expandCollection(collection) {
const expandedCollection = {
...collection,
};
if (isArray(collection.orderedItems)) {
const expandPromises = collection.orderedItems
.filter(isEntityReference)
.map(queryItem.bind(this));
const expanded = await Promise.all(expandPromises);
expandedCollection.orderedItems = expanded;
}
else if (type_utilities_1.guard.isArray(collection.items) && collection.items.length) {
return {
...collection,
items: expandedItems,
};
if (isArray(collection.items)) {
const expandPromises = collection.items
.filter(isEntityReference)
.map(queryItem.bind(this));
const expanded = await Promise.all(expandPromises);
expandedCollection.items = expanded;
}
return collection;
};
return expandedCollection;
}
exports.expandCollection = expandCollection;
function isEntityReference(value) {
return type_utilities_1.guard.isApEntity(value) || type_utilities_1.guard.isUrl(value);
}
function isArray(items) {
return type_utilities_1.guard.isArray(items) && items.length > 0;
}
async function queryItem(item) {
if (type_utilities_1.guard.isApEntity(item)) {
return item;
}
const cachedItem = await this.queryById(item);
return cachedItem !== null && cachedItem !== void 0 ? cachedItem : item;
}
//# sourceMappingURL=expandCollection.js.map

View File

@ -1 +1 @@
{"version":3,"file":"expandCollection.js","sourceRoot":"","sources":["../src/expandCollection.ts"],"names":[],"mappings":";;;AACA,iEAAqD;AAI9C,MAAM,gBAAgB,GAC3B,KAAK,UAAU,gBAAgB,CAE7B,UAA+B;IAE/B,MAAM,KAAK,GAAG,IAAI,CAAC,kBAAkB,CAAC,UAAU,CAAC,CAAC;IAElD,MAAM,aAAa,GAAG,MAAM,OAAO,CAAC,GAAG,CACrC,KAAK,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE;;QACvB,IAAI,sBAAK,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;YAC1B,OAAO,IAAI,CAAC;SACb;QAED,OAAO,MAAA,CAAC,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,mCAAI,IAAI,CAAC;IAC9C,CAAC,CAAC,CACH,CAAC;IAEF,IACE,sBAAK,CAAC,OAAO,CAAC,UAAU,CAAC,YAAY,CAAC;QACtC,UAAU,CAAC,YAAY,CAAC,MAAM,EAC9B;QACA,OAAO;YACL,GAAG,UAAU;YACb,YAAY,EAAE,aAAa;SAC5B,CAAC;KACH;SAAM,IAAI,sBAAK,CAAC,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,MAAM,EAAE;QACrE,OAAO;YACL,GAAG,UAAU;YACb,KAAK,EAAE,aAAa;SACrB,CAAC;KACH;IAED,OAAO,UAAU,CAAC;AACpB,CAAC,CAAC;AAjCS,QAAA,gBAAgB,oBAiCzB"}
{"version":3,"file":"expandCollection.js","sourceRoot":"","sources":["../src/expandCollection.ts"],"names":[],"mappings":";;;AACA,iEAAqD;AAU9C,KAAK,UAAU,gBAAgB,CAEpC,UAA+B;IAE/B,MAAM,kBAAkB,GAAG;QACzB,GAAG,UAAU;KACd,CAAC;IAEF,IAAI,OAA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}

View File

@ -1,2 +1,3 @@
import { CoreLibrary } from './adapters';
export declare const expandEntity: CoreLibrary['expandEntity'];
import * as AP from '@activity-kit/types';
import { CoreLibrary } from '.';
export declare function expandEntity(this: CoreLibrary, entity: AP.Entity): Promise<AP.Entity>;

View File

@ -11,10 +11,10 @@ const selfReferentialKeys = [
'href',
'publicKey',
];
const expandEntity = async function expandEntity(entity) {
async function expandEntity(entity) {
var _a;
return (_a = type_utilities_1.cast.isApEntity(await expandObject.bind(this)(entity))) !== null && _a !== void 0 ? _a : entity;
};
}
exports.expandEntity = expandEntity;
async function expandObject(object) {
const expanded = {};

View File

@ -1 +1 @@
{"version":3,"file":"expandEntity.js","sourceRoot":"","sources":["../src/expandEntity.ts"],"names":[],"mappings":";;;AACA,iEAA2D;AAI3D,MAAM,mBAAmB,GAAG;IAC1B,UAAU;IACV,KAAK;IACL,IAAI;IACJ,MAAM;IACN,KAAK;IACL,MAAM;IACN,WAAW;CACZ,CAAC;AAEK,MAAM,YAAY,GACvB,KAAK,UAAU,YAAY,CAEzB,MAAiB;;IAEjB,OAAO,MAAA,qBAAI,CAAC,UAAU,CAAC,MAAM,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,mCAAI,MAAM,CAAC;AAC1E,CAAC,CAAC;AANS,QAAA,YAAY,gBAMrB;AAEJ,KAAK,UAAU,YAAY,CAEzB,MAA+B;IAE/B,MAAM,QAAQ,GAA4B,EAAE,CAAC;IAE7C,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;QACjD,QAAQ,CAAC,GAAG,CAAC,GAAG,MAAM,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC;KAC5D;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,KAAK,UAAU,WAAW,CAExB,KAAoC;IAEpC,MAAM,CA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123 +0,0 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchEntityById = void 0;
const AP = __importStar(require("@activity-kit/types"));
const type_utilities_1 = require("@activity-kit/type-utilities");
const utilities_1 = require("@activity-kit/utilities");
const fetchEntityById = async function fetchEntityById(id) {
const isJsonLdContentType = await getIsJsonLdContentType.bind(this)(id);
if (!isJsonLdContentType) {
return null;
}
const botActor = await getBotActor.bind(this)();
type_utilities_1.assert.exists(botActor);
const botActorId = (0, utilities_1.getId)(botActor);
type_utilities_1.assert.exists(botActorId);
const { dateHeader, signatureHeader } = await this.getHttpSignature(id, botActorId, await this.getPrivateKey(botActor));
const headers = {
date: dateHeader,
signature: signatureHeader,
};
const fetchedJson = await fetchJsonByUrl.bind(this)(id, headers);
if (fetchedJson) {
const convertedEntity = (0, utilities_1.convertJsonToEntity)(fetchedJson);
if (convertedEntity) {
const entity = (0, utilities_1.compressEntity)(convertedEntity);
if (entity) {
await this.saveEntity(entity);
return entity;
}
}
}
return null;
};
exports.fetchEntityById = fetchEntityById;
async function fetchJsonByUrl(url, headers) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 1250);
const config = {
signal: controller.signal,
headers: {
...headers,
[utilities_1.ACCEPT_HEADER]: utilities_1.ACTIVITYSTREAMS_CONTENT_TYPE,
},
};
async function handleResponse(response) {
clearTimeout(timeout);
const data = await response.json();
if (response.status === 200) {
return data;
}
if (response.status === 400 || response.status === 410) {
if ('@context' in data) {
return data;
}
else {
return {
'@context': utilities_1.ACTIVITYSTREAMS_CONTEXT,
type: AP.ExtendedObjectTypes.TOMBSTONE,
id: url.href,
url: url.href,
};
}
}
if (response.status >= 500) {
console.log('Server error.', response.status, url.href);
return null;
}
console.log('Unexpected status code.', response.status, url.href);
return data;
}
async function handleError(error) {
clearTimeout(timeout);
console.log(`${error}`);
return null;
}
return await this.fetch(url.href, config)
.then(handleResponse)
.catch(handleError);
}
async function getContentType(url) {
const { headers } = await this.fetch(url.toString(), { method: 'HEAD' });
return headers.get('Content-Type');
}
async function getIsJsonLdContentType(url) {
const contentType = await getContentType.bind(this)(url);
if (!contentType) {
return false;
}
return (contentType.includes(utilities_1.ACTIVITYSTREAMS_CONTENT_TYPE) ||
contentType.includes(utilities_1.LINKED_DATA_CONTENT_TYPE) ||
contentType.includes(utilities_1.JSON_CONTENT_TYPE));
}
async function getBotActor() {
var _a;
const botActor = await this.findOne('entity', {
preferredUsername: utilities_1.SERVER_ACTOR_USERNAME,
});
return (_a = type_utilities_1.cast.isApActor(botActor)) !== null && _a !== void 0 ? _a : null;
}
//# sourceMappingURL=fetchEntityById.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"fetchEntityById.js","sourceRoot":"","sources":["../src/fetchEntityById.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wDAA0C;AAC1C,iEAA4D;AAC5D,uDAUiC;AAI1B,MAAM,eAAe,GAC1B,KAAK,UAAU,eAAe,CAE5B,EAAO;IAEP,MAAM,mBAAmB,GAAG,MAAM,sBAAsB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC;IAExE,I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E,MAAM,CAAC;SACtC,IAAI,CAAC,cAAc,CAAC;SACpB,KAAK,CAAC,WAAW,CAAC,CAAC;AACxB,CAAC;AAED,KAAK,UAAU,cAAc,CAE3B,GAAQ;IAER,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IACzE,OAAO,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;AACrC,CAAC;AAED,KAAK,UAAU,sBAAsB,CAEnC,GAAQ;IAER,MAAM,WAAW,GAAG,MAAM,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;IAEzD,IAAI,CAAC,WAAW,EAAE;QAChB,OAAO,KAAK,CAAC;KACd;IAED,OAAO,CACL,WAAW,CAAC,QAAQ,CAAC,wCAA4B,CAAC;QAClD,WAAW,CAAC,QAAQ,CAAC,oCAAwB,CAAC;QAC9C,WAAW,CAAC,QAAQ,CAAC,6BAAiB,CAAC,CACxC,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,WAAW;;IACxB,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE;QAC5C,iBAAiB,EAAE,iCAAqB;KACzC,CAAC,CAAC;IAEH,OAAO,MAAA,qBAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,mCAAI,IAAI,CAAC;AAC1C,CAAC"}

View File

@ -1,2 +1,4 @@
import { CoreLibrary } from './adapters';
export declare const findEntityById: CoreLibrary['fetchEntityById'];
/// <reference types="node" />
import * as AP from '@activity-kit/types';
import { CoreLibrary } from '.';
export declare function findEntityById(this: CoreLibrary, id: URL): Promise<AP.Entity | null>;

View File

@ -2,9 +2,9 @@
Object.defineProperty(exports, "__esModule", { value: true });
exports.findEntityById = void 0;
const utilities_1 = require("@activity-kit/utilities");
const findEntityById = async function findEntityById(id) {
async function findEntityById(id) {
const collectionName = (0, utilities_1.getCollectionNameByUrl)(id);
return await this.findOne(collectionName, { id: id.href });
};
}
exports.findEntityById = findEntityById;
//# sourceMappingURL=findEntityById.js.map

View File

@ -1 +1 @@
{"version":3,"file":"findEntityById.js","sourceRoot":"","sources":["../src/findEntityById.ts"],"names":[],"mappings":";;;AACA,uDAAiE;AAI1D,MAAM,cAAc,GACzB,KAAK,UAAU,cAAc,CAE3B,EAAO;IAEP,MAAM,cAAc,GAAG,IAAA,kCAAsB,EAAC,EAAE,CAAC,CAAC;IAElD,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;AAC7D,CAAC,CAAC;AARS,QAAA,cAAc,kBAQvB"}
{"version":3,"file":"findEntityById.js","sourceRoot":"","sources":["../src/findEntityById.ts"],"names":[],"mappings":";;;AACA,uDAAiE;AAS1D,KAAK,UAAU,cAAc,CAElC,EAAO;IAEP,MAAM,cAAc,GAAG,IAAA,kCAAsB,EAAC,EAAE,CAAC,CAAC;IAElD,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;AAC7D,CAAC;AAPD,wCAOC"}

View File

@ -1,2 +1,3 @@
import { CoreLibrary } from './adapters';
export declare const getActorByUserId: CoreLibrary['getActorByUserId'];
import * as AP from '@activity-kit/types';
import { CoreLibrary } from '.';
export declare function getActorByUserId(this: CoreLibrary, userId: string): Promise<AP.Actor | null>;

View File

@ -2,13 +2,13 @@
Object.defineProperty(exports, "__esModule", { value: true });
exports.getActorByUserId = void 0;
const type_utilities_1 = require("@activity-kit/type-utilities");
const getActorByUserId = async function getActorByUserId(userId) {
async function getActorByUserId(userId) {
const preferredUsername = await this.findStringValueById('username', userId);
const user = await this.findOne('entity', { preferredUsername });
if (!type_utilities_1.guard.isApActor(user)) {
return null;
}
return user;
};
}
exports.getActorByUserId = getActorByUserId;
//# sourceMappingURL=getActorByUserId.js.map

View File

@ -1 +1 @@
{"version":3,"file":"getActorByUserId.js","sourceRoot":"","sources":["../src/getActorByUserId.ts"],"names":[],"mappings":";;;AACA,iEAAqD;AAI9C,MAAM,gBAAgB,GAC3B,KAAK,UAAU,gBAAgB,CAE7B,MAAc;IAEd,MAAM,iBAAiB,GAAG,MAAM,IAAI,CAAC,mBAAmB,CACtD,UAAU,EACV,MAAM,CACP,CAAC;IAEF,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,iBAAiB,EAAE,CAAC,CAAC;IAEjE,IAAI,CAAC,sBAAK,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE;QAC1B,OAAO,IAAI,CAAC;KACb;IAED,OAAO,IAAI,CAAC;AACd,CAAC,CAAC;AAjBS,QAAA,gBAAgB,oBAiBzB"}
{"version":3,"file":"getActorByUserId.js","sourceRoot":"","sources":["../src/getActorByUserId.ts"],"names":[],"mappings":";;;AACA,iEAAqD;AAW9C,KAAK,UAAU,gBAAgB,CAEpC,MAAc;IAEd,MAAM,iBAAiB,GAAG,MAAM,IAAI,CAAC,mBAAmB,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;IAE7E,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,iBAAiB,EAAE,CAAC,CAAC;IAEjE,IAAI,CAAC,sBAAK,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE;QAC1B,OAAO,IAAI,CAAC;KACb;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AAbD,4CAaC"}

View File

@ -1,2 +0,0 @@
import { CoreLibrary } from './adapters';
export declare const getCollectionItems: CoreLibrary['getCollectionItems'];

View File

@ -1,22 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCollectionItems = void 0;
const type_utilities_1 = require("@activity-kit/type-utilities");
const getCollectionItems = function getCollectionItems(entity) {
const collectionItems = [];
if (type_utilities_1.guard.isArray(entity.orderedItems) && entity.orderedItems.length) {
const orderedItems = entity.orderedItems.filter((item) => {
return type_utilities_1.guard.isApEntity(item) || type_utilities_1.guard.isUrl(item);
});
collectionItems.push(...orderedItems);
}
else if (type_utilities_1.guard.isArray(entity.items) && entity.items.length) {
const items = entity.items.filter((item) => {
return type_utilities_1.guard.isApEntity(item) || type_utilities_1.guard.isUrl(item);
});
collectionItems.push(...items);
}
return collectionItems;
};
exports.getCollectionItems = getCollectionItems;
//# sourceMappingURL=getCollectionItems.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"getCollectionItems.js","sourceRoot":"","sources":["../src/getCollectionItems.ts"],"names":[],"mappings":";;;AACA,iEAAqD;AAI9C,MAAM,kBAAkB,GAC7B,SAAS,kBAAkB,CAEzB,MAA2B;IAE3B,MAAM,eAAe,GAAyB,EAAE,CAAC;IAEjD,IAAI,sBAAK,CAAC,OAAO,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,MAAM,CAAC,YAAY,CAAC,MAAM,EAAE;QACpE,MAAM,YAAY,GAAG,MAAM,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE;YACvD,OAAO,sBAAK,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,sBAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACrD,CAAC,CAAC,CAAC;QAEH,eAAe,CAAC,IAAI,CAAC,GAAG,YAAY,CAAC,CAAC;KACvC;SAAM,IAAI,sBAAK,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE;QAC7D,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE;YACzC,OAAO,sBAAK,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,sBAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACrD,CAAC,CAAC,CAAC;QAEH,eAAe,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,CAAC;KAChC;IAED,OAAO,eAAe,CAAC;AACzB,CAAC,CAAC;AAtBS,QAAA,kBAAkB,sBAsB3B"}

View File

@ -1,2 +1,3 @@
import { CoreLibrary } from './adapters';
export declare const getPaginatedCollectionItems: CoreLibrary['getPaginatedCollectionItems'];
import * as AP from '@activity-kit/types';
import { CoreLibrary } from '.';
export declare function getPaginatedCollectionItems(this: CoreLibrary, collection: AP.EitherCollection): Promise<AP.EntityReference[]>;

View File

@ -27,7 +27,7 @@ exports.getPaginatedCollectionItems = void 0;
const AP = __importStar(require("@activity-kit/types"));
const type_utilities_1 = require("@activity-kit/type-utilities");
const utilities_1 = require("@activity-kit/utilities");
const getPaginatedCollectionItems = async function getPaginatedCollectionItems(collection) {
async function getPaginatedCollectionItems(collection) {
const firstCollectionPageId = (0, utilities_1.getId)(collection.first);
if (!firstCollectionPageId) {
if (type_utilities_1.guard.isArray(collection.orderedItems)) {
@ -62,6 +62,6 @@ const getPaginatedCollectionItems = async function getPaginatedCollectionItems(c
nextCollectionPage = nextPage;
}
return collectionItems.flat();
};
}
exports.getPaginatedCollectionItems = getPaginatedCollectionItems;
//# sourceMappingURL=getPaginatedCollectionItems.js.map

View File

@ -1 +1 @@
{"version":3,"file":"getPaginatedCollectionItems.js","sourceRoot":"","sources":["../src/getPaginatedCollectionItems.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wDAA0C;AAC1C,iEAAqD;AACrD,uDAAgD;AAIzC,MAAM,2BAA2B,GACtC,KAAK,UAAU,2BAA2B,CAExC,UAA+B;IAE/B,MAAM,qBAAqB,GAAG,IAAA,iBAAK,EAAC,UAAU,CAAC,KAAK,CAAC,CAAC;IAEtD,IAAI,CAAC,qBAAqB,EAAE;QAG1B,IAAI,sBAAK,CAAC,OAAO,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE;YAC1C,OAAO,UAAU,CAAC,YAA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;SACP;QAED,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QAElD,IACE,CAAC,sBAAK,CAAC,UAAU,CAAoB,QAAQ,EAAE,EAAE,CAAC,mBAAmB,CAAC,EACtE;YACA,MAAM;SACP;QAED,kBAAkB,GAAG,QAAQ,CAAC;KAC/B;IAED,OAAO,eAAe,CAAC,IAAI,EAAE,CAAC;AAChC,CAAC;AA9DD,kEA8DC"}

View File

@ -1,2 +0,0 @@
import { CoreLibrary } from './adapters';
export declare const getPrivateKey: CoreLibrary['getPrivateKey'];

View File

@ -1,16 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPrivateKey = void 0;
const getPrivateKey = async function getPrivateKey(actor) {
if (!actor.preferredUsername) {
throw new Error('Actor has no `preferredUsername`.');
}
const userId = await this.findStringIdByValue('username', actor.preferredUsername);
const privateKey = await this.findStringValueById('privateKey', userId);
if (!privateKey) {
throw new Error('Private key not found for this Actor.');
}
return privateKey;
};
exports.getPrivateKey = getPrivateKey;
//# sourceMappingURL=getPrivateKey.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"getPrivateKey.js","sourceRoot":"","sources":["../src/getPrivateKey.ts"],"names":[],"mappings":";;;AAIO,MAAM,aAAa,GACxB,KAAK,UAAU,aAAa,CAE1B,KAAe;IAEf,IAAI,CAAC,KAAK,CAAC,iBAAiB,EAAE;QAC5B,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;KACtD;IAED,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,mBAAmB,CAC3C,UAAU,EACV,KAAK,CAAC,iBAAiB,CACxB,CAAC;IAEF,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,mBAAmB,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC;IAExE,IAAI,CAAC,UAAU,EAAE;QACf,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;KAC1D;IAED,OAAO,UAAU,CAAC;AACpB,CAAC,CAAC;AArBS,QAAA,aAAa,iBAqBtB"}

View File

@ -1,2 +1,4 @@
import { CoreLibrary } from './adapters';
export declare const getRecipientUrls: CoreLibrary['getRecipientUrls'];
/// <reference types="node" />
import * as AP from '@activity-kit/types';
import { CoreLibrary } from '.';
export declare function getRecipientUrls(this: CoreLibrary, activity: AP.Activity): Promise<URL[]>;

View File

@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
exports.getRecipientUrls = void 0;
const type_utilities_1 = require("@activity-kit/type-utilities");
const utilities_1 = require("@activity-kit/utilities");
const getRecipientUrls = async function getRecipientUrls(activity) {
async function getRecipientUrls(activity) {
const tags = type_utilities_1.guard.isApCoreObject(activity.object) && activity.object.tag
? getArray(activity.object.tag)
: [];
@ -22,7 +22,7 @@ const getRecipientUrls = async function getRecipientUrls(activity) {
.filter((recipientUrl) => recipientUrl.href !== utilities_1.PUBLIC_ACTOR);
const actorUrls = await Promise.all(recipientIds.map(getActorIds.bind(this)));
return (0, utilities_1.deduplicateUrls)(actorUrls.flat());
};
}
exports.getRecipientUrls = getRecipientUrls;
async function getActorIds(recipientId) {
const foundRecipient = await this.queryById(recipientId);

View File

@ -1 +1 @@
{"version":3,"file":"getRecipientUrls.js","sourceRoot":"","sources":["../src/getRecipientUrls.ts"],"names":[],"mappings":";;;AACA,iEAAqD;AACrD,uDAA+E;AAIxE,MAAM,gBAAgB,GAC3B,KAAK,UAAU,gBAAgB,CAE7B,QAAqB;IAErB,MAAM,IAAI,GACR,sBAAK,CAAC,cAAc,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,QAAQ,CAAC,MAAM,CAAC,GAAG;QAC1D,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC;QAC/B,CAAC,CAAC,EAAE,CAAC;IACT,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,iBAAK,CAAC,CAAC,MAAM,CAAC,sBAAK,CAAC,KAAK,CA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AC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;IAErD,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE;QAC3B,OAAO,sBAAK,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,sBAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACrD,CAAC,CAAC,CAAC;AACL,CAAC"}

View File

@ -1,2 +1,3 @@
import { CoreLibrary } from './adapters';
export declare const getStreamByName: CoreLibrary['getStreamByName'];
import * as AP from '@activity-kit/types';
import { CoreLibrary } from '.';
export declare function getStreamByName(this: CoreLibrary, actor: AP.Actor, name: string): Promise<AP.EitherCollection | null>;

View File

@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
exports.getStreamByName = void 0;
const type_utilities_1 = require("@activity-kit/type-utilities");
const utilities_1 = require("@activity-kit/utilities");
const getStreamByName = async function getStreamByName(actor, name) {
async function getStreamByName(actor, name) {
if (!actor.streams) {
return null;
}
@ -22,6 +22,6 @@ const getStreamByName = async function getStreamByName(actor, name) {
}
}
return null;
};
}
exports.getStreamByName = getStreamByName;
//# sourceMappingURL=getStreamByName.js.map

View File

@ -1 +1 @@
{"version":3,"file":"getStreamByName.js","sourceRoot":"","sources":["../src/getStreamByName.ts"],"names":[],"mappings":";;;AACA,iEAAqD;AACrD,uDAAgD;AAIzC,MAAM,eAAe,GAC1B,KAAK,UAAU,eAAe,CAE5B,KAAe,EACf,IAAY;IAEZ,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE;QAClB,OAAO,IAAI,CAAC;KACb;IAED,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,GAAG,CAC/B,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,MAA0B,EAAE,EAAE;QACrD,MAAM,QAAQ,GAAG,IAAA,iBAAK,EAAC,MAAM,CAAC,CAAC;QAE/B,IAAI,CAAC,QAAQ,EAAE;YACb,OAAO,IAAI,CAAC;SACb;QAED,OAAO,MAAM,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;IACxC,CAAC,CAAC,CACH,CAAC;IAEF,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE;QAC5B,IAAI,sBAAK,CAAC,cAAc,CAAC,MAAM,CAAC,EAAE;YAChC,IAAI,MAAM,CAAC,IAAI,KAAK,IAAI,EAAE;gBACxB,OAAO,MAAM,CAAC;aACf;SACF;KACF;IAED,OAAO,IAAI,CAAC;AACd,CAAC,CAAC;AA/BS,QAAA,eAAe,mBA+BxB"}
{"version":3,"file":"getStreamByName.js","sourceRoot":"","sources":["../src/getStreamByName.ts"],"names":[],"mappings":";;;AACA,iEAAqD;AACrD,uDAAgD;AASzC,KAAK,UAAU,eAAe,CAEnC,KAAe,EACf,IAAY;IAEZ,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE;QAClB,OAAO,IAAI,CAAC;KACb;IAED,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,GAAG,CAC/B,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,MAA0B,EAAE,EAAE;QACrD,MAAM,QAAQ,GAAG,IAAA,iBAAK,EAAC,MAAM,CAAC,CAAC;QAE/B,IAAI,CAAC,QAAQ,EAAE;YACb,OAAO,IAAI,CAAC;SACb;QAED,OAAO,MAAM,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;IACxC,CAAC,CAAC,CACH,CAAC;IAEF,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE;QAC5B,IAAI,sBAAK,CAAC,cAAc,CAAC,MAAM,CAAC,EAAE;YAChC,IAAI,MAAM,CAAC,IAAI,KAAK,IAAI,EAAE;gBACxB,OAAO,MAAM,CAAC;aACf;SACF;KACF;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AA9BD,0CA8BC"}

View File

@ -1,7 +1,25 @@
/// <reference types="node" />
import * as AP from '@activity-kit/types';
import { AuthAdapter, CryptoAdapter, DbAdapter, FetchPolyfill, StorageAdapter, CoreLibrary } from './adapters';
export declare class Core implements CoreLibrary {
import { AuthAdapter, CryptoAdapter, DbAdapter, FetchPolyfill, StorageAdapter } from './adapters';
import { findEntityById } from './findEntityById';
import { queryById } from './queryById';
import { expandEntity } from './expandEntity';
import { getPaginatedCollectionItems } from './getPaginatedCollectionItems';
import { expandCollection } from './expandCollection';
import { getActorByUserId } from './getActorByUserId';
import { getStreamByName } from './getStreamByName';
import { broadcast } from './broadcast';
import { getRecipientUrls } from './getRecipientUrls';
declare class CoreFunctions {
findEntityById: typeof findEntityById;
queryById: typeof queryById;
getActorByUserId: typeof getActorByUserId;
getStreamByName: typeof getStreamByName;
expandEntity: typeof expandEntity;
getPaginatedCollectionItems: typeof getPaginatedCollectionItems;
expandCollection: typeof expandCollection;
broadcast: typeof broadcast;
getRecipientUrls: typeof getRecipientUrls;
}
export declare class CoreLibrary extends CoreFunctions implements AuthAdapter, DbAdapter, StorageAdapter, CryptoAdapter {
fetch: FetchPolyfill;
initializeDb?: DbAdapter['initializeDb'];
findAll: DbAdapter['findAll'];
@ -31,17 +49,5 @@ export declare class Core implements CoreLibrary {
db: DbAdapter;
fetch?: FetchPolyfill;
});
findEntityById: (this: CoreLibrary, id: URL) => Promise<AP.Entity | null>;
getActorByUserId: (this: CoreLibrary, userId: string) => Promise<AP.Actor | null>;
getPrivateKey: (this: CoreLibrary, actor: AP.Actor) => Promise<string>;
getStreamByName: (this: CoreLibrary, actor: AP.Actor, name: string) => Promise<AP.EitherCollection | null>;
fetchEntityById: (this: CoreLibrary, id: URL) => Promise<AP.Entity | null>;
queryById: (this: CoreLibrary, id: URL) => Promise<AP.Entity | null>;
expandEntity: (this: CoreLibrary, entity: AP.Entity) => Promise<AP.Entity>;
getCollectionItems: (this: CoreLibrary, entity: AP.Collection | AP.OrderedCollection) => AP.EntityReference[];
getPaginatedCollectionItems: (this: CoreLibrary, collection: AP.Collection | AP.OrderedCollection) => Promise<AP.EntityReference[]>;
expandCollection: (this: CoreLibrary, collection: AP.EitherCollection) => Promise<AP.EitherCollection>;
broadcast: (this: CoreLibrary, activity: AP.Activity, actor: AP.Actor) => Promise<unknown>;
getRecipientUrls: (this: CoreLibrary, activity: AP.Activity) => Promise<URL[]>;
}
export { AuthAdapter, CryptoAdapter, DbAdapter, DbOptions, FetchPolyfill, StorageAdapter, CoreLibrary, Plugin, Routes, } from './adapters';
export { AuthAdapter, CryptoAdapter, DbAdapter, DbOptions, FetchPolyfill, StorageAdapter, Plugin, Routes, } from './adapters';

View File

@ -3,66 +3,61 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DbOptions = exports.Core = void 0;
exports.DbOptions = exports.CoreLibrary = void 0;
const isomorphic_fetch_1 = __importDefault(require("isomorphic-fetch"));
const findEntityById_1 = require("./findEntityById");
const fetchEntityById_1 = require("./fetchEntityById");
const queryById_1 = require("./queryById");
const expandEntity_1 = require("./expandEntity");
const getPrivateKey_1 = require("./getPrivateKey");
const getCollectionItems_1 = require("./getCollectionItems");
const getPaginatedCollectionItems_1 = require("./getPaginatedCollectionItems");
const expandCollection_1 = require("./expandCollection");
const getActorByUserId_1 = require("./getActorByUserId");
const getStreamByName_1 = require("./getStreamByName");
const broadcast_1 = require("./broadcast");
const getRecipientUrls_1 = require("./getRecipientUrls");
class Core {
constructor(adapters) {
var _a;
class CoreFunctions {
constructor() {
this.findEntityById = findEntityById_1.findEntityById;
this.getActorByUserId = getActorByUserId_1.getActorByUserId;
this.getPrivateKey = getPrivateKey_1.getPrivateKey;
this.getStreamByName = getStreamByName_1.getStreamByName;
this.fetchEntityById = fetchEntityById_1.fetchEntityById;
this.queryById = queryById_1.queryById;
this.getActorByUserId = getActorByUserId_1.getActorByUserId;
this.getStreamByName = getStreamByName_1.getStreamByName;
this.expandEntity = expandEntity_1.expandEntity;
this.getCollectionItems = getCollectionItems_1.getCollectionItems;
this.getPaginatedCollectionItems = getPaginatedCollectionItems_1.getPaginatedCollectionItems;
this.expandCollection = expandCollection_1.expandCollection;
this.broadcast = broadcast_1.broadcast;
this.getRecipientUrls = getRecipientUrls_1.getRecipientUrls;
this.fetch = (_a = adapters.fetch) !== null && _a !== void 0 ? _a : isomorphic_fetch_1.default;
if (adapters.db.initializeDb) {
this.initializeDb = async () => { var _a, _b; return await ((_b = (_a = adapters.db).initializeDb) === null || _b === void 0 ? void 0 : _b.call(_a)); };
}
this.findAll = async (collection, matchingObject) => await adapters.db.findAll(collection, matchingObject);
this.findOne = async (collection, matchingObject, options) => await adapters.db.findOne(collection, matchingObject, options);
this.findStringIdByValue = async (dbCollection, value) => await adapters.db.findStringIdByValue(dbCollection, value);
this.findStringValueById = async (dbCollection, _id) => await adapters.db.findStringValueById(dbCollection, _id);
this.insertItem = async (path, url) => await adapters.db.insertItem(path, url);
this.removeItem = async (path, url) => await adapters.db.removeItem(path, url);
this.insertOrderedItem = async (path, url) => await adapters.db.insertOrderedItem(path, url);
this.removeOrderedItem = async (path, url) => await adapters.db.removeOrderedItem(path, url);
this.saveEntity = async (entity) => await adapters.db.saveEntity(entity);
this.saveString = async (dbCollection, _id, value) => await adapters.db.saveString(dbCollection, _id, value);
this.getHttpSignature = async (foreignTarget, actorId, privateKey, entity) => await adapters.crypto.getHttpSignature(foreignTarget, actorId, privateKey, entity);
this.generateKeyPair = async () => await adapters.crypto.generateKeyPair();
this.hashPassword = async (password, salt) => await adapters.crypto.hashPassword(password, salt);
this.randomBytes = async (numberOfBytes) => await adapters.crypto.randomBytes(numberOfBytes);
this.getGuid = async () => await adapters.crypto.randomBytes(16);
this.getTokenByUserId = async (userId) => await adapters.auth.getTokenByUserId(userId);
this.createUser = async ({ email, password, preferredUsername, }) => await adapters.auth.createUser({
email,
password,
preferredUsername,
});
this.getUserIdByToken = async (token) => await adapters.auth.getUserIdByToken(token);
this.authenticatePassword = async (email, password) => await adapters.auth.authenticatePassword(email, password);
this.upload = async (file) => await adapters.storage.upload(file);
}
}
exports.Core = Core;
class CoreLibrary extends CoreFunctions {
constructor(adapters) {
var _a;
super();
this.fetch = (_a = adapters.fetch) !== null && _a !== void 0 ? _a : isomorphic_fetch_1.default;
if (adapters.db.initializeDb) {
this.initializeDb = adapters.db.initializeDb.bind(adapters.db);
}
this.findAll = adapters.db.findAll.bind(adapters.db);
this.findOne = adapters.db.findOne.bind(adapters.db);
this.findStringIdByValue = adapters.db.findStringIdByValue.bind(adapters.db);
this.findStringValueById = adapters.db.findStringValueById.bind(adapters.db);
this.insertItem = adapters.db.insertItem.bind(adapters.db);
this.removeItem = adapters.db.removeItem.bind(adapters.db);
this.insertOrderedItem = adapters.db.insertOrderedItem.bind(adapters.db);
this.removeOrderedItem = adapters.db.removeOrderedItem.bind(adapters.db);
this.saveEntity = adapters.db.saveEntity.bind(adapters.db);
this.saveString = adapters.db.saveString.bind(adapters.db);
this.getHttpSignature = adapters.crypto.getHttpSignature.bind(adapters.crypto);
this.generateKeyPair = adapters.crypto.generateKeyPair.bind(adapters.crypto);
this.hashPassword = adapters.crypto.hashPassword.bind(adapters.crypto);
this.randomBytes = adapters.crypto.randomBytes.bind(adapters.crypto);
this.getGuid = async () => await adapters.crypto.randomBytes(16);
this.getTokenByUserId = adapters.auth.getTokenByUserId.bind(adapters.auth);
this.createUser = adapters.auth.createUser.bind(adapters.auth);
this.getUserIdByToken = adapters.auth.getUserIdByToken.bind(adapters.auth);
this.authenticatePassword = adapters.auth.authenticatePassword.bind(adapters.auth);
this.upload = adapters.storage.upload.bind(adapters.storage);
}
}
exports.CoreLibrary = CoreLibrary;
var adapters_1 = require("./adapters");
Object.defineProperty(exports, "DbOptions", { enumerable: true, get: function () { return adapters_1.DbOptions; } });
//# sourceMappingURL=index.js.map

View File

@ -1 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;AACA,wEAAqC;AAYrC,qDAAkD;AAClD,uDAAoD;AACpD,2CAAwC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AC,MAAM,CAAC,eAAe,CAAC,IAAI,CACzD,QAAQ,CAAC,MAAM,CAChB,CAAC;QAEF,IAAI,CAAC,YAAY,GAAG,QAAQ,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;QAEvE,IAAI,CAAC,WAAW,GAAG,QAAQ,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;QAErE,IAAI,CAAC,OAAO,GAAG,KAAK,IAAI,EAAE,CAAC,MAAM,QAAQ,CAAC,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;QAEjE,IAAI,CAAC,gBAAgB,GAAG,QAAQ,CAAC,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAE3E,IAAI,CAAC,UAAU,GAAG,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAE/D,IAAI,CAAC,gBAAgB,GAAG,QAAQ,CAAC,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAE3E,IAAI,CAAC,oBAAoB,GAAG,QAAQ,CAAC,IAAI,CAAC,oBAAoB,CAAC,IAAI,CACjE,QAAQ,CAAC,IAAI,CACd,CAAC;QAEF,IAAI,CAAC,MAAM,GAAG,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IAC/D,CAAC;CACF;AAjGD,kCAiGC;AAED,uCASoB;AALlB,qGAAA,SAAS,OAAA"}

View File

@ -1,2 +1,4 @@
import { CoreLibrary } from './adapters';
export declare const queryById: CoreLibrary['queryById'];
/// <reference types="node" />
import * as AP from '@activity-kit/types';
import { CoreLibrary } from '.';
export declare function queryById(this: CoreLibrary, id: URL): Promise<AP.Entity | null>;

View File

@ -27,11 +27,12 @@ exports.queryById = void 0;
const AP = __importStar(require("@activity-kit/types"));
const type_utilities_1 = require("@activity-kit/type-utilities");
const utilities_1 = require("@activity-kit/utilities");
const queryById = async function queryById(id) {
const getPrivateKey_1 = require("./util/getPrivateKey");
async function queryById(id) {
if ((0, utilities_1.isLocal)(id)) {
return await this.findEntityById(id);
}
const fetchedEntity = await this.fetchEntityById(id);
const fetchedEntity = await fetchEntityByUrl.bind(this)(id);
if (!fetchedEntity ||
type_utilities_1.guard.isApType(fetchedEntity, AP.ExtendedObjectTypes.TOMBSTONE)) {
const foundEntity = await this.findEntityById(id);
@ -40,6 +41,105 @@ const queryById = async function queryById(id) {
}
}
return fetchedEntity;
};
}
exports.queryById = queryById;
async function fetchEntityByUrl(id) {
const isJsonLdContentType = await getIsJsonLdContentType.bind(this)(id);
if (!isJsonLdContentType) {
return null;
}
const botActor = await getBotActor.bind(this)();
type_utilities_1.assert.exists(botActor);
const botActorId = (0, utilities_1.getId)(botActor);
type_utilities_1.assert.exists(botActorId);
const privateKey = await getPrivateKey_1.getPrivateKey.bind(this)(botActor);
type_utilities_1.assert.exists(privateKey);
const { dateHeader, signatureHeader } = await this.getHttpSignature(id, botActorId, privateKey);
const headers = {
date: dateHeader,
signature: signatureHeader,
};
const fetchedJson = await fetchJsonByUrl.bind(this)(id, headers);
if (!fetchedJson) {
return null;
}
const convertedEntity = (0, utilities_1.convertJsonToEntity)(fetchedJson);
if (!convertedEntity) {
return null;
}
const entity = (0, utilities_1.compressEntity)(convertedEntity);
if (!entity) {
return null;
}
await this.saveEntity(entity);
return entity;
}
async function fetchJsonByUrl(url, headers) {
const config = {
headers: {
...headers,
[utilities_1.ACCEPT_HEADER]: utilities_1.ACTIVITYSTREAMS_CONTENT_TYPE,
},
};
return await this.fetch(url.href, config)
.then(handleResponse)
.catch(handleError);
}
async function handleResponse(response) {
var _a;
const data = (_a = type_utilities_1.cast.isPlainObject(await response.json())) !== null && _a !== void 0 ? _a : null;
if (!data) {
return null;
}
if (response.status === 200) {
return data;
}
if (response.status === 400 || response.status === 410) {
if ('@context' in data) {
return data;
}
else {
return {
'@context': utilities_1.ACTIVITYSTREAMS_CONTEXT,
type: AP.ExtendedObjectTypes.TOMBSTONE,
id: response.url,
url: response.url,
};
}
}
if (response.status >= 500) {
return null;
}
return data;
}
async function handleError(error) {
console.log(`${error}`);
return null;
}
async function getContentType(url) {
var _a;
const response = await this.fetch(url.toString(), {
method: 'HEAD',
headers: {
[utilities_1.ACCEPT_HEADER]: utilities_1.ACTIVITYSTREAMS_CONTENT_TYPE,
},
});
return (_a = response.headers.get(utilities_1.CONTENT_TYPE_HEADER)) !== null && _a !== void 0 ? _a : null;
}
async function getIsJsonLdContentType(url) {
const contentType = await getContentType.bind(this)(url);
if (!contentType) {
return false;
}
return (contentType.includes(utilities_1.ACTIVITYSTREAMS_CONTENT_TYPE) ||
contentType.includes(utilities_1.LINKED_DATA_CONTENT_TYPE) ||
contentType.includes(utilities_1.JSON_CONTENT_TYPE));
}
async function getBotActor() {
var _a;
const botActor = await this.findOne('entity', {
preferredUsername: utilities_1.SERVER_ACTOR_USERNAME,
});
return (_a = type_utilities_1.cast.isApActor(botActor)) !== null && _a !== void 0 ? _a : null;
}
//# sourceMappingURL=queryById.js.map

View File

@ -1 +1 @@
{"version":3,"file":"queryById.js","sourceRoot":"","sources":["../src/queryById.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wDAA0C;AAC1C,iEAAqD;AACrD,uDAAkD;AAI3C,MAAM,SAAS,GAA6B,KAAK,UAAU,SAAS,CAEzE,EAAO;IAEP,IAAI,IAAA,mBAAO,EAAC,EAAE,CAAC,EAAE;QACf,OAAO,MAAM,IAAI,CAAC,cAAc,CAAC,EAAE,CAAC,CAAC;KACtC;IAED,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,EAAE,CAAC,CAAC;IAErD,IACE,CAAC,aAAa;QACd,sBAAK,CAAC,QAAQ,CACZ,aAAa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+BAAmB,CAAC,mCAAI,IAAI,CAAC;AAC3D,CAAC;AAOD,KAAK,UAAU,sBAAsB,CAEnC,GAAQ;IAER,MAAM,WAAW,GAAG,MAAM,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;IAEzD,IAAI,CAAC,WAAW,EAAE;QAChB,OAAO,KAAK,CAAC;KACd;IAED,OAAO,CACL,WAAW,CAAC,QAAQ,CAAC,wCAA4B,CAAC;QAClD,WAAW,CAAC,QAAQ,CAAC,oCAAwB,CAAC;QAC9C,WAAW,CAAC,QAAQ,CAAC,6BAAiB,CAAC,CACxC,CAAC;AACJ,CAAC;AAUD,KAAK,UAAU,WAAW;;IACxB,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE;QAC5C,iBAAiB,EAAE,iCAAqB;KACzC,CAAC,CAAC;IAEH,OAAO,MAAA,qBAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,mCAAI,IAAI,CAAC;AAC1C,CAAC"}

View File

@ -0,0 +1,3 @@
import * as AP from '@activity-kit/types';
import { CoreLibrary } from '..';
export declare function getPrivateKey(this: CoreLibrary, actor: AP.Actor): Promise<string>;

View File

@ -0,0 +1,15 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPrivateKey = void 0;
async function getPrivateKey(actor) {
if (!actor.preferredUsername) {
return '';
}
const userId = await this.findStringIdByValue('username', actor.preferredUsername);
if (!userId) {
return '';
}
return await this.findStringValueById('privateKey', userId);
}
exports.getPrivateKey = getPrivateKey;
//# sourceMappingURL=getPrivateKey.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"getPrivateKey.js","sourceRoot":"","sources":["../../src/util/getPrivateKey.ts"],"names":[],"mappings":";;;AASO,KAAK,UAAU,aAAa,CAEjC,KAAe;IAEf,IAAI,CAAC,KAAK,CAAC,iBAAiB,EAAE;QAC5B,OAAO,EAAE,CAAC;KACX;IAED,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,mBAAmB,CAC3C,UAAU,EACV,KAAK,CAAC,iBAAiB,CACxB,CAAC;IAEF,IAAI,CAAC,MAAM,EAAE;QACX,OAAO,EAAE,CAAC;KACX;IAED,OAAO,MAAM,IAAI,CAAC,mBAAmB,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC;AAC9D,CAAC;AAlBD,sCAkBC"}

View File

@ -1,10 +1,7 @@
import * as AP from '@activity-kit/types';
import { AuthAdapter } from './Auth';
import { CryptoAdapter } from './Crypto';
import { DbAdapter } from './Db';
import { StorageAdapter } from './Storage';
import { FetchPolyfill } from './FetchPolyfill';
export { AuthAdapter } from './Auth';
export { DbAdapter, DbOptions } from './Db';
@ -21,41 +18,3 @@ export type Adapters = {
storage: StorageAdapter;
crypto: CryptoAdapter;
};
export type CoreLibrary = AuthAdapter &
DbAdapter &
StorageAdapter &
CryptoAdapter & {
fetch: FetchPolyfill;
getGuid: () => Promise<string>;
findEntityById: (this: CoreLibrary, id: URL) => Promise<AP.Entity | null>;
getActorByUserId: (
this: CoreLibrary,
userId: string,
) => Promise<AP.Actor | null>;
getStreamByName: (
this: CoreLibrary,
actor: AP.Actor,
name: string,
) => Promise<AP.EitherCollection | null>;
fetchEntityById: (this: CoreLibrary, id: URL) => Promise<AP.Entity | null>;
queryById: (this: CoreLibrary, id: URL) => Promise<AP.Entity | null>;
expandEntity: (this: CoreLibrary, entity: AP.Entity) => Promise<AP.Entity>;
getPaginatedCollectionItems: (
this: CoreLibrary,
collection: AP.Collection | AP.OrderedCollection,
) => Promise<AP.EntityReference[]>;
expandCollection: (
this: CoreLibrary,
collection: AP.EitherCollection,
) => Promise<AP.EitherCollection>;
getRecipientUrls: (
this: CoreLibrary,
activity: AP.Activity,
) => Promise<URL[]>;
broadcast: (
this: CoreLibrary,
activity: AP.Activity,
actor: AP.Actor,
) => Promise<unknown>;
};

View File

@ -11,14 +11,15 @@ import {
getId,
} from '@activity-kit/utilities';
import { CoreLibrary } from './adapters';
import { CoreLibrary } from '.';
import { getPrivateKey } from './util/getPrivateKey';
/**
* Send an Activity to all of its recipients on behalf of an Actor.
*
* @returns A record of each URL and the HTTP status code of the response.
*/
export const broadcast: CoreLibrary['broadcast'] = async function broadcast(
export async function broadcast(
this: CoreLibrary,
activity: AP.Activity,
actor: AP.Actor,
@ -26,17 +27,19 @@ export const broadcast: CoreLibrary['broadcast'] = async function broadcast(
const activityWithContext = applyContext(activity);
const cleanedActivity = cleanProps(activityWithContext);
const plainEntity = convertEntityToJson(cleanedActivity);
const recipientInboxUrls = await getRecipientInboxUrls.bind(this)(
activity,
actor,
);
const sendToRecipient = (recipientInboxUrl: URL) =>
signAndSendToInboxUrl.call(this, recipientInboxUrl, actor, plainEntity);
const promises = recipientInboxUrls.map(sendToRecipient);
const resultEntries = await Promise.all(promises);
return Object.fromEntries(resultEntries);
};
}
/**
* Send to a single recipient on behalf of an Actor.
@ -50,6 +53,37 @@ async function signAndSendToInboxUrl(
actor: AP.Actor,
plainEntity: Record<string, unknown>,
): Promise<[string, number]> {
const headers = await getHeaders.bind(this)(
actor,
foreignActorInbox,
plainEntity,
);
const statusCode = await this.fetch(foreignActorInbox.href, {
method: 'post',
body: JSON.stringify(plainEntity),
headers,
})
.then(async (res) => {
return res.status;
})
.catch(() => {
return 0;
});
return [foreignActorInbox.href, statusCode];
}
/**
* Get the headers for an Activity.
* @returns A record of headers.
*/
async function getHeaders(
this: CoreLibrary,
actor: AP.Actor,
foreignActorInbox: URL,
plainEntity: Record<string, unknown>,
): Promise<Record<string, string>> {
const actorId = getId(actor);
assert.exists(actorId);
@ -68,7 +102,7 @@ async function signAndSendToInboxUrl(
throw new Error('Failed to sign Activity');
}
const headers = {
return {
[CONTENT_TYPE_HEADER]: ACTIVITYSTREAMS_CONTENT_TYPE,
[ACCEPT_HEADER]: ACTIVITYSTREAMS_CONTENT_TYPE,
Host: foreignActorInbox.hostname,
@ -76,24 +110,12 @@ async function signAndSendToInboxUrl(
Digest: digestHeader,
Signature: signatureHeader,
};
const statusCode = await this.fetch(foreignActorInbox.href, {
method: 'post',
body: JSON.stringify(plainEntity),
headers,
})
.then(async (res) => {
return res.status;
})
.catch(() => {
return 0;
});
return [foreignActorInbox.href, statusCode];
}
/**
* Get the inbox URLs of all recipients of an Activity.
*
* @returns An array of inbox URLs.
*/
async function getRecipientInboxUrls(
this: CoreLibrary,
@ -107,7 +129,7 @@ async function getRecipientInboxUrls(
return null;
}
const foundEntity = await this.fetchEntityById(recipientUrl);
const foundEntity = await this.queryById(recipientUrl);
if (!guard.isApActor(foundEntity)) {
return null;
@ -128,26 +150,3 @@ async function getRecipientInboxUrls(
return deduplicateUrls(filteredUrls);
}
/**
* Get the private key of an Actor.
*/
async function getPrivateKey(
this: CoreLibrary,
actor: AP.Actor,
): Promise<string> {
if (!actor.preferredUsername) {
return '';
}
const userId = await this.findStringIdByValue(
'username',
actor.preferredUsername,
);
if (!userId) {
return '';
}
return await this.findStringValueById('privateKey', userId);
}

View File

@ -1,7 +1,7 @@
import * as AP from '@activity-kit/types';
import { guard } from '@activity-kit/type-utilities';
import { CoreLibrary } from './adapters';
import { CoreLibrary } from '.';
/**
* Given a Collection or OrderedCollection, convert its item/orderedItem
@ -9,49 +9,64 @@ import { CoreLibrary } from './adapters';
*
* @returns A Promise that resolves to the expanded Collection.
*/
export const expandCollection: CoreLibrary['expandCollection'] =
async function expandCollection(
this: CoreLibrary,
collection: AP.EitherCollection,
): Promise<AP.EitherCollection> {
const expandedCollection = {
...collection,
};
if (isArray(collection.orderedItems)) {
const expandPromises = collection.orderedItems
.filter(isEntityReference)
.map(query.bind(this));
const expanded = await Promise.all(expandPromises);
expandedCollection.orderedItems = expanded;
}
if (isArray(collection.items)) {
const expandPromises = collection.items
.filter(isEntityReference)
.map(query.bind(this));
const expanded = await Promise.all(expandPromises);
expandedCollection.items = expanded;
}
return expandedCollection;
export async function expandCollection(
this: CoreLibrary,
collection: AP.EitherCollection,
): Promise<AP.EitherCollection> {
const expandedCollection = {
...collection,
};
if (isArray(collection.orderedItems)) {
const expandPromises = collection.orderedItems
.filter(isEntityReference)
.map(queryItem.bind(this));
const expanded = await Promise.all(expandPromises);
expandedCollection.orderedItems = expanded;
}
if (isArray(collection.items)) {
const expandPromises = collection.items
.filter(isEntityReference)
.map(queryItem.bind(this));
const expanded = await Promise.all(expandPromises);
expandedCollection.items = expanded;
}
return expandedCollection;
}
/**
* Determine if a value is an EntityReference.
*/
function isEntityReference(value: unknown): boolean {
return guard.isApEntity(value) || guard.isUrl(value);
}
/**
* Determine if a value is an array of EntityReferences.
*
* @returns Boolean representing whether the value is an array of
* EntityReferences.
*/
function isArray(
items: AP.OrArray<AP.EntityReference> | undefined,
): items is Array<AP.Entity> {
return guard.isArray(items) && items.length > 0;
}
async function query(
/**
* Query an EntityReference and return the full Entity.
*
* If the EntityReference is already an Entity, it will be returned as-is.
*
* @returns A Promise that resolves to the full Entity.
*/
async function queryItem(
this: CoreLibrary,
item: AP.EntityReference,
): Promise<AP.EntityReference> {

View File

@ -1,7 +1,7 @@
import * as AP from '@activity-kit/types';
import { cast, guard } from '@activity-kit/type-utilities';
import { CoreLibrary } from './adapters';
import { CoreLibrary } from '.';
/**
* Keys that should not be expanded.
@ -22,16 +22,17 @@ const selfReferentialKeys = [
*
* @returns A Promise that resolves to the expanded Entity.
*/
export const expandEntity: CoreLibrary['expandEntity'] =
async function expandEntity(
this: CoreLibrary,
entity: AP.Entity,
): Promise<AP.Entity> {
return cast.isApEntity(await expandObject.bind(this)(entity)) ?? entity;
};
export async function expandEntity(
this: CoreLibrary,
entity: AP.Entity,
): Promise<AP.Entity> {
return cast.isApEntity(await expandObject.bind(this)(entity)) ?? entity;
}
/**
* Expand all references in an object.
*
* @returns A Promise that resolves to an object with all references expanded.
*/
async function expandObject(
this: CoreLibrary,
@ -49,6 +50,8 @@ async function expandObject(
/**
* Expand a single entry in an object, which may be a reference to another
* Entity.
*
* @returns A Promise that resolves to the expanded entry in the object.
*/
async function expandEntry(
this: CoreLibrary,

View File

@ -1,221 +0,0 @@
import * as AP from '@activity-kit/types';
import { cast, assert } from '@activity-kit/type-utilities';
import {
ACCEPT_HEADER,
ACTIVITYSTREAMS_CONTENT_TYPE,
convertJsonToEntity,
compressEntity,
LINKED_DATA_CONTENT_TYPE,
JSON_CONTENT_TYPE,
getId,
SERVER_ACTOR_USERNAME,
ACTIVITYSTREAMS_CONTEXT,
CONTENT_TYPE_HEADER,
} from '@activity-kit/utilities';
import { CoreLibrary } from './adapters';
import { Body } from './adapters/FetchPolyfill';
/**
* Fetch an Entity by its URL.
*
* @returns The fetched Entity or null if the URL does not represent an Entity.
*/
export const fetchEntityById: CoreLibrary['fetchEntityById'] =
async function fetchEntityById(
this: CoreLibrary,
id: URL,
): Promise<AP.Entity | null> {
const isJsonLdContentType = await getIsJsonLdContentType.bind(this)(id);
if (!isJsonLdContentType) {
return null;
}
const botActor = await getBotActor.bind(this)();
assert.exists(botActor);
const botActorId = getId(botActor);
assert.exists(botActorId);
const privateKey = await getPrivateKey.bind(this)(botActor);
assert.exists(privateKey);
const { dateHeader, signatureHeader } = await this.getHttpSignature(
id,
botActorId,
privateKey,
);
const headers = {
date: dateHeader,
signature: signatureHeader,
};
const fetchedJson = await fetchJsonByUrl.bind(this)(id, headers);
if (!fetchedJson) {
return null;
}
const convertedEntity = convertJsonToEntity(fetchedJson);
if (!convertedEntity) {
return null;
}
const entity = compressEntity(convertedEntity);
if (!entity) {
return null;
}
await this.saveEntity(entity);
return entity;
};
/**
* Fetch a JSON object from a URL using the provided headers.
*/
async function fetchJsonByUrl(
this: CoreLibrary,
url: URL,
headers: Record<string, string>,
): Promise<Record<string, unknown> | null> {
const config = {
headers: {
...headers,
[ACCEPT_HEADER]: ACTIVITYSTREAMS_CONTENT_TYPE,
},
};
return await this.fetch(url.href, config)
.then(handleResponse)
.catch(handleError);
}
/**
* Handle a response from a fetch request.
*/
async function handleResponse(
response: Body,
): Promise<Record<string, unknown> | null> {
const data = cast.isPlainObject(await response.json()) ?? null;
if (!data) {
return null;
}
if (response.status === 200) {
return data;
}
if (response.status === 400 || response.status === 410) {
if ('@context' in data) {
// Likely a tombstone
return data;
} else {
// Return a tombstone
return {
'@context': ACTIVITYSTREAMS_CONTEXT,
type: AP.ExtendedObjectTypes.TOMBSTONE,
id: response.url,
url: response.url,
};
}
}
if (response.status >= 500) {
return null;
}
return data;
}
/**
* Handle an error from a fetch request.
*/
async function handleError(error: Error) {
console.log(`${error}`);
return null;
}
/**
* Get the content type of a URL.
*
* A HEAD request is used to determine if a URL is a JSON-LD object.
*/
async function getContentType(
this: CoreLibrary,
url: URL,
): Promise<string | null> {
const response = await this.fetch(url.toString(), {
method: 'HEAD',
headers: {
[ACCEPT_HEADER]: ACTIVITYSTREAMS_CONTENT_TYPE,
},
});
return response.headers.get(CONTENT_TYPE_HEADER) ?? null;
}
/**
* Check if a URL returns a content type that represent a JSON-LD object.
*/
async function getIsJsonLdContentType(
this: CoreLibrary,
url: URL,
): Promise<boolean> {
const contentType = await getContentType.bind(this)(url);
if (!contentType) {
return false;
}
return (
contentType.includes(ACTIVITYSTREAMS_CONTENT_TYPE) ||
contentType.includes(LINKED_DATA_CONTENT_TYPE) ||
contentType.includes(JSON_CONTENT_TYPE)
);
}
/**
* Get the server Actor.
*
* Mastodon in secure mode requires that all requests include a signature of the
* Actor that is making the request. We use the server Actor.
*/
async function getBotActor(this: CoreLibrary) {
const botActor = await this.findOne('entity', {
preferredUsername: SERVER_ACTOR_USERNAME,
});
return cast.isApActor(botActor) ?? null;
}
/**
* Get the private key of an Actor.
*/
async function getPrivateKey(
this: CoreLibrary,
actor: AP.Actor,
): Promise<string> {
if (!actor.preferredUsername) {
return '';
}
const userId = await this.findStringIdByValue(
'username',
actor.preferredUsername,
);
if (!userId) {
return '';
}
return await this.findStringValueById('privateKey', userId);
}

View File

@ -1,14 +1,18 @@
import * as AP from '@activity-kit/types';
import { getCollectionNameByUrl } from '@activity-kit/utilities';
import { CoreLibrary } from './adapters';
import { CoreLibrary } from '.';
export const findEntityById: CoreLibrary['fetchEntityById'] =
async function findEntityById(
this: CoreLibrary,
id: URL,
): Promise<AP.Entity | null> {
const collectionName = getCollectionNameByUrl(id);
/**
* Finds an Entity by its ID, which is a URL.
*
* @returns The Entity, or null if not found.
*/
export async function findEntityById(
this: CoreLibrary,
id: URL,
): Promise<AP.Entity | null> {
const collectionName = getCollectionNameByUrl(id);
return await this.findOne(collectionName, { id: id.href });
};
return await this.findOne(collectionName, { id: id.href });
}

View File

@ -1,23 +1,26 @@
import * as AP from '@activity-kit/types';
import { guard } from '@activity-kit/type-utilities';
import { CoreLibrary } from './adapters';
import { CoreLibrary } from '.';
export const getActorByUserId: CoreLibrary['getActorByUserId'] =
async function getActorByUserId(
this: CoreLibrary,
userId: string,
): Promise<AP.Actor | null> {
const preferredUsername = await this.findStringValueById(
'username',
userId,
);
/**
* Finds an Actor by its User ID.
*
* The User ID is stored in the database and is not the same as the Actor's ID.
*
* @returns The Actor, or null if not found.
*/
export async function getActorByUserId(
this: CoreLibrary,
userId: string,
): Promise<AP.Actor | null> {
const preferredUsername = await this.findStringValueById('username', userId);
const user = await this.findOne('entity', { preferredUsername });
const user = await this.findOne('entity', { preferredUsername });
if (!guard.isApActor(user)) {
return null;
}
if (!guard.isApActor(user)) {
return null;
}
return user;
};
return user;
}

View File

@ -1,28 +0,0 @@
import * as AP from '@activity-kit/types';
import { guard } from '@activity-kit/type-utilities';
import { CoreLibrary } from './adapters';
export const getCollectionItems: CoreLibrary['getCollectionItems'] =
function getCollectionItems(
this: CoreLibrary,
entity: AP.EitherCollection,
): AP.EntityReference[] {
const collectionItems: AP.EntityReference[] = [];
if (guard.isArray(entity.orderedItems) && entity.orderedItems.length) {
const orderedItems = entity.orderedItems.filter((item) => {
return guard.isApEntity(item) || guard.isUrl(item);
});
collectionItems.push(...orderedItems);
} else if (guard.isArray(entity.items) && entity.items.length) {
const items = entity.items.filter((item) => {
return guard.isApEntity(item) || guard.isUrl(item);
});
collectionItems.push(...items);
}
return collectionItems;
};

View File

@ -2,69 +2,77 @@ import * as AP from '@activity-kit/types';
import { guard } from '@activity-kit/type-utilities';
import { getId } from '@activity-kit/utilities';
import { CoreLibrary } from './adapters';
import { CoreLibrary } from '.';
export const getPaginatedCollectionItems: CoreLibrary['getPaginatedCollectionItems'] =
async function getPaginatedCollectionItems(
this: CoreLibrary,
collection: AP.EitherCollection,
): Promise<AP.EntityReference[]> {
const firstCollectionPageId = getId(collection.first);
/**
* Given a Collection or OrderedCollection, traverse its pages and return all
* items.
*
* This is useful for getting all items in a foreign Collection, which may be
* paginated.
*
* @returns A Promise that resolves to an array of all items in the Collection.
*/
export async function getPaginatedCollectionItems(
this: CoreLibrary,
collection: AP.EitherCollection,
): Promise<AP.EntityReference[]> {
const firstCollectionPageId = getId(collection.first);
if (!firstCollectionPageId) {
// TODO .getArray()
if (!firstCollectionPageId) {
// TODO .getArray()
if (guard.isArray(collection.orderedItems)) {
return collection.orderedItems;
}
if (guard.isArray(collection.items)) {
return collection.items;
}
return [];
if (guard.isArray(collection.orderedItems)) {
return collection.orderedItems;
}
const firstCollectionPage = await this.queryById(firstCollectionPageId);
if (guard.isArray(collection.items)) {
return collection.items;
}
return [];
}
const firstCollectionPage = await this.queryById(firstCollectionPageId);
if (
!guard.isApTypeOf<AP.CollectionPage>(
firstCollectionPage,
AP.CollectionPageTypes,
)
) {
return [];
}
const collectionItems: AP.EntityReference[][] = [];
let nextCollectionPage = firstCollectionPage;
while (nextCollectionPage) {
if (guard.isArray(nextCollectionPage.orderedItems)) {
collectionItems.push(nextCollectionPage.orderedItems);
}
if (guard.isArray(nextCollectionPage.items)) {
collectionItems.push(nextCollectionPage.items);
}
const nextPageId = getId(nextCollectionPage.next);
if (!guard.exists(nextPageId)) {
break;
}
const nextPage = await this.queryById(nextPageId);
if (
!guard.isApTypeOf<AP.CollectionPage>(
firstCollectionPage,
AP.CollectionPageTypes,
)
!guard.isApTypeOf<AP.CollectionPage>(nextPage, AP.CollectionPageTypes)
) {
return [];
break;
}
const collectionItems: AP.EntityReference[][] = [];
nextCollectionPage = nextPage;
}
let nextCollectionPage = firstCollectionPage;
while (nextCollectionPage) {
if (guard.isArray(nextCollectionPage.orderedItems)) {
collectionItems.push(nextCollectionPage.orderedItems);
}
if (guard.isArray(nextCollectionPage.items)) {
collectionItems.push(nextCollectionPage.items);
}
const nextPageId = getId(nextCollectionPage.next);
if (!guard.exists(nextPageId)) {
break;
}
const nextPage = await this.queryById(nextPageId);
if (
!guard.isApTypeOf<AP.CollectionPage>(nextPage, AP.CollectionPageTypes)
) {
break;
}
nextCollectionPage = nextPage;
}
return collectionItems.flat();
};
return collectionItems.flat();
}

View File

@ -1,60 +0,0 @@
import * as AP from '@activity-kit/types';
import { guard } from '@activity-kit/type-utilities';
import { deduplicateUrls, getId } from '@activity-kit/utilities';
import { CoreLibrary } from './adapters';
export const getRecipientInboxUrls: CoreLibrary['getRecipientInboxUrls'] =
async function getRecipientInboxUrls(
this: CoreLibrary,
activity: AP.Activity,
actor: AP.Actor,
inboxesOnly?: boolean,
): Promise<URL[]> {
const recipientUrls = await this.getRecipientUrls(activity);
const recipientInboxUrls = await Promise.all(
recipientUrls.map(async (recipientUrl) => {
return await mapRecipientUrl.bind(this)(
recipientUrl,
actor,
inboxesOnly,
);
}),
);
return deduplicateUrls(recipientInboxUrls.flat().filter(guard.isUrl));
};
async function mapRecipientUrl(
this: CoreLibrary,
recipientUrl: URL,
actor: AP.Actor,
inboxesOnly?: boolean,
) {
if (recipientUrl.href === getId(actor)?.href) {
return [];
}
const foundEntity = await this.fetchEntityById(recipientUrl);
if (!guard.isApActor(foundEntity)) {
return [];
}
if (!inboxesOnly) {
if (foundEntity.endpoints) {
if (guard.isUrl(foundEntity.endpoints.sharedInbox)) {
return [foundEntity.endpoints.sharedInbox];
}
}
}
const inboxId = getId(foundEntity.inbox);
if (guard.isUrl(inboxId)) {
return [inboxId];
}
return [];
}

View File

@ -1,41 +1,49 @@
import * as AP from '@activity-kit/types';
import { guard } from '@activity-kit/type-utilities';
import { getId, PUBLIC_ACTOR, deduplicateUrls } from '@activity-kit/utilities';
import { deduplicateUrls, PUBLIC_ACTOR, getId } from '@activity-kit/utilities';
import { CoreLibrary } from './adapters';
import { CoreLibrary } from '.';
export const getRecipientUrls: CoreLibrary['getRecipientUrls'] =
async function getRecipientUrls(
this: CoreLibrary,
activity: AP.Activity,
): Promise<URL[]> {
const tags =
guard.isApCoreObject(activity.object) && activity.object.tag
? getArray(activity.object.tag)
: [];
const mentions = tags.map(getId).filter(guard.isUrl);
/**
* Given an Activity, get the URLs of all recipients.
*
* @returns An array of recipient URLs.
*/
export async function getRecipientUrls(
this: CoreLibrary,
activity: AP.Activity,
): Promise<URL[]> {
const tags =
guard.isApCoreObject(activity.object) && activity.object.tag
? getArray(activity.object.tag)
: [];
const mentions = tags.map(getId).filter(guard.isUrl);
const recipients = [
...getArray(activity.to),
...getArray(activity.cc),
...getArray(activity.bto),
...getArray(activity.bcc),
...getArray(activity.audience),
...mentions,
].flat();
const recipients = [
...getArray(activity.to),
...getArray(activity.cc),
...getArray(activity.bto),
...getArray(activity.bcc),
...getArray(activity.audience),
...mentions,
].flat();
const recipientIds = recipients
.map(getId)
.filter(guard.isUrl)
.filter((recipientUrl) => recipientUrl.href !== PUBLIC_ACTOR);
const recipientIds = recipients
.map(getId)
.filter(guard.isUrl)
.filter((recipientUrl) => recipientUrl.href !== PUBLIC_ACTOR);
const actorUrls = await Promise.all(
recipientIds.map(getActorIds.bind(this)),
);
const actorUrls = await Promise.all(recipientIds.map(getActorIds.bind(this)));
return deduplicateUrls(actorUrls.flat());
};
return deduplicateUrls(actorUrls.flat());
}
/**
* Given a recipient URL, get all of the Actor URLs that it represents, as it
* may be a Collection.
*
* @returns An array of Actor URLs.
*/
async function getActorIds(
this: CoreLibrary,
recipientId: URL,
@ -89,8 +97,16 @@ async function getActorIds(
return [];
}
/**
* Get an array of EntityReferences.
*
* Collection items can be either an EntityReference or an array of
* EntityReferences.
*
* @returns An array of EntityReferences.
*/
function getArray(
items: null | undefined | AP.OrArray<AP.EntityReference>,
items: AP.Collection['items'] | AP.Collection['orderedItems'] | undefined,
): AP.EntityReference[] {
if (!items) {
return [];

View File

@ -2,37 +2,41 @@ import * as AP from '@activity-kit/types';
import { guard } from '@activity-kit/type-utilities';
import { getId } from '@activity-kit/utilities';
import { CoreLibrary } from './adapters';
import { CoreLibrary } from '.';
export const getStreamByName: CoreLibrary['getStreamByName'] =
async function getStreamByName(
this: CoreLibrary,
actor: AP.Actor,
name: string,
): Promise<AP.EitherCollection | null> {
if (!actor.streams) {
return null;
}
/**
* Finds a Stream by its name.
*
* @returns The Stream, or null if not found.
*/
export async function getStreamByName(
this: CoreLibrary,
actor: AP.Actor,
name: string,
): Promise<AP.EitherCollection | null> {
if (!actor.streams) {
return null;
}
const streams = await Promise.all(
actor.streams.map(async (stream: AP.EntityReference) => {
const streamId = getId(stream);
const streams = await Promise.all(
actor.streams.map(async (stream: AP.EntityReference) => {
const streamId = getId(stream);
if (!streamId) {
return null;
}
if (!streamId) {
return null;
}
return await this.queryById(streamId);
}),
);
return await this.queryById(streamId);
}),
);
for (const stream of streams) {
if (guard.isApCollection(stream)) {
if (stream.name === name) {
return stream;
}
for (const stream of streams) {
if (guard.isApCollection(stream)) {
if (stream.name === name) {
return stream;
}
}
}
return null;
};
return null;
}

View File

@ -1,18 +1,14 @@
import * as AP from '@activity-kit/types';
import fetch from 'isomorphic-fetch';
import {
AuthAdapter,
CryptoAdapter,
DbAdapter,
DbOptions,
FetchPolyfill,
StorageAdapter,
CoreLibrary,
} from './adapters';
import { findEntityById } from './findEntityById';
import { fetchEntityById } from './fetchEntityById';
import { queryById } from './queryById';
import { expandEntity } from './expandEntity';
import { getPaginatedCollectionItems } from './getPaginatedCollectionItems';
@ -22,7 +18,27 @@ import { getStreamByName } from './getStreamByName';
import { broadcast } from './broadcast';
import { getRecipientUrls } from './getRecipientUrls';
export class Core implements CoreLibrary {
class CoreFunctions {
// Find.
public findEntityById = findEntityById;
public queryById = queryById;
public getActorByUserId = getActorByUserId;
public getStreamByName = getStreamByName;
// Expand.
public expandEntity = expandEntity;
public getPaginatedCollectionItems = getPaginatedCollectionItems;
public expandCollection = expandCollection;
// Server-to-Server.
public broadcast = broadcast;
public getRecipientUrls = getRecipientUrls;
}
export class CoreLibrary
extends CoreFunctions
implements AuthAdapter, DbAdapter, StorageAdapter, CryptoAdapter
{
fetch: FetchPolyfill;
initializeDb?: DbAdapter['initializeDb'];
@ -58,121 +74,64 @@ export class Core implements CoreLibrary {
db: DbAdapter;
fetch?: FetchPolyfill;
}) {
super();
this.fetch = adapters.fetch ?? fetch;
if (adapters.db.initializeDb) {
this.initializeDb = async () => await adapters.db.initializeDb?.();
this.initializeDb = adapters.db.initializeDb.bind(adapters.db);
}
this.findAll = async (
collection: string,
matchingObject: Record<string, unknown>,
) => await adapters.db.findAll(collection, matchingObject);
this.findAll = adapters.db.findAll.bind(adapters.db);
this.findOne = async (
collection: string,
matchingObject: Record<string, unknown>,
options?: Array<keyof typeof DbOptions>,
) => await adapters.db.findOne(collection, matchingObject, options);
this.findOne = adapters.db.findOne.bind(adapters.db);
this.findStringIdByValue = async (dbCollection: string, value: string) =>
await adapters.db.findStringIdByValue(dbCollection, value);
this.findStringIdByValue = adapters.db.findStringIdByValue.bind(
adapters.db,
);
this.findStringValueById = async (dbCollection: string, _id: string) =>
await adapters.db.findStringValueById(dbCollection, _id);
this.findStringValueById = adapters.db.findStringValueById.bind(
adapters.db,
);
this.insertItem = async (path: URL, url: URL) =>
await adapters.db.insertItem(path, url);
this.insertItem = adapters.db.insertItem.bind(adapters.db);
this.removeItem = async (path: URL, url: URL) =>
await adapters.db.removeItem(path, url);
this.removeItem = adapters.db.removeItem.bind(adapters.db);
this.insertOrderedItem = async (path: URL, url: URL) =>
await adapters.db.insertOrderedItem(path, url);
this.insertOrderedItem = adapters.db.insertOrderedItem.bind(adapters.db);
this.removeOrderedItem = async (path: URL, url: URL) =>
await adapters.db.removeOrderedItem(path, url);
this.removeOrderedItem = adapters.db.removeOrderedItem.bind(adapters.db);
this.saveEntity = async (entity: AP.Entity) =>
await adapters.db.saveEntity(entity);
this.saveEntity = adapters.db.saveEntity.bind(adapters.db);
this.saveString = async (
dbCollection: string,
_id: string,
value: string,
) => await adapters.db.saveString(dbCollection, _id, value);
this.saveString = adapters.db.saveString.bind(adapters.db);
this.getHttpSignature = async (
foreignTarget: URL,
actorId: URL,
privateKey: string,
entity?: Record<string, unknown>,
) =>
await adapters.crypto.getHttpSignature(
foreignTarget,
actorId,
privateKey,
entity,
);
this.getHttpSignature = adapters.crypto.getHttpSignature.bind(
adapters.crypto,
);
this.generateKeyPair = async () => await adapters.crypto.generateKeyPair();
this.generateKeyPair = adapters.crypto.generateKeyPair.bind(
adapters.crypto,
);
this.hashPassword = async (password: string, salt: string) =>
await adapters.crypto.hashPassword(password, salt);
this.hashPassword = adapters.crypto.hashPassword.bind(adapters.crypto);
this.randomBytes = async (numberOfBytes: number) =>
await adapters.crypto.randomBytes(numberOfBytes);
this.randomBytes = adapters.crypto.randomBytes.bind(adapters.crypto);
this.getGuid = async () => await adapters.crypto.randomBytes(16);
this.getTokenByUserId = async (userId) =>
await adapters.auth.getTokenByUserId(userId);
this.getTokenByUserId = adapters.auth.getTokenByUserId.bind(adapters.auth);
this.createUser = async ({
email,
password,
preferredUsername,
}: {
email: string;
password?: string;
preferredUsername: string;
}) =>
await adapters.auth.createUser({
email,
password,
preferredUsername,
});
this.createUser = adapters.auth.createUser.bind(adapters.auth);
this.getUserIdByToken = async (token) =>
await adapters.auth.getUserIdByToken(token);
this.getUserIdByToken = adapters.auth.getUserIdByToken.bind(adapters.auth);
this.authenticatePassword = async (email: string, password: string) =>
await adapters.auth.authenticatePassword(email, password);
this.authenticatePassword = adapters.auth.authenticatePassword.bind(
adapters.auth,
);
this.upload = async (file) => await adapters.storage.upload(file);
this.upload = adapters.storage.upload.bind(adapters.storage);
}
// Find.
public findEntityById = findEntityById;
public getActorByUserId = getActorByUserId;
public getStreamByName = getStreamByName;
// Fetch.
public fetchEntityById = fetchEntityById;
public queryById = queryById;
// Expand.
public expandEntity = expandEntity;
public getPaginatedCollectionItems = getPaginatedCollectionItems;
public expandCollection = expandCollection;
// Broadcast Server-to-Server.
public broadcast = broadcast;
public getRecipientUrls = getRecipientUrls;
}
export {
@ -182,7 +141,6 @@ export {
DbOptions,
FetchPolyfill,
StorageAdapter,
CoreLibrary,
Plugin,
Routes,
} from './adapters';

View File

@ -1,10 +1,37 @@
import * as AP from '@activity-kit/types';
import { guard } from '@activity-kit/type-utilities';
import { isLocal } from '@activity-kit/utilities';
import { cast, assert, guard } from '@activity-kit/type-utilities';
import {
isLocal,
ACCEPT_HEADER,
ACTIVITYSTREAMS_CONTENT_TYPE,
convertJsonToEntity,
compressEntity,
LINKED_DATA_CONTENT_TYPE,
JSON_CONTENT_TYPE,
getId,
SERVER_ACTOR_USERNAME,
ACTIVITYSTREAMS_CONTEXT,
CONTENT_TYPE_HEADER,
} from '@activity-kit/utilities';
import { CoreLibrary } from './adapters';
import { CoreLibrary } from '.';
import { Body } from './adapters/FetchPolyfill';
import { getPrivateKey } from './util/getPrivateKey';
export const queryById: CoreLibrary['queryById'] = async function queryById(
/**
* Finds an Entity by its ID, which is a URL.
*
* If the Entity is not found locally it will be fetched from the URL.
*
* If the Entity is a Tombstone, it will be returned.
*
* If the Entity is not a Tombstone, it will be saved to the database.
*
* If the Entity is not found at the URL, it will be saved as a Tombstone.
*
* @returns The Entity, which may be a Tombstone, or null if not found.
*/
export async function queryById(
this: CoreLibrary,
id: URL,
): Promise<AP.Entity | null> {
@ -12,7 +39,7 @@ export const queryById: CoreLibrary['queryById'] = async function queryById(
return await this.findEntityById(id);
}
const fetchedEntity = await this.fetchEntityById(id);
const fetchedEntity = await fetchEntityByUrl.bind(this)(id);
if (
!fetchedEntity ||
@ -29,4 +56,198 @@ export const queryById: CoreLibrary['queryById'] = async function queryById(
}
return fetchedEntity;
};
}
/**
* Fetch an Entity by its URL.
*
* @returns The fetched Entity or null if the URL does not represent an Entity.
*/
async function fetchEntityByUrl(
this: CoreLibrary,
id: URL,
): Promise<AP.Entity | null> {
const isJsonLdContentType = await getIsJsonLdContentType.bind(this)(id);
if (!isJsonLdContentType) {
return null;
}
const botActor = await getBotActor.bind(this)();
assert.exists(botActor);
const botActorId = getId(botActor);
assert.exists(botActorId);
const privateKey = await getPrivateKey.bind(this)(botActor);
assert.exists(privateKey);
const { dateHeader, signatureHeader } = await this.getHttpSignature(
id,
botActorId,
privateKey,
);
const headers = {
date: dateHeader,
signature: signatureHeader,
};
const fetchedJson = await fetchJsonByUrl.bind(this)(id, headers);
if (!fetchedJson) {
return null;
}
const convertedEntity = convertJsonToEntity(fetchedJson);
if (!convertedEntity) {
return null;
}
const entity = compressEntity(convertedEntity);
if (!entity) {
return null;
}
await this.saveEntity(entity);
return entity;
}
/**
* Fetch a JSON object from a URL using the provided headers.
*
* @returns The JSON object, or null if not found.
*/
async function fetchJsonByUrl(
this: CoreLibrary,
url: URL,
headers: Record<string, string>,
): Promise<Record<string, unknown> | null> {
const config = {
headers: {
...headers,
[ACCEPT_HEADER]: ACTIVITYSTREAMS_CONTENT_TYPE,
},
};
return await this.fetch(url.href, config)
.then(handleResponse)
.catch(handleError);
}
/**
* Handle a response from a fetch request.
*
* @returns The JSON object, or null if not found.
*/
async function handleResponse(
response: Body,
): Promise<Record<string, unknown> | null> {
const data = cast.isPlainObject(await response.json()) ?? null;
if (!data) {
return null;
}
if (response.status === 200) {
return data;
}
if (response.status === 400 || response.status === 410) {
if ('@context' in data) {
// Likely a tombstone
return data;
} else {
// Return a tombstone
return {
'@context': ACTIVITYSTREAMS_CONTEXT,
type: AP.ExtendedObjectTypes.TOMBSTONE,
id: response.url,
url: response.url,
};
}
}
if (response.status >= 500) {
return null;
}
return data;
}
/**
* Handle an error from a fetch request.
*
* Allows the application to continue if a fetch request fails.
*
* @returns null
*/
async function handleError(error: Error) {
console.log(`${error}`);
return null;
}
/**
* Get the content type of a URL.
*
* A HEAD request is used to determine if a URL is a JSON-LD object.
*
* @returns The content type, or null if not found.
*/
async function getContentType(
this: CoreLibrary,
url: URL,
): Promise<string | null> {
const response = await this.fetch(url.toString(), {
method: 'HEAD',
headers: {
[ACCEPT_HEADER]: ACTIVITYSTREAMS_CONTENT_TYPE,
},
});
return response.headers.get(CONTENT_TYPE_HEADER) ?? null;
}
/**
* Check if a URL returns a content type that represent a JSON-LD object.
*
* @returns True if the URL returns a JSON-LD content type.
*/
async function getIsJsonLdContentType(
this: CoreLibrary,
url: URL,
): Promise<boolean> {
const contentType = await getContentType.bind(this)(url);
if (!contentType) {
return false;
}
return (
contentType.includes(ACTIVITYSTREAMS_CONTENT_TYPE) ||
contentType.includes(LINKED_DATA_CONTENT_TYPE) ||
contentType.includes(JSON_CONTENT_TYPE)
);
}
/**
* Get the server Actor.
*
* Mastodon in secure mode requires that all requests include a signature of the
* Actor that is making the request. We use the server Actor.
*
* @returns The server Actor, or null if not found.
*/
async function getBotActor(this: CoreLibrary): Promise<AP.Actor | null> {
const botActor = await this.findOne('entity', {
preferredUsername: SERVER_ACTOR_USERNAME,
});
return cast.isApActor(botActor) ?? null;
}

View File

@ -0,0 +1,28 @@
import * as AP from '@activity-kit/types';
import { CoreLibrary } from '..';
/**
* Get the private key of an Actor.
*
* @returns The private key as a string.
*/
export async function getPrivateKey(
this: CoreLibrary,
actor: AP.Actor,
): Promise<string> {
if (!actor.preferredUsername) {
return '';
}
const userId = await this.findStringIdByValue(
'username',
actor.preferredUsername,
);
if (!userId) {
return '';
}
return await this.findStringValueById('privateKey', userId);
}

View File

@ -12,70 +12,63 @@ export async function handleFoundCollectionPage(
entity: AP.EitherCollectionPage,
render: (entity: AP.Entity) => Promise<string>,
): Promise<Result> {
// Treat as CollectionPage.
const pageParts = this.url.href.split('/page/');
const getPageUrl = (page: number) =>
new URL(
`${this.url.pathname === '/' ? '' : this.url.pathname}/page/${page}`,
this.url.origin,
);
const page = pageParts[1];
const currentPage = page ? Number(page) : 1;
const firstItemIndex = (currentPage - 1) * ITEMS_PER_COLLECTION_PAGE;
const startIndex = firstItemIndex + 1;
const hasPage = this.url.href.includes('/page/');
const pageParts = this.url.href.split('/page/');
const getPageUrl = (page: number) =>
new URL(
`${this.url.pathname === '/' ? '' : this.url.pathname}/page/${page}`,
this.url.origin,
const limitedItems = getCollectionItems(entity).slice(
firstItemIndex,
firstItemIndex + ITEMS_PER_COLLECTION_PAGE,
);
const page = pageParts[1];
const currentPage = page ? Number(page) : 1;
const firstItemIndex = (currentPage - 1) * ITEMS_PER_COLLECTION_PAGE;
const startIndex = firstItemIndex + 1;
if (!hasPage) {
const limitedItems = getCollectionItems(entity).slice(
firstItemIndex,
firstItemIndex + ITEMS_PER_COLLECTION_PAGE,
);
const items = expandItems(limitedItems);
const items = expandItems(limitedItems);
const collectionPage = {
...entity,
id: getPageUrl(currentPage),
url: getPageUrl(currentPage),
partOf: baseUrl,
first: getPageUrl(1),
last: getPageUrl(lastPageIndex),
...(currentPage > 1
? {
prev: getPageUrl(currentPage - 1),
}
: null),
...(currentPage < lastPageIndex
? {
next: getPageUrl(currentPage + 1),
}
: null),
};
if (isOrderedCollection) {
const orderedCollectionPageEntity: AP.OrderedCollectionPage = {
...collectionPage,
type: AP.CollectionPageTypes.ORDERED_COLLECTION_PAGE,
orderedItems: items,
startIndex,
const collectionPage = {
...entity,
id: getPageUrl(currentPage),
url: getPageUrl(currentPage),
partOf: baseUrl,
first: getPageUrl(1),
last: getPageUrl(lastPageIndex),
...(currentPage > 1
? {
prev: getPageUrl(currentPage - 1),
}
: null),
...(currentPage < lastPageIndex
? {
next: getPageUrl(currentPage + 1),
}
: null),
};
return this.handleFoundEntity(orderedCollectionPageEntity, render);
if (isOrderedCollection) {
const orderedCollectionPageEntity: AP.OrderedCollectionPage = {
...collectionPage,
type: AP.CollectionPageTypes.ORDERED_COLLECTION_PAGE,
orderedItems: items,
startIndex,
};
return this.handleFoundEntity(orderedCollectionPageEntity, render);
}
const collectionPageEntity: AP.CollectionPage = {
...collectionPage,
type: AP.CollectionPageTypes.COLLECTION_PAGE,
items: items,
};
return this.handleFoundEntity(collectionPageEntity, render);
}
const collectionPageEntity: AP.CollectionPage = {
...collectionPage,
type: AP.CollectionPageTypes.COLLECTION_PAGE,
items: items,
};
return this.handleFoundEntity(collectionPageEntity, render);
}
function expandItems(
objects: Array<unknown>,
): Array<AP.Object | AP.Link | AP.Mention> {

View File

@ -2,6 +2,11 @@ import * as AP from '@activity-kit/types';
import { guard } from '@activity-kit/type-utilities';
import { ACTIVITYSTREAMS_CONTEXT, W3ID_SECURITY_CONTEXT } from './globals';
/**
* Applies the ActivityStreams context to an Entity.
*
* @returns The Entity with the context applied.
*/
export function applyContext(entity: AP.Entity): AP.Entity {
if (!entity['@context']) {
if (guard.isApActor(entity)) {

View File

@ -3,6 +3,8 @@ import * as AP from '@activity-kit/types';
/**
* Removes the private `bto` and `bcc` properties from Entities so they don't
* leak out upon delivery.
*
* @returns The Entity with the private properties removed.
**/
export function cleanProps(entity: AP.Entity): AP.Entity {
const cleanedEntity = { ...entity };

View File

@ -1,6 +1,11 @@
import * as AP from '@activity-kit/types';
import { cast, guard } from '@activity-kit/type-utilities';
/**
* Compresses an Entity by replacing all nested Entities with their URLs.
*
* @returns The compressed Entity, or null if not an Entity.
*/
export function compressEntity(entity: AP.Entity): AP.Entity | null {
return cast.isApEntity(compressObject(entity)) ?? null;
}

View File

@ -1,6 +1,11 @@
import * as AP from '@activity-kit/types';
import { cast, guard } from '@activity-kit/type-utilities';
/**
* Converts an Entity to a plain JSON object.
*
* @returns The plain object.
*/
export function convertEntityToJson(
object: AP.Entity,
): Record<string, unknown> {

File diff suppressed because it is too large Load Diff

View File

@ -2,6 +2,11 @@ import * as AP from '@activity-kit/types';
import { cast, guard } from '@activity-kit/type-utilities';
import { PUBLIC_ACTOR } from './globals';
/**
* Converts a JSON object to an Entity.
*
* @returns The Entity, or null if not an Entity.
*/
export function convertJsonToEntity(
object: Record<string, unknown>,
): AP.Entity | null {

View File

@ -1,3 +1,6 @@
/**
* Removes duplicate URLs from an array of URLs.
*/
export const deduplicateUrls = (unfilteredUrls: URL[]) => {
return [...new Set(unfilteredUrls.map((url) => url.toString()))].map(
(url) => new URL(url),

View File

@ -1,5 +1,10 @@
import { LOCAL_HOSTNAME } from './globals';
/**
* Gets the database collection name for a given URL.
*
* @returns The collection name.
*/
export const getCollectionNameByUrl = (url: URL) => {
const isLocal = url.hostname === LOCAL_HOSTNAME;

View File

@ -1,6 +1,11 @@
import * as AP from '@activity-kit/types';
import { cast, guard } from '@activity-kit/type-utilities';
/**
* Get the Entity from an EntityReference, if the EntityReference is an Entity.
*
* @returns The Entity, or null if not an Entity.
*/
export const getEntity = <T extends AP.Entity>(
entity: undefined | null | AP.EntityReference | AP.EntityReference[],
): T | null => {

View File

@ -1,6 +1,11 @@
import * as AP from '@activity-kit/types';
import { guard } from '@activity-kit/type-utilities';
/**
* Get the URL from an EntityReference, if the EntityReference is a URL.
*
* @returns The URL, or null if not a URL.
*/
export const getId = (
entity?: undefined | null | AP.EntityReference | AP.EntityReference[],
): URL | null => {

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,10 @@
import { getCollectionNameByUrl } from './getCollectionNameByUrl';
/**
* Determines whether a URL is local or not.
*
* @returns True if local, false if foreign.
*/
export function isLocal(url: URL) {
return getCollectionNameByUrl(url) !== 'foreignEntity';
}

View File

@ -3,6 +3,13 @@ import * as AP from '@activity-kit/types';
import { convertJsonLdToEntity } from './convertJsonLdToEntity';
import { streamToString } from './streamToString';
/**
* Parse an HTTP stream into an Entity.
*
* @returns The Entity, or null if not found.
*
* @todo This is being depricated in favor of having adapters handle this.
*/
export async function parseStream(
req: IncomingMessage,
): Promise<AP.Entity | null> {

View File

@ -1,5 +1,12 @@
import { IncomingMessage } from 'http';
/**
* Converts an HTTP stream to a string.
*
* @returns The string.
*
* @todo This is being depricated in favor of having adapters handle this.
*/
export async function streamToString(stream: IncomingMessage): Promise<string> {
if (stream) {
const chunks = [];