@openpeepshq/core 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import { getSharedConnection } from '../redis/index.js';
2
- const KEY_PREFIX = 'analytics:v4:';
2
+ const KEY_PREFIX = 'analytics:v5:';
3
3
  const OPEN_DAY_TTL_SEC = 60 * 60;
4
4
  const CLOSED_RANGE_TTL_SEC = 60 * 60 * 6;
5
5
  export const analyticsCacheKey = (section, from, to) => `${KEY_PREFIX}${section}:${from}:${to}`;
@@ -5,7 +5,7 @@ export * from './explorer';
5
5
  export { map } from './pg/map';
6
6
  export { collectionInfos } from './pg/collections';
7
7
  export type { CollectionInfoKey } from './pg/collections';
8
- export { closePostgres, type PgDb } from './pg/client';
8
+ export { closePostgres, pgConnectionString, type PgDb } from './pg/client';
9
9
  export type { PgFilter, SqlFilter } from './pg/map/queryTypes';
10
10
  export { combine, createdAtBetween, documentKeyAfter, documentKeyBefore, edgeFilters, eventTimeFilters, groupFilters, isSqlFilter, notificationFilters, pgSql, postFilters, profileFilters, } from './pg/filters';
11
11
  export { computedFields, sorts } from './pg/queries';
package/dist/db/index.js CHANGED
@@ -3,7 +3,7 @@ export { empty } from './examples.js';
3
3
  export * from './explorer/index.js';
4
4
  export { map } from './pg/map/index.js';
5
5
  export { collectionInfos } from './pg/collections.js';
6
- export { closePostgres } from './pg/client.js';
6
+ export { closePostgres, pgConnectionString } from './pg/client.js';
7
7
  export { combine, createdAtBetween, documentKeyAfter, documentKeyBefore, edgeFilters, eventTimeFilters, groupFilters, isSqlFilter, notificationFilters, pgSql, postFilters, profileFilters, } from './pg/filters/index.js';
8
8
  export { computedFields, sorts } from './pg/queries/index.js';
9
9
  let dbPromise;
@@ -0,0 +1,32 @@
1
+ import type { ProfileWithMeta } from '@openpeepshq/common/types';
2
+ export type LocalActor = {
3
+ id: string;
4
+ handle: string;
5
+ displayName?: string;
6
+ bio?: string;
7
+ avatar?: string | null;
8
+ createdAt: string;
9
+ deleted: boolean;
10
+ };
11
+ export type LocalActorKeys = {
12
+ id: string;
13
+ publicKeyPem: string;
14
+ privateKeyPem: string;
15
+ keyId: string | null;
16
+ };
17
+ export type RemoteActorInput = {
18
+ uri: string;
19
+ handle: string;
20
+ domain: string;
21
+ inboxUrl?: string | null;
22
+ sharedInboxUrl?: string | null;
23
+ publicKeyPem?: string | null;
24
+ displayName?: string;
25
+ bio?: string;
26
+ avatar?: string | null;
27
+ };
28
+ export declare const federatedHandleFrom: (preferred: string | null | undefined, uri: string) => string;
29
+ export declare const loadLocalActor: (profileId: string) => Promise<LocalActor | null>;
30
+ export declare const findLocalActorIdByHandle: (handle: string) => Promise<string | null>;
31
+ export declare const loadLocalActorKeys: (profileId: string) => Promise<LocalActorKeys | null>;
32
+ export declare const upsertRemoteActor: (input: RemoteActorInput) => Promise<ProfileWithMeta | undefined>;
@@ -0,0 +1,136 @@
1
+ import { and, eq, isNull } from 'drizzle-orm';
2
+ import { uuidv7 } from 'uuidv7';
3
+ import { allpeepDb } from '../db/index.js';
4
+ import { pgDb } from '../db/pg/client.js';
5
+ import { nowIso } from '../db/pg/mappers.js';
6
+ import { profiles } from '../db/pg/schema/documents.js';
7
+ import { profilesMapping } from '../profiles/mapping.js';
8
+ import { findProfileByHandleAndDomain, findProfileByUri } from './profiles.js';
9
+ export const federatedHandleFrom = (preferred, uri) => {
10
+ const fromName = (preferred ?? '')
11
+ .replace(/[^a-zA-Z0-9_.-]/g, '')
12
+ .slice(0, 64);
13
+ if (fromName.length >= 1)
14
+ return fromName;
15
+ const fromUri = uri.replace(/[^a-zA-Z0-9]/g, '').slice(-16);
16
+ return `actor-${fromUri || 'remote'}`;
17
+ };
18
+ const clipDisplayName = (name) => name ? name.slice(0, 30) : undefined;
19
+ const bodyOf = (row) => (row.body ?? {});
20
+ export const loadLocalActor = async (profileId) => {
21
+ const db = pgDb();
22
+ // The Fedify actor dispatcher passes the username from the URL path (e.g.
23
+ // "alice" from /ap/users/alice), not a UUID. Resolve it to a profile ID
24
+ // via findLocalActorIdByHandle, falling back to the original value which
25
+ // may already be a UUID from internal callers.
26
+ const resolvedId = (await findLocalActorIdByHandle(profileId)) ?? profileId;
27
+ const [row] = await db
28
+ .select({
29
+ id: profiles.id,
30
+ handle: profiles.handle,
31
+ type: profiles.type,
32
+ body: profiles.body,
33
+ createdAt: profiles.createdAt,
34
+ deletedAt: profiles.deletedAt,
35
+ })
36
+ .from(profiles)
37
+ .where(eq(profiles.id, resolvedId))
38
+ .limit(1);
39
+ if (!row || row.type !== 'local')
40
+ return null;
41
+ const body = bodyOf(row);
42
+ return {
43
+ id: row.id,
44
+ handle: row.handle,
45
+ displayName: body.displayName,
46
+ bio: body.bio,
47
+ avatar: body.avatar,
48
+ createdAt: row.createdAt,
49
+ deleted: row.deletedAt != null,
50
+ };
51
+ };
52
+ export const findLocalActorIdByHandle = async (handle) => {
53
+ const db = pgDb();
54
+ const [row] = await db
55
+ .select({ id: profiles.id })
56
+ .from(profiles)
57
+ .where(and(eq(profiles.handle, handle), eq(profiles.type, 'local'), isNull(profiles.deletedAt)))
58
+ .limit(1);
59
+ return row?.id ?? null;
60
+ };
61
+ export const loadLocalActorKeys = async (profileId) => {
62
+ const db = pgDb();
63
+ const resolvedId = (await findLocalActorIdByHandle(profileId)) ?? profileId;
64
+ const [row] = await db
65
+ .select({
66
+ id: profiles.id,
67
+ type: profiles.type,
68
+ publicKeyPem: profiles.publicKeyPem,
69
+ privateKeyPem: profiles.privateKeyPem,
70
+ keyId: profiles.keyId,
71
+ deletedAt: profiles.deletedAt,
72
+ })
73
+ .from(profiles)
74
+ .where(eq(profiles.id, resolvedId))
75
+ .limit(1);
76
+ if (!row ||
77
+ row.type !== 'local' ||
78
+ row.deletedAt != null ||
79
+ !row.publicKeyPem ||
80
+ !row.privateKeyPem) {
81
+ return null;
82
+ }
83
+ return {
84
+ id: row.id,
85
+ publicKeyPem: row.publicKeyPem,
86
+ privateKeyPem: row.privateKeyPem,
87
+ keyId: row.keyId,
88
+ };
89
+ };
90
+ export const upsertRemoteActor = async (input) => {
91
+ const existing = await findProfileByUri(input.uri);
92
+ const displayName = clipDisplayName(input.displayName);
93
+ const db = pgDb();
94
+ if (existing) {
95
+ await db
96
+ .update(profiles)
97
+ .set({
98
+ inboxUrl: input.inboxUrl ?? existing.inboxUrl,
99
+ sharedInboxUrl: input.sharedInboxUrl ?? existing.sharedInboxUrl,
100
+ publicKeyPem: input.publicKeyPem ?? existing.publicKeyPem,
101
+ fetchedAt: nowIso(),
102
+ })
103
+ .where(eq(profiles.id, existing.id));
104
+ if (displayName || input.bio || input.avatar) {
105
+ await profilesMapping.update(await allpeepDb().then((d) => d.db), existing.id, {
106
+ ...(displayName ? { displayName } : {}),
107
+ ...(input.bio ? { bio: input.bio } : {}),
108
+ ...(input.avatar ? { avatar: input.avatar } : {}),
109
+ });
110
+ }
111
+ return findProfileByUri(input.uri);
112
+ }
113
+ const handleTaken = await findProfileByHandleAndDomain(input.handle, input.domain);
114
+ const handle = handleTaken
115
+ ? federatedHandleFrom(null, input.uri)
116
+ : input.handle;
117
+ const id = uuidv7();
118
+ const actorFields = {
119
+ uri: input.uri,
120
+ inboxUrl: input.inboxUrl,
121
+ sharedInboxUrl: input.sharedInboxUrl,
122
+ publicKeyPem: input.publicKeyPem,
123
+ fetchedAt: nowIso(),
124
+ };
125
+ await profilesMapping.create(await allpeepDb().then((d) => d.db), {
126
+ id,
127
+ handle,
128
+ type: 'federated',
129
+ activityPub: { domain: input.domain },
130
+ displayName,
131
+ bio: input.bio,
132
+ avatar: input.avatar ?? undefined,
133
+ ...actorFields,
134
+ });
135
+ return findProfileByUri(input.uri);
136
+ };
@@ -1,5 +1,16 @@
1
+ /** Fedify URI templates; must stay aligned with `actorUri` / `objectUri`. */
2
+ export declare const ACTOR_PATH: "/ap/users/{identifier}";
3
+ export declare const ACTOR_INBOX_PATH: "/ap/users/{identifier}/inbox";
4
+ export declare const SHARED_INBOX_PATH: "/ap/inbox";
5
+ export declare const FOLLOWERS_PATH: "/ap/users/{identifier}/followers";
6
+ export declare const NOTE_PATH: "/ap/objects/{id}";
7
+ export declare const CREATE_PATH: "/ap/create/{id}";
8
+ export declare const ACCEPT_PATH: "/ap/accept/{id}";
9
+ export declare const federationOrigin: (domain: string) => string;
1
10
  export declare const actorUri: (domain: string, profileId: string) => string;
2
11
  export declare const objectUri: (domain: string, postId: string) => string;
12
+ export declare const createActivityUri: (domain: string, activityId: string) => string;
13
+ export declare const acceptActivityUri: (domain: string, activityId: string) => string;
3
14
  export declare const generateActorKeyPair: () => import("crypto").KeyPairSyncResult<string, string>;
4
15
  export declare const localActorScalars: (profileId: string, domain: string) => {
5
16
  uri: string;
@@ -2,8 +2,19 @@ import { generateKeyPairSync } from 'node:crypto';
2
2
  import { and, eq, isNull, sql } from 'drizzle-orm';
3
3
  import { pgDb } from '../db/pg/client.js';
4
4
  import { profiles } from '../db/pg/schema/documents.js';
5
+ /** Fedify URI templates; must stay aligned with `actorUri` / `objectUri`. */
6
+ export const ACTOR_PATH = '/ap/users/{identifier}';
7
+ export const ACTOR_INBOX_PATH = '/ap/users/{identifier}/inbox';
8
+ export const SHARED_INBOX_PATH = '/ap/inbox';
9
+ export const FOLLOWERS_PATH = '/ap/users/{identifier}/followers';
10
+ export const NOTE_PATH = '/ap/objects/{id}';
11
+ export const CREATE_PATH = '/ap/create/{id}';
12
+ export const ACCEPT_PATH = '/ap/accept/{id}';
13
+ export const federationOrigin = (domain) => `https://${domain}`;
5
14
  export const actorUri = (domain, profileId) => `https://${domain}/ap/users/${profileId}`;
6
15
  export const objectUri = (domain, postId) => `https://${domain}/ap/objects/${postId}`;
16
+ export const createActivityUri = (domain, activityId) => `https://${domain}/ap/create/${activityId}`;
17
+ export const acceptActivityUri = (domain, activityId) => `https://${domain}/ap/accept/${activityId}`;
7
18
  export const generateActorKeyPair = () => generateKeyPairSync('rsa', {
8
19
  modulusLength: 2048,
9
20
  publicKeyEncoding: { type: 'spki', format: 'pem' },
@@ -1,4 +1,11 @@
1
1
  export { findApActivityByUri, recordApActivity } from './activities';
2
2
  export type { ApActivity, ApActivityDirection } from './activities';
3
- export { actorUri, backfillLocalFederationIdentities, generateActorKeyPair, localActorScalars, localObjectScalars, objectUri, } from './identity';
3
+ export { federatedHandleFrom, findLocalActorIdByHandle, loadLocalActor, loadLocalActorKeys, upsertRemoteActor, } from './actors';
4
+ export type { LocalActor, LocalActorKeys, RemoteActorInput } from './actors';
5
+ export { ACCEPT_PATH, ACTOR_INBOX_PATH, ACTOR_PATH, CREATE_PATH, FOLLOWERS_PATH, NOTE_PATH, SHARED_INBOX_PATH, acceptActivityUri, actorUri, backfillLocalFederationIdentities, createActivityUri, federationOrigin, generateActorKeyPair, localActorScalars, localObjectScalars, objectUri, } from './identity';
6
+ export { ingestIncomingFollow, ingestIncomingUnfollow, listFederatedFollowerRecipients, } from './ingest';
7
+ export type { FollowerRecipient } from './ingest';
8
+ export { loadPublicNote } from './notes';
9
+ export type { PublicNote } from './notes';
10
+ export { federationIsActive, hostnameOf, peerHostAllowed } from './peers';
4
11
  export { findProfileByHandleAndDomain, findProfileByUri } from './profiles';
@@ -1,3 +1,7 @@
1
1
  export { findApActivityByUri, recordApActivity } from './activities.js';
2
- export { actorUri, backfillLocalFederationIdentities, generateActorKeyPair, localActorScalars, localObjectScalars, objectUri, } from './identity.js';
2
+ export { federatedHandleFrom, findLocalActorIdByHandle, loadLocalActor, loadLocalActorKeys, upsertRemoteActor, } from './actors.js';
3
+ export { ACCEPT_PATH, ACTOR_INBOX_PATH, ACTOR_PATH, CREATE_PATH, FOLLOWERS_PATH, NOTE_PATH, SHARED_INBOX_PATH, acceptActivityUri, actorUri, backfillLocalFederationIdentities, createActivityUri, federationOrigin, generateActorKeyPair, localActorScalars, localObjectScalars, objectUri, } from './identity.js';
4
+ export { ingestIncomingFollow, ingestIncomingUnfollow, listFederatedFollowerRecipients, } from './ingest.js';
5
+ export { loadPublicNote } from './notes.js';
6
+ export { federationIsActive, hostnameOf, peerHostAllowed } from './peers.js';
3
7
  export { findProfileByHandleAndDomain, findProfileByUri } from './profiles.js';
@@ -0,0 +1,9 @@
1
+ import type { Profile } from '@openpeepshq/common/types';
2
+ export declare const ingestIncomingFollow: (follower: Profile, followed: Profile, activityUri: string) => Promise<void>;
3
+ export declare const ingestIncomingUnfollow: (follower: Profile, followed: Profile, activityUri: string) => Promise<void>;
4
+ export type FollowerRecipient = {
5
+ uri: string;
6
+ inboxUrl: string;
7
+ sharedInboxUrl: string | null;
8
+ };
9
+ export declare const listFederatedFollowerRecipients: (followedId: string) => Promise<FollowerRecipient[]>;
@@ -0,0 +1,60 @@
1
+ import { and, eq, isNull, sql } from 'drizzle-orm';
2
+ import { pgDb } from '../db/pg/client.js';
3
+ import { follows } from '../db/pg/schema/edges.js';
4
+ import { profiles } from '../db/pg/schema/documents.js';
5
+ import { follow, unfollow } from '../profiles/mutations.js';
6
+ import { follows as hasFollow } from '../profiles/finders.js';
7
+ import { recordApActivity } from './activities.js';
8
+ export const ingestIncomingFollow = async (follower, followed, activityUri) => {
9
+ if (!(await hasFollow(follower, followed))) {
10
+ await follow(follower, followed, {
11
+ uri: activityUri,
12
+ reblogs: true,
13
+ notify: true,
14
+ });
15
+ }
16
+ await recordApActivity({
17
+ uri: activityUri,
18
+ type: 'Follow',
19
+ actorUri: followerUri(follower),
20
+ objectUri: followerUri(followed),
21
+ direction: 'in',
22
+ });
23
+ };
24
+ export const ingestIncomingUnfollow = async (follower, followed, activityUri) => {
25
+ if (await hasFollow(follower, followed)) {
26
+ await unfollow(follower, followed);
27
+ }
28
+ await recordApActivity({
29
+ uri: activityUri,
30
+ type: 'Undo',
31
+ actorUri: followerUri(follower),
32
+ objectUri: followerUri(followed),
33
+ direction: 'in',
34
+ });
35
+ };
36
+ const followerUri = (profile) => {
37
+ const uri = profile.uri;
38
+ return uri ?? `profile:${profile.id}`;
39
+ };
40
+ export const listFederatedFollowerRecipients = async (followedId) => {
41
+ const db = pgDb();
42
+ const rows = await db
43
+ .select({
44
+ uri: profiles.uri,
45
+ inboxUrl: profiles.inboxUrl,
46
+ sharedInboxUrl: profiles.sharedInboxUrl,
47
+ })
48
+ .from(follows)
49
+ .innerJoin(profiles, sql `${follows.fromId} = ${profiles.id}::text`)
50
+ .where(and(eq(follows.toId, followedId), eq(profiles.type, 'federated'), isNull(profiles.deletedAt)));
51
+ return rows.flatMap((row) => row.uri && row.inboxUrl
52
+ ? [
53
+ {
54
+ uri: row.uri,
55
+ inboxUrl: row.inboxUrl,
56
+ sharedInboxUrl: row.sharedInboxUrl,
57
+ },
58
+ ]
59
+ : []);
60
+ };
@@ -0,0 +1,8 @@
1
+ export type PublicNote = {
2
+ id: string;
3
+ creatorId: string;
4
+ content: string;
5
+ published: string;
6
+ inReplyToUri: string | null;
7
+ };
8
+ export declare const loadPublicNote: (postId: string) => Promise<PublicNote | null>;
@@ -0,0 +1,30 @@
1
+ import { and, eq, isNull } from 'drizzle-orm';
2
+ import { pgDb } from '../db/pg/client.js';
3
+ import { posts } from '../db/pg/schema/documents.js';
4
+ export const loadPublicNote = async (postId) => {
5
+ const db = pgDb();
6
+ const [row] = await db
7
+ .select({
8
+ id: posts.id,
9
+ type: posts.type,
10
+ visibility: posts.visibility,
11
+ creatorId: posts.creatorId,
12
+ body: posts.body,
13
+ inReplyToUri: posts.inReplyToUri,
14
+ createdAt: posts.createdAt,
15
+ deletedAt: posts.deletedAt,
16
+ })
17
+ .from(posts)
18
+ .where(and(eq(posts.id, postId), isNull(posts.deletedAt)))
19
+ .limit(1);
20
+ if (!row || row.type !== 'note' || row.visibility !== 'public')
21
+ return null;
22
+ const body = (row.body ?? {});
23
+ return {
24
+ id: row.id,
25
+ creatorId: row.creatorId,
26
+ content: body.content ?? '',
27
+ published: row.createdAt,
28
+ inReplyToUri: row.inReplyToUri,
29
+ };
30
+ };
@@ -0,0 +1,3 @@
1
+ export declare const hostnameOf: (value: string | URL) => string | null;
2
+ export declare const peerHostAllowed: (value: string | URL | null | undefined) => Promise<boolean>;
3
+ export declare const federationIsActive: () => Promise<boolean>;
@@ -0,0 +1,24 @@
1
+ import { hostIsAllowed } from '@openpeepshq/common/lib';
2
+ import { config } from '../config/index.js';
3
+ export const hostnameOf = (value) => {
4
+ try {
5
+ const host = new URL(value).hostname
6
+ .trim()
7
+ .toLowerCase()
8
+ .replace(/\.$/, '');
9
+ return host || null;
10
+ }
11
+ catch {
12
+ return null;
13
+ }
14
+ };
15
+ export const peerHostAllowed = async (value) => {
16
+ if (value == null)
17
+ return false;
18
+ const host = hostnameOf(value);
19
+ if (!host)
20
+ return false;
21
+ const cfg = await config();
22
+ return hostIsAllowed(host, cfg.federation.allowedHosts);
23
+ };
24
+ export const federationIsActive = async () => (await config()).federation.active;
@@ -1,4 +1,12 @@
1
1
  import type { MediaStorage } from '@openpeepshq/common/types';
2
+ /**
3
+ * Thrown when file content does not match its declared type (e.g. a text file
4
+ * renamed to `.jpg`). The upload handler maps this to HTTP 400 so the client
5
+ * gets a clear message instead of a 500.
6
+ */
7
+ export declare class MediaContentError extends Error {
8
+ constructor(message: string);
9
+ }
2
10
  export declare const mediaStorage: () => Promise<MediaStorage>;
3
11
  /**
4
12
  * A media source/output that lives on disk rather than in memory. The whole
@@ -15,6 +15,17 @@ import { hub } from '../events/index.js';
15
15
  let storagePromise = null;
16
16
  const log = logger('app:media');
17
17
  const previewMaxWidth = 700;
18
+ /**
19
+ * Thrown when file content does not match its declared type (e.g. a text file
20
+ * renamed to `.jpg`). The upload handler maps this to HTTP 400 so the client
21
+ * gets a clear message instead of a 500.
22
+ */
23
+ export class MediaContentError extends Error {
24
+ constructor(message) {
25
+ super(message);
26
+ this.name = 'MediaContentError';
27
+ }
28
+ }
18
29
  const initStorage = async () => {
19
30
  const { media: { storage: { params }, }, } = await config();
20
31
  hub.on('configUpdated', (namespace, name) => {
@@ -99,7 +110,7 @@ export const transcodeIncomingMedia = async (type, inputPath, originalName, sour
99
110
  export const createPreview = async (inputPath, mimetype, originalName) => {
100
111
  switch (mimetype.split('/')[0]) {
101
112
  case 'image':
102
- return createImagePreview(inputPath, mimetype);
113
+ return createImagePreview(inputPath);
103
114
  case 'audio':
104
115
  return createAudioPreview(inputPath);
105
116
  case 'video':
@@ -111,19 +122,18 @@ export const createPreview = async (inputPath, mimetype, originalName) => {
111
122
  return createFilePreview(inputPath, mimetype, originalName);
112
123
  }
113
124
  };
114
- const createImagePreview = async (inputPath, mimetype) => {
115
- const width = await sharp(inputPath)
116
- .metadata()
117
- .then((m) => m.width || 0);
118
- if (width <= previewMaxWidth) {
119
- return { path: inputPath, mimetype };
120
- }
125
+ const createImagePreview = async (inputPath) => {
121
126
  const outputPath = join(tmpdir(), `preview-${randomString(16)}.webp`);
122
- await sharp(inputPath)
123
- .rotate()
124
- .resize(previewMaxWidth)
125
- .webp()
126
- .toFile(outputPath);
127
+ try {
128
+ await sharp(inputPath)
129
+ .rotate()
130
+ .resize(previewMaxWidth)
131
+ .webp({ quality: 80 })
132
+ .toFile(outputPath);
133
+ }
134
+ catch {
135
+ throw new MediaContentError("This file isn't a supported image.");
136
+ }
127
137
  return { path: outputPath, mimetype: 'image/webp' };
128
138
  };
129
139
  const escapeXml = (value) => value
@@ -142,6 +152,18 @@ const createPdfPreview = async (inputPath) => {
142
152
  .resize(previewMaxWidth)
143
153
  .webp({ quality: 80 })
144
154
  .toFile(outputPath);
155
+ // sharp/poppler may produce a blank or corrupt thumbnail without erroring
156
+ // when fonts are missing (text renders as tofu rectangles) or the PDF page is
157
+ // genuinely empty. Validate the output so callers fall back to the document
158
+ // card preview, which shows the filename instead of garbled content.
159
+ const { size } = await fs.stat(outputPath);
160
+ if (size < 100) {
161
+ throw new Error('PDF preview rendered to empty image');
162
+ }
163
+ const stats = await sharp(outputPath).stats();
164
+ if (stats.channels.every((c) => c.stdev < 2)) {
165
+ throw new Error('PDF preview rendered to blank image');
166
+ }
145
167
  return { path: outputPath, mimetype: 'image/webp' };
146
168
  };
147
169
  const OFFICE_DOC_EXTENSIONS = new Set([
@@ -515,6 +515,7 @@ export declare const markPostsSeen: (posts: {
515
515
  }[], profile: Profile) => Promise<void>;
516
516
  export declare const markGroupPostsSeen: (authData: AuthorizationData, groupId: string) => Promise<void>;
517
517
  export declare const deletePost: (post: PostWithMeta, profile: Profile) => Promise<import("@openpeepshq/common").DbPost | undefined>;
518
+ export declare const validatePollVote: (post: PostWithMeta, data: Answer) => void;
518
519
  export declare const vote: (profile: Profile, post: PostWithMeta, data: Answer) => Promise<void>;
519
520
  export declare const rsvpRespond: (profile: Profile, post: PostWithMeta, data: RsvpRequest) => Promise<void>;
520
521
  export declare const rsvpManageByOrganizer: (actingProfile: Profile, targetProfile: Profile, post: PostWithMeta, response: Extract<RsvpResponse, "removed" | "yes">, recurrenceId?: string) => Promise<void>;
@@ -13,7 +13,7 @@ import { profilesCache } from '../profiles/cache.js';
13
13
  import { findOrCreateHashtag } from '../hashtags/index.js';
14
14
  import { hub } from '../events/index.js';
15
15
  import { listUnseenGroupPostIds } from './unseenCounts.js';
16
- import { AP_LIKE_REACTION, canManageEventRsvps, capacityRsvpDecision, eventDataForDbUpdate, getEffectiveRsvp, instanceRsvpIdsForProfile, isOneToOneDm, normalizeEventDataForSave, overlaySeriesRsvpEntries, participantIds, passThroughUndefined, rsvpCancelNotice, sameRecurrenceId, } from '@openpeepshq/common/lib';
16
+ import { AP_LIKE_REACTION, canManageEventRsvps, capacityRsvpDecision, eventDataForDbUpdate, getEffectiveRsvp, instanceRsvpIdsForProfile, isOneToOneDm, normalizeEventDataForSave, overlaySeriesRsvpEntries, participantIds, passThroughUndefined, rsvpCancelNotice, rsvpTargetsPastEvent, sameRecurrenceId, } from '@openpeepshq/common/lib';
17
17
  import { forbidden, unprocessableRequest } from '../errors/index.js';
18
18
  import { areBlocked, hasBlockAmong } from '../profiles/blocks.js';
19
19
  import { rebuildEventOccurrences, clearEventOccurrences, } from './eventOccurrences.js';
@@ -199,10 +199,51 @@ export const deletePost = async (post, profile) => {
199
199
  }
200
200
  return postsMapping.find(db, post.id);
201
201
  };
202
- export const vote = (profile, post, data) => allpeepDb().then(({ db }) => entryConnector(db, profile, post, {
203
- type: 'answer',
204
- data,
205
- }).then(() => hub.emit('entryCreated', profile, post, { type: 'answer', data })));
202
+ export const validatePollVote = (post, data) => {
203
+ if (post.data?.type !== 'question')
204
+ return;
205
+ const question = post.data;
206
+ if (question.expiresAt &&
207
+ Date.now() > new Date(question.expiresAt).getTime()) {
208
+ throw forbidden({ errorKey: 'error.pollClosed' });
209
+ }
210
+ const multiple = question.multiple ?? false;
211
+ const optionsCount = question.options.length;
212
+ // Empty selection is allowed — it clears an existing vote (undo).
213
+ if (data.selection.length === 0)
214
+ return;
215
+ if (!multiple && data.selection.length !== 1) {
216
+ throw unprocessableRequest({
217
+ errorKey: 'error.invalidPollVote',
218
+ parameters: { reason: 'singleChoiceRequired' },
219
+ });
220
+ }
221
+ const seen = new Set();
222
+ for (const index of data.selection) {
223
+ if (index < 0 || index >= optionsCount) {
224
+ throw unprocessableRequest({
225
+ errorKey: 'error.invalidPollVote',
226
+ parameters: { reason: 'optionOutOfRange' },
227
+ });
228
+ }
229
+ if (seen.has(index)) {
230
+ throw unprocessableRequest({
231
+ errorKey: 'error.invalidPollVote',
232
+ parameters: { reason: 'duplicateOption' },
233
+ });
234
+ }
235
+ seen.add(index);
236
+ }
237
+ };
238
+ export const vote = async (profile, post, data) => {
239
+ validatePollVote(post, data);
240
+ const { db } = await allpeepDb();
241
+ await entryConnector(db, profile, post, {
242
+ type: 'answer',
243
+ data,
244
+ });
245
+ await hub.emit('entryCreated', profile, post, { type: 'answer', data });
246
+ };
206
247
  const attendingRsvp = (response) => response === 'yes' || response === 'tentative';
207
248
  const rsvpOccurrenceIds = (data) => {
208
249
  if (data.recurrenceIds?.length)
@@ -259,6 +300,12 @@ export const rsvpRespond = async (profile, post, data) => {
259
300
  throw forbidden({ errorKey: 'error.rsvpRemovedForbidden' });
260
301
  }
261
302
  const occurrenceIds = rsvpOccurrenceIds(data);
303
+ if (rsvpTargetsPastEvent(post.data, {
304
+ occurrenceIds,
305
+ recurrenceId: data.recurrenceId,
306
+ })) {
307
+ throw unprocessableRequest({ errorKey: 'error.eventEnded' });
308
+ }
262
309
  if (!post.data.maxAttendees) {
263
310
  if (getEffectiveRsvp(post, profile.id)?.response === 'removed') {
264
311
  throw forbidden({ errorKey: 'error.rsvpRemoved' });
@@ -1,6 +1,6 @@
1
1
  import { profilesMapping } from './mapping.js';
2
2
  import { allpeepDb } from '../db/index.js';
3
- import { followConnector, followDisconnector, giveControl, roleAssigner, roleUnassigner, } from './helpers.js';
3
+ import { followConnector, followDisconnector, followFinder, giveControl, roleAssigner, roleUnassigner, } from './helpers.js';
4
4
  import { hub } from '../events/index.js';
5
5
  import { randomString } from '@openpeepshq/common/lib';
6
6
  import { deleteAccessTokensForProfile } from '../accessTokens/helpers.js';
@@ -66,9 +66,12 @@ export const deleteProfile = async (profileId) => {
66
66
  };
67
67
  export const follow = async (follower, followed, followData) => {
68
68
  const { db } = await allpeepDb();
69
- await followConnector(db, follower, followed, followData);
69
+ const existing = await followFinder(db, follower, followed);
70
+ if (!existing) {
71
+ await followConnector(db, follower, followed, followData);
72
+ await hub.emit('followCreated', follower, followed);
73
+ }
70
74
  await Promise.all([clearProfileCache(follower), clearProfileCache(followed)]);
71
- await hub.emit('followCreated', follower, followed);
72
75
  };
73
76
  export const unfollow = async (follower, followed) => {
74
77
  const { db } = await allpeepDb();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openpeepshq/core",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "type": "module",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "dependencies": {
@@ -38,9 +38,9 @@
38
38
  "uuidv7": "^1.0.2",
39
39
  "web-push": "^3.6.7",
40
40
  "@openpeepshq/common": "0.4.0",
41
+ "@openpeepshq/geocoder": "^0.1.2",
41
42
  "@openpeepshq/fetch-client": "^0.2.1",
42
- "@openpeepshq/i18n": "^0.2.1",
43
- "@openpeepshq/geocoder": "^0.1.2"
43
+ "@openpeepshq/i18n": "^0.2.1"
44
44
  },
45
45
  "main": "dist/index.js",
46
46
  "types": "dist/index.d.ts",