@openpeepshq/common 0.1.43
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.
- package/LICENSE.md +21 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/lib/adminSections.d.ts +53 -0
- package/dist/lib/adminSections.js +62 -0
- package/dist/lib/attachmentHelpers.d.ts +1 -0
- package/dist/lib/attachmentHelpers.js +13 -0
- package/dist/lib/capabilitiesHelpers.d.ts +118 -0
- package/dist/lib/capabilitiesHelpers.js +238 -0
- package/dist/lib/colors.d.ts +5 -0
- package/dist/lib/colors.js +17 -0
- package/dist/lib/csvHelpers.d.ts +6 -0
- package/dist/lib/csvHelpers.js +17 -0
- package/dist/lib/eventIcs.d.ts +4 -0
- package/dist/lib/eventIcs.js +83 -0
- package/dist/lib/groupHelpers.d.ts +134 -0
- package/dist/lib/groupHelpers.js +216 -0
- package/dist/lib/index.d.ts +17 -0
- package/dist/lib/index.js +17 -0
- package/dist/lib/jamHelpers.d.ts +5 -0
- package/dist/lib/jamHelpers.js +37 -0
- package/dist/lib/markdownHelpers.d.ts +1 -0
- package/dist/lib/markdownHelpers.js +24 -0
- package/dist/lib/mediaDimensions.d.ts +19 -0
- package/dist/lib/mediaDimensions.js +19 -0
- package/dist/lib/postHelpers.d.ts +146 -0
- package/dist/lib/postHelpers.js +144 -0
- package/dist/lib/profileHelpers.d.ts +30 -0
- package/dist/lib/profileHelpers.js +75 -0
- package/dist/lib/pushHelpers.d.ts +4 -0
- package/dist/lib/pushHelpers.js +6 -0
- package/dist/lib/scopeHelpers.d.ts +25 -0
- package/dist/lib/scopeHelpers.js +85 -0
- package/dist/lib/text.d.ts +3 -0
- package/dist/lib/text.js +18 -0
- package/dist/lib/tokenHelpers.d.ts +21 -0
- package/dist/lib/tokenHelpers.js +81 -0
- package/dist/lib/utils.d.ts +43 -0
- package/dist/lib/utils.js +200 -0
- package/dist/types/admin-db.d.ts +62 -0
- package/dist/types/admin-db.js +41 -0
- package/dist/types/admin-email.d.ts +39 -0
- package/dist/types/admin-email.js +41 -0
- package/dist/types/admin-jobs.d.ts +15 -0
- package/dist/types/admin-jobs.js +14 -0
- package/dist/types/admin-performance.d.ts +23 -0
- package/dist/types/admin-performance.js +14 -0
- package/dist/types/analytics.d.ts +583 -0
- package/dist/types/analytics.js +213 -0
- package/dist/types/api.d.ts +20076 -0
- package/dist/types/api.js +492 -0
- package/dist/types/apple-app-site-association.d.ts +50 -0
- package/dist/types/apple-app-site-association.js +38 -0
- package/dist/types/auth.d.ts +367 -0
- package/dist/types/auth.js +17 -0
- package/dist/types/capabilities.d.ts +24 -0
- package/dist/types/capabilities.js +144 -0
- package/dist/types/config.d.ts +858 -0
- package/dist/types/config.js +352 -0
- package/dist/types/db.d.ts +8780 -0
- package/dist/types/db.js +65 -0
- package/dist/types/index.d.ts +18 -0
- package/dist/types/index.js +18 -0
- package/dist/types/internal.d.ts +44337 -0
- package/dist/types/internal.js +154 -0
- package/dist/types/models.d.ts +2619 -0
- package/dist/types/models.js +599 -0
- package/dist/types/notifications.d.ts +148 -0
- package/dist/types/notifications.js +40 -0
- package/dist/types/plugins.d.ts +66 -0
- package/dist/types/plugins.js +29 -0
- package/dist/types/stats.d.ts +10216 -0
- package/dist/types/stats.js +109 -0
- package/dist/types/stripe.d.ts +42 -0
- package/dist/types/stripe.js +35 -0
- package/dist/types/utils.d.ts +84 -0
- package/dist/types/utils.js +39 -0
- package/package.json +54 -0
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { Answer, AnswerWithPublicProfile, AuthorizationData, CapabilitiesConfig, Event, GroupWithMeta, PostType, PostDataUnion, PublicPost, PublicProfile, Thread, VisibilityType } from '../types';
|
|
2
|
+
export declare const buildThreads: (posts: PublicPost[]) => Thread[];
|
|
3
|
+
export declare const getReactionCount: (post: PublicPost) => Record<"👍", number>;
|
|
4
|
+
export declare const countVotes: (optionsCount: number, answers: Answer[]) => number[];
|
|
5
|
+
export declare const collectVotes: (post: PublicPost) => {
|
|
6
|
+
voteCounts: number[];
|
|
7
|
+
votes: AnswerWithPublicProfile[];
|
|
8
|
+
};
|
|
9
|
+
export declare const calculateEffectiveRsvps: (post: PublicPost) => {
|
|
10
|
+
response: "no" | "yes" | "tentative" | "removed";
|
|
11
|
+
profile: {
|
|
12
|
+
id: string;
|
|
13
|
+
type: "local" | "guest" | "federated";
|
|
14
|
+
createdAt: string;
|
|
15
|
+
updatedAt: string;
|
|
16
|
+
handle: string;
|
|
17
|
+
memberships: {
|
|
18
|
+
group: {
|
|
19
|
+
handle: string;
|
|
20
|
+
capabilities: Record<string, {
|
|
21
|
+
add?: string[] | undefined;
|
|
22
|
+
remove?: string[] | undefined;
|
|
23
|
+
} | undefined>;
|
|
24
|
+
id: string;
|
|
25
|
+
createdAt: string;
|
|
26
|
+
updatedAt: string;
|
|
27
|
+
avatar?: string | null | undefined;
|
|
28
|
+
header?: string | null | undefined;
|
|
29
|
+
displayName?: string | undefined;
|
|
30
|
+
description?: string | undefined;
|
|
31
|
+
rules?: string | undefined;
|
|
32
|
+
pinnedPostId?: string | undefined;
|
|
33
|
+
discoverable?: boolean | undefined;
|
|
34
|
+
deletedAt?: string | null | undefined;
|
|
35
|
+
};
|
|
36
|
+
roles?: ("none" | "local" | "member" | "admin" | "moderator" | "invited")[] | null | undefined;
|
|
37
|
+
}[] | undefined;
|
|
38
|
+
deletedAt?: string | null | undefined;
|
|
39
|
+
avatar?: string | null | undefined;
|
|
40
|
+
header?: string | null | undefined;
|
|
41
|
+
displayName?: string | undefined;
|
|
42
|
+
bio?: string | undefined;
|
|
43
|
+
location?: {
|
|
44
|
+
text: string;
|
|
45
|
+
coordinates?: {
|
|
46
|
+
lat: number;
|
|
47
|
+
lng: number;
|
|
48
|
+
alt?: number | undefined;
|
|
49
|
+
} | undefined;
|
|
50
|
+
} | undefined;
|
|
51
|
+
locked?: boolean | undefined;
|
|
52
|
+
bot?: boolean | undefined;
|
|
53
|
+
discoverable?: boolean | undefined;
|
|
54
|
+
fields?: {
|
|
55
|
+
name: string;
|
|
56
|
+
value: string;
|
|
57
|
+
}[] | undefined;
|
|
58
|
+
profileStats?: {
|
|
59
|
+
followersCount: number;
|
|
60
|
+
followingCount: number;
|
|
61
|
+
} | undefined;
|
|
62
|
+
};
|
|
63
|
+
createdAt: string;
|
|
64
|
+
}[];
|
|
65
|
+
export declare const getEffectiveRsvp: (post: PublicPost, profileId: string) => {
|
|
66
|
+
response: "no" | "yes" | "tentative" | "removed";
|
|
67
|
+
profile: {
|
|
68
|
+
id: string;
|
|
69
|
+
type: "local" | "guest" | "federated";
|
|
70
|
+
createdAt: string;
|
|
71
|
+
updatedAt: string;
|
|
72
|
+
handle: string;
|
|
73
|
+
memberships: {
|
|
74
|
+
group: {
|
|
75
|
+
handle: string;
|
|
76
|
+
capabilities: Record<string, {
|
|
77
|
+
add?: string[] | undefined;
|
|
78
|
+
remove?: string[] | undefined;
|
|
79
|
+
} | undefined>;
|
|
80
|
+
id: string;
|
|
81
|
+
createdAt: string;
|
|
82
|
+
updatedAt: string;
|
|
83
|
+
avatar?: string | null | undefined;
|
|
84
|
+
header?: string | null | undefined;
|
|
85
|
+
displayName?: string | undefined;
|
|
86
|
+
description?: string | undefined;
|
|
87
|
+
rules?: string | undefined;
|
|
88
|
+
pinnedPostId?: string | undefined;
|
|
89
|
+
discoverable?: boolean | undefined;
|
|
90
|
+
deletedAt?: string | null | undefined;
|
|
91
|
+
};
|
|
92
|
+
roles?: ("none" | "local" | "member" | "admin" | "moderator" | "invited")[] | null | undefined;
|
|
93
|
+
}[] | undefined;
|
|
94
|
+
deletedAt?: string | null | undefined;
|
|
95
|
+
avatar?: string | null | undefined;
|
|
96
|
+
header?: string | null | undefined;
|
|
97
|
+
displayName?: string | undefined;
|
|
98
|
+
bio?: string | undefined;
|
|
99
|
+
location?: {
|
|
100
|
+
text: string;
|
|
101
|
+
coordinates?: {
|
|
102
|
+
lat: number;
|
|
103
|
+
lng: number;
|
|
104
|
+
alt?: number | undefined;
|
|
105
|
+
} | undefined;
|
|
106
|
+
} | undefined;
|
|
107
|
+
locked?: boolean | undefined;
|
|
108
|
+
bot?: boolean | undefined;
|
|
109
|
+
discoverable?: boolean | undefined;
|
|
110
|
+
fields?: {
|
|
111
|
+
name: string;
|
|
112
|
+
value: string;
|
|
113
|
+
}[] | undefined;
|
|
114
|
+
profileStats?: {
|
|
115
|
+
followersCount: number;
|
|
116
|
+
followingCount: number;
|
|
117
|
+
} | undefined;
|
|
118
|
+
};
|
|
119
|
+
createdAt: string;
|
|
120
|
+
} | undefined;
|
|
121
|
+
export declare const countYesRsvps: (post: PublicPost) => number;
|
|
122
|
+
export declare const isCapacityEvent: (event: Event) => boolean;
|
|
123
|
+
export declare const parseEventMaxAttendeesInput: (raw: string) => number | undefined;
|
|
124
|
+
export declare const withoutEventMaxAttendees: <T extends Event>(event: T) => T;
|
|
125
|
+
export declare const normalizeEventDataForSave: <T extends Event>(event: T) => T;
|
|
126
|
+
/** ArangoDB may store null when capacity was cleared; strip for validation/output. */
|
|
127
|
+
export declare const normalizeEventDataFromDb: <T extends Event>(event: T) => T;
|
|
128
|
+
export declare const normalizePostDataFromDb: (data: PostDataUnion) => PostDataUnion;
|
|
129
|
+
/** ArangoDB update deep-merges nested `data`; null removes maxAttendees. */
|
|
130
|
+
export type EventDbUpdate = Omit<Event, 'maxAttendees'> & {
|
|
131
|
+
maxAttendees?: number | null;
|
|
132
|
+
};
|
|
133
|
+
export declare const eventDataForDbUpdate: (previous: Event | undefined, normalized: Event) => EventDbUpdate;
|
|
134
|
+
export declare const canManageEventRsvps: (profile: Pick<PublicProfile, "id"> | undefined, post: PublicPost) => boolean;
|
|
135
|
+
export type JamCapacityJoinBlock = {
|
|
136
|
+
blocked: false;
|
|
137
|
+
} | {
|
|
138
|
+
blocked: true;
|
|
139
|
+
reason: 'full' | 'rsvp-required' | 'removed';
|
|
140
|
+
};
|
|
141
|
+
export declare const getJamCapacityJoinBlock: (post: PublicPost, profile: Pick<PublicProfile, "id"> | undefined) => JamCapacityJoinBlock;
|
|
142
|
+
export declare const canDeletePost: (authData: AuthorizationData, post: PublicPost, config: CapabilitiesConfig) => boolean;
|
|
143
|
+
export declare const canCreatePost: (authData: AuthorizationData, type: PostType, visibility: VisibilityType, group?: GroupWithMeta) => boolean;
|
|
144
|
+
export declare const canCreatePostTypeInAnyGroup: (authData: AuthorizationData, type: PostType) => boolean;
|
|
145
|
+
export declare const canCreatePostTypeWithVisibility: (authData: AuthorizationData, type: PostType, visibility: VisibilityType) => boolean;
|
|
146
|
+
export declare const canCreatePostType: (authData: AuthorizationData, type: PostType) => boolean;
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { visibilityTypeValues, } from '../types/index.js';
|
|
2
|
+
import { canModerateJam } from './jamHelpers.js';
|
|
3
|
+
import { checkGroupCapabilities, checkPostCapabilities, checkRoleCapabilities, } from './capabilitiesHelpers.js';
|
|
4
|
+
import { scopeMatches } from './scopeHelpers.js';
|
|
5
|
+
import { countBy, dateSorter, groupBy, transformValues } from './utils.js';
|
|
6
|
+
const buildThread = (rootPost, postList) => ({
|
|
7
|
+
...rootPost,
|
|
8
|
+
children: postList
|
|
9
|
+
.filter((p) => p.inReplyToId === rootPost.id)
|
|
10
|
+
.map((post) => buildThread(post, postList)),
|
|
11
|
+
});
|
|
12
|
+
export const buildThreads = (posts) => posts
|
|
13
|
+
.filter((p) => !posts.find((p2) => p2.id === p.inReplyToId))
|
|
14
|
+
.map((post) => buildThread(post, posts))
|
|
15
|
+
.sort(dateSorter());
|
|
16
|
+
export const getReactionCount = (post) => {
|
|
17
|
+
return countBy(post.reactions, (r) => r.reaction);
|
|
18
|
+
};
|
|
19
|
+
export const countVotes = (optionsCount, answers) => {
|
|
20
|
+
const voteCounts = new Array(optionsCount).fill(0);
|
|
21
|
+
for (const answer of answers) {
|
|
22
|
+
for (const index of answer.selection) {
|
|
23
|
+
if (index < optionsCount) {
|
|
24
|
+
voteCounts[index] = voteCounts[index] + 1;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return voteCounts;
|
|
29
|
+
};
|
|
30
|
+
export const collectVotes = (post) => {
|
|
31
|
+
if (post.type !== 'question') {
|
|
32
|
+
return {
|
|
33
|
+
voteCounts: [],
|
|
34
|
+
votes: [],
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
const postData = post.data;
|
|
38
|
+
const sortedVoteEntries = post.entries
|
|
39
|
+
.filter((e) => e.type === 'answer')
|
|
40
|
+
.sort(dateSorter());
|
|
41
|
+
const votesByProfile = groupBy(sortedVoteEntries, (e) => e.profile.id);
|
|
42
|
+
const lastVoteByProfile = transformValues(votesByProfile, (votes) => votes.slice(-1)[0]);
|
|
43
|
+
const votes = [...Object.values(lastVoteByProfile)]
|
|
44
|
+
.filter((ve) => ve.data.selection.length > 0)
|
|
45
|
+
.map((entry) => ({
|
|
46
|
+
profile: entry.profile,
|
|
47
|
+
selection: entry.data.selection,
|
|
48
|
+
}));
|
|
49
|
+
const voteCounts = countVotes(postData.options.length, votes);
|
|
50
|
+
return {
|
|
51
|
+
votes,
|
|
52
|
+
voteCounts,
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
const latestRsvpPerProfile = (rsvps) => {
|
|
56
|
+
const rsvpsByProfile = groupBy(rsvps, (r) => r.profile.id);
|
|
57
|
+
return Object.values(rsvpsByProfile).map((profileRsvps) => {
|
|
58
|
+
const sorted = profileRsvps.sort(dateSorter());
|
|
59
|
+
return sorted[sorted.length - 1];
|
|
60
|
+
});
|
|
61
|
+
};
|
|
62
|
+
export const calculateEffectiveRsvps = (post) => latestRsvpPerProfile(post.rsvps || []);
|
|
63
|
+
export const getEffectiveRsvp = (post, profileId) => calculateEffectiveRsvps(post).find((r) => r.profile.id === profileId);
|
|
64
|
+
export const countYesRsvps = (post) => calculateEffectiveRsvps(post).filter((r) => r.response === 'yes').length;
|
|
65
|
+
export const isCapacityEvent = (event) => !!event.maxAttendees;
|
|
66
|
+
export const parseEventMaxAttendeesInput = (raw) => {
|
|
67
|
+
const trimmed = raw.trim();
|
|
68
|
+
if (!trimmed)
|
|
69
|
+
return undefined;
|
|
70
|
+
const parsed = Number.parseInt(trimmed, 10);
|
|
71
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
|
|
72
|
+
};
|
|
73
|
+
export const withoutEventMaxAttendees = (event) => {
|
|
74
|
+
const { maxAttendees: _, ...rest } = event;
|
|
75
|
+
return rest;
|
|
76
|
+
};
|
|
77
|
+
export const normalizeEventDataForSave = (event) => {
|
|
78
|
+
const { maxAttendees } = event;
|
|
79
|
+
if (maxAttendees == null ||
|
|
80
|
+
!Number.isFinite(maxAttendees) ||
|
|
81
|
+
maxAttendees < 1) {
|
|
82
|
+
return withoutEventMaxAttendees(event);
|
|
83
|
+
}
|
|
84
|
+
return { ...event, maxAttendees: Math.trunc(maxAttendees) };
|
|
85
|
+
};
|
|
86
|
+
/** ArangoDB may store null when capacity was cleared; strip for validation/output. */
|
|
87
|
+
export const normalizeEventDataFromDb = (event) => {
|
|
88
|
+
if (event.maxAttendees != null) {
|
|
89
|
+
return event;
|
|
90
|
+
}
|
|
91
|
+
return withoutEventMaxAttendees(event);
|
|
92
|
+
};
|
|
93
|
+
export const normalizePostDataFromDb = (data) => data.type === 'event' ? normalizeEventDataFromDb(data) : data;
|
|
94
|
+
export const eventDataForDbUpdate = (previous, normalized) => {
|
|
95
|
+
if ((previous === null || previous === void 0 ? void 0 : previous.maxAttendees) != null &&
|
|
96
|
+
!('maxAttendees' in normalized)) {
|
|
97
|
+
return { ...normalized, maxAttendees: null };
|
|
98
|
+
}
|
|
99
|
+
return normalized;
|
|
100
|
+
};
|
|
101
|
+
export const canManageEventRsvps = (profile, post) => !!(profile &&
|
|
102
|
+
(post.profile.id === profile.id || canModerateJam(profile, post)));
|
|
103
|
+
export const getJamCapacityJoinBlock = (post, profile) => {
|
|
104
|
+
var _a;
|
|
105
|
+
const event = ((_a = post.data) === null || _a === void 0 ? void 0 : _a.type) === 'event' ? post.data : undefined;
|
|
106
|
+
if (!(event === null || event === void 0 ? void 0 : event.maxAttendees) || !(profile === null || profile === void 0 ? void 0 : profile.id)) {
|
|
107
|
+
return { blocked: false };
|
|
108
|
+
}
|
|
109
|
+
if (canModerateJam(profile, post)) {
|
|
110
|
+
return { blocked: false };
|
|
111
|
+
}
|
|
112
|
+
const myRsvp = getEffectiveRsvp(post, profile.id);
|
|
113
|
+
if ((myRsvp === null || myRsvp === void 0 ? void 0 : myRsvp.response) === 'yes') {
|
|
114
|
+
return { blocked: false };
|
|
115
|
+
}
|
|
116
|
+
if ((myRsvp === null || myRsvp === void 0 ? void 0 : myRsvp.response) === 'removed') {
|
|
117
|
+
return { blocked: true, reason: 'removed' };
|
|
118
|
+
}
|
|
119
|
+
if (countYesRsvps(post) >= event.maxAttendees) {
|
|
120
|
+
return { blocked: true, reason: 'full' };
|
|
121
|
+
}
|
|
122
|
+
return { blocked: true, reason: 'rsvp-required' };
|
|
123
|
+
};
|
|
124
|
+
export const canDeletePost = (authData, post, config) => checkPostCapabilities(authData, ['core-posts-delete'], post, config).success;
|
|
125
|
+
export const canCreatePost = (authData, type, visibility, group) => {
|
|
126
|
+
var _a;
|
|
127
|
+
return visibility === 'group' ?
|
|
128
|
+
!!group && checkGroupCapabilities(authData, [`core-posts-create-${type}`], group).success :
|
|
129
|
+
checkRoleCapabilities((_a = authData.profile) === null || _a === void 0 ? void 0 : _a.roles, [`core-posts-create-${type}-${visibility}`]).success
|
|
130
|
+
&& scopeMatches({ scopes: authData.scopes, requiredScope: { scopeLevel: 'write', resource: { type: 'posts' } } });
|
|
131
|
+
};
|
|
132
|
+
export const canCreatePostTypeInAnyGroup = (authData, type) => {
|
|
133
|
+
var _a, _b;
|
|
134
|
+
return scopeMatches({ scopes: authData.scopes, requiredScope: { scopeLevel: 'write', resource: { type: 'groups' } } }) &&
|
|
135
|
+
!!((_b = (_a = authData.profile) === null || _a === void 0 ? void 0 : _a.memberships) === null || _b === void 0 ? void 0 : _b.some((m) => checkGroupCapabilities(authData, [`core-posts-create-${type}`], m.group).success));
|
|
136
|
+
};
|
|
137
|
+
export const canCreatePostTypeWithVisibility = (authData, type, visibility) => {
|
|
138
|
+
var _a;
|
|
139
|
+
return visibility === 'group' ?
|
|
140
|
+
canCreatePostTypeInAnyGroup(authData, type) :
|
|
141
|
+
checkRoleCapabilities((_a = authData.profile) === null || _a === void 0 ? void 0 : _a.roles, [`core-posts-create-${type}-${visibility}`]).success &&
|
|
142
|
+
scopeMatches({ scopes: authData.scopes, requiredScope: { scopeLevel: 'write', resource: { type: 'posts' } } });
|
|
143
|
+
};
|
|
144
|
+
export const canCreatePostType = (authData, type) => visibilityTypeValues.some((visibility) => canCreatePostTypeWithVisibility(authData, type, visibility));
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { GroupWithMeta, InviteLinkWithMeta, ProfileSettings, ProfileWithMeta, PublicProfile, StripeSubscriptionData } from '../types';
|
|
2
|
+
export declare const PROFILE_DISPLAY_NAME_MAX_LENGTH = 30;
|
|
3
|
+
/** Public sentinel shown for soft-deleted authors (API + clients). */
|
|
4
|
+
export declare const DELETED_AUTHOR_DISPLAY_NAME = "Deleted author";
|
|
5
|
+
export declare const DELETED_AUTHOR_HANDLE = "deleted";
|
|
6
|
+
export declare const clampProfileDisplayName: (displayName: string | undefined | null) => string | undefined;
|
|
7
|
+
export declare const isDeletedProfile: (profile: {
|
|
8
|
+
deletedAt?: string | null;
|
|
9
|
+
} | undefined | null) => boolean;
|
|
10
|
+
/**
|
|
11
|
+
* Strip PII from a soft-deleted profile for public API / UI surfaces.
|
|
12
|
+
* Keeps id + timestamps (including deletedAt) so clients can detect the state.
|
|
13
|
+
*/
|
|
14
|
+
export declare const toPublicDeletedProfile: <T extends PublicProfile>(profile: T) => T;
|
|
15
|
+
export declare const anonymizeProfileIfDeleted: <T extends PublicProfile>(profile: T | undefined | null) => T | undefined;
|
|
16
|
+
export declare const profileName: (profile?: PublicProfile) => string | undefined;
|
|
17
|
+
export declare const matchesQuery: (profile: PublicProfile | GroupWithMeta | undefined, query: string, queryOptions?: {
|
|
18
|
+
handle: boolean;
|
|
19
|
+
displayName: boolean;
|
|
20
|
+
}) => boolean;
|
|
21
|
+
export declare const inviteLinkMatchesQuery: (inviteLink: InviteLinkWithMeta, query: string, queryOptions?: {
|
|
22
|
+
handle: boolean;
|
|
23
|
+
displayName: boolean;
|
|
24
|
+
slug: boolean;
|
|
25
|
+
group: boolean;
|
|
26
|
+
}) => boolean;
|
|
27
|
+
export declare const sortProfiles: (profiles: PublicProfile[]) => PublicProfile[];
|
|
28
|
+
export declare const isStripeActive: (sub: StripeSubscriptionData | undefined | null) => boolean;
|
|
29
|
+
export declare const getStripeCustomerId: (profileSettings: ProfileSettings) => string | undefined;
|
|
30
|
+
export declare const isOwnerProfile: (profile: ProfileWithMeta) => boolean;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
const containsIgnoreCase = (candidate, query) => candidate.toLowerCase().indexOf(query.toLowerCase()) > -1;
|
|
2
|
+
export const PROFILE_DISPLAY_NAME_MAX_LENGTH = 30;
|
|
3
|
+
/** Public sentinel shown for soft-deleted authors (API + clients). */
|
|
4
|
+
export const DELETED_AUTHOR_DISPLAY_NAME = 'Deleted author';
|
|
5
|
+
export const DELETED_AUTHOR_HANDLE = 'deleted';
|
|
6
|
+
export const clampProfileDisplayName = (displayName) => {
|
|
7
|
+
if (!displayName)
|
|
8
|
+
return undefined;
|
|
9
|
+
const clamped = displayName.slice(0, PROFILE_DISPLAY_NAME_MAX_LENGTH);
|
|
10
|
+
return clamped || undefined;
|
|
11
|
+
};
|
|
12
|
+
export const isDeletedProfile = (profile) => !!(profile === null || profile === void 0 ? void 0 : profile.deletedAt);
|
|
13
|
+
/**
|
|
14
|
+
* Strip PII from a soft-deleted profile for public API / UI surfaces.
|
|
15
|
+
* Keeps id + timestamps (including deletedAt) so clients can detect the state.
|
|
16
|
+
*/
|
|
17
|
+
export const toPublicDeletedProfile = (profile) => ({
|
|
18
|
+
...profile,
|
|
19
|
+
displayName: DELETED_AUTHOR_DISPLAY_NAME,
|
|
20
|
+
handle: DELETED_AUTHOR_HANDLE,
|
|
21
|
+
avatar: null,
|
|
22
|
+
header: null,
|
|
23
|
+
bio: undefined,
|
|
24
|
+
location: undefined,
|
|
25
|
+
locked: undefined,
|
|
26
|
+
bot: undefined,
|
|
27
|
+
discoverable: undefined,
|
|
28
|
+
memberships: [],
|
|
29
|
+
fields: undefined,
|
|
30
|
+
profileStats: undefined,
|
|
31
|
+
});
|
|
32
|
+
export const anonymizeProfileIfDeleted = (profile) => {
|
|
33
|
+
if (!profile)
|
|
34
|
+
return undefined;
|
|
35
|
+
return isDeletedProfile(profile) ? toPublicDeletedProfile(profile) : profile;
|
|
36
|
+
};
|
|
37
|
+
export const profileName = (profile) => (profile === null || profile === void 0 ? void 0 : profile.displayName) || (profile === null || profile === void 0 ? void 0 : profile.handle);
|
|
38
|
+
export const matchesQuery = (profile, query, queryOptions = { handle: true, displayName: true }) => !!(profile &&
|
|
39
|
+
(query.startsWith('@')
|
|
40
|
+
? profile.handle && containsIgnoreCase(profile.handle, query.substring(1))
|
|
41
|
+
: (queryOptions.handle &&
|
|
42
|
+
profile.handle &&
|
|
43
|
+
containsIgnoreCase(profile.handle, query)) ||
|
|
44
|
+
(queryOptions.displayName &&
|
|
45
|
+
profile.displayName &&
|
|
46
|
+
containsIgnoreCase(profile.displayName, query))));
|
|
47
|
+
export const inviteLinkMatchesQuery = (inviteLink, query, queryOptions = { handle: true, displayName: true, slug: true, group: true }) => {
|
|
48
|
+
const profile = inviteLink.profile;
|
|
49
|
+
if (query.startsWith('@')) {
|
|
50
|
+
return !!((profile === null || profile === void 0 ? void 0 : profile.handle) && containsIgnoreCase(profile.handle, query.substring(1)));
|
|
51
|
+
}
|
|
52
|
+
const groupMatches = queryOptions.group &&
|
|
53
|
+
inviteLink.groups.some((group) => containsIgnoreCase(group.handle, query) ||
|
|
54
|
+
(group.displayName && containsIgnoreCase(group.displayName, query)));
|
|
55
|
+
return !!(groupMatches ||
|
|
56
|
+
(profile &&
|
|
57
|
+
((queryOptions.handle &&
|
|
58
|
+
profile.handle &&
|
|
59
|
+
containsIgnoreCase(profile.handle, query)) ||
|
|
60
|
+
(queryOptions.displayName &&
|
|
61
|
+
profile.displayName &&
|
|
62
|
+
containsIgnoreCase(profile.displayName, query)) ||
|
|
63
|
+
(queryOptions.slug &&
|
|
64
|
+
inviteLink.slug &&
|
|
65
|
+
containsIgnoreCase(inviteLink.slug, query)))));
|
|
66
|
+
};
|
|
67
|
+
export const sortProfiles = (profiles) => {
|
|
68
|
+
var _a;
|
|
69
|
+
return (_a = profiles === null || profiles === void 0 ? void 0 : profiles.sort((a, b) => profileName(a).localeCompare(profileName(b)))) !== null && _a !== void 0 ? _a : [];
|
|
70
|
+
};
|
|
71
|
+
export const isStripeActive = (sub) => (sub === null || sub === void 0 ? void 0 : sub.status) === 'active' || (sub === null || sub === void 0 ? void 0 : sub.status) === 'trialing';
|
|
72
|
+
export const getStripeCustomerId = (profileSettings) => { var _a; return (_a = profileSettings === null || profileSettings === void 0 ? void 0 : profileSettings.stripeSettings) === null || _a === void 0 ? void 0 : _a.customerId; };
|
|
73
|
+
export const isOwnerProfile = (profile) => {
|
|
74
|
+
return profile === null || profile === void 0 ? void 0 : profile.roles.some((role) => role.key === 'owner');
|
|
75
|
+
};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { PushSubscription } from '../types';
|
|
2
|
+
export declare const pushSubscriptionDeviceName: (subscription: PushSubscription) => string | undefined;
|
|
3
|
+
export declare const pushSubscriptionEndpoint: (subscription: PushSubscription) => string | undefined;
|
|
4
|
+
export declare const pushSubscriptionIsMobile: (subscription: PushSubscription) => boolean;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export const pushSubscriptionDeviceName = (subscription) => 'deviceName' in subscription ? subscription.deviceName : undefined;
|
|
2
|
+
export const pushSubscriptionEndpoint = (subscription) => 'endpoint' in subscription ? subscription.endpoint : undefined;
|
|
3
|
+
export const pushSubscriptionIsMobile = (subscription) => {
|
|
4
|
+
var _a;
|
|
5
|
+
return ((_a = pushSubscriptionDeviceName(subscription)) === null || _a === void 0 ? void 0 : _a.toLowerCase().match(/phone|android|mobile|ios/)) != null;
|
|
6
|
+
};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { AuthorizationData, PublicPost, Resource, Scope } from '../types';
|
|
2
|
+
export declare const calculateRequiredScope: ({ resource, requiredCapabilities, }: {
|
|
3
|
+
resource: Resource;
|
|
4
|
+
requiredCapabilities: string[];
|
|
5
|
+
}) => Scope;
|
|
6
|
+
export declare const scopeMatches: ({ scopes, requiredScope, }: {
|
|
7
|
+
scopes?: Scope[];
|
|
8
|
+
requiredScope: Scope;
|
|
9
|
+
}) => boolean;
|
|
10
|
+
export declare const getPublicPostReadScope: (postId: string) => Scope;
|
|
11
|
+
/** Public posts are readable without auth; grant read scope for that post id. */
|
|
12
|
+
export declare const withPublicPostReadScopes: (authData: AuthorizationData, post: Pick<PublicPost, "id" | "visibility">, neededCapabilities: string[]) => AuthorizationData;
|
|
13
|
+
export declare const getPublicGroupReadScope: (groupId: string) => Scope;
|
|
14
|
+
/**
|
|
15
|
+
* Groups that grant the needed *-read caps to relationship `none` are readable
|
|
16
|
+
* without auth (same pattern as {@link withPublicPostReadScopes}).
|
|
17
|
+
*/
|
|
18
|
+
export declare const withPublicGroupReadScopes: (authData: AuthorizationData, group: {
|
|
19
|
+
id: string;
|
|
20
|
+
capabilities?: {
|
|
21
|
+
none?: {
|
|
22
|
+
add?: string[];
|
|
23
|
+
};
|
|
24
|
+
} | null;
|
|
25
|
+
}, neededCapabilities: string[]) => AuthorizationData;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
const includesScopeLevel = (scopeLevel, requiredScopeLevel) => {
|
|
2
|
+
switch (requiredScopeLevel) {
|
|
3
|
+
case 'write':
|
|
4
|
+
return scopeLevel === 'write' || scopeLevel === 'admin';
|
|
5
|
+
case 'read':
|
|
6
|
+
return (scopeLevel === 'read' ||
|
|
7
|
+
scopeLevel === 'write' ||
|
|
8
|
+
scopeLevel === 'admin');
|
|
9
|
+
case 'admin':
|
|
10
|
+
return scopeLevel === 'admin';
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
const calculateRequiredScopeLevel = (requiredCapabilities) => {
|
|
14
|
+
return requiredCapabilities.reduce((acc, capability) => {
|
|
15
|
+
if (acc === 'admin') {
|
|
16
|
+
return 'admin';
|
|
17
|
+
}
|
|
18
|
+
if (capability.endsWith('-create') ||
|
|
19
|
+
capability.endsWith('-update') ||
|
|
20
|
+
capability.endsWith('-delete')) {
|
|
21
|
+
return 'write';
|
|
22
|
+
}
|
|
23
|
+
else if (!capability.endsWith('-read')) {
|
|
24
|
+
return 'admin';
|
|
25
|
+
}
|
|
26
|
+
return acc;
|
|
27
|
+
}, 'read');
|
|
28
|
+
};
|
|
29
|
+
export const calculateRequiredScope = ({ resource, requiredCapabilities, }) => ({
|
|
30
|
+
scopeLevel: calculateRequiredScopeLevel(requiredCapabilities),
|
|
31
|
+
resource,
|
|
32
|
+
});
|
|
33
|
+
export const scopeMatches = ({ scopes, requiredScope, }) => Array.isArray(scopes) &&
|
|
34
|
+
!!scopes.find((s) => (!s.scopeLevel ||
|
|
35
|
+
!requiredScope.scopeLevel ||
|
|
36
|
+
includesScopeLevel(s.scopeLevel, requiredScope.scopeLevel)) &&
|
|
37
|
+
(!s.resource.id ||
|
|
38
|
+
s.resource.id === requiredScope.resource.id ||
|
|
39
|
+
s.resource.id === '*' ||
|
|
40
|
+
requiredScope.resource.id === '*') &&
|
|
41
|
+
(s.resource.type === requiredScope.resource.type ||
|
|
42
|
+
s.resource.type === '*' ||
|
|
43
|
+
requiredScope.resource.type === '*'));
|
|
44
|
+
export const getPublicPostReadScope = (postId) => ({
|
|
45
|
+
scopeLevel: 'read',
|
|
46
|
+
resource: { type: 'posts', id: postId },
|
|
47
|
+
});
|
|
48
|
+
/** Public posts are readable without auth; grant read scope for that post id. */
|
|
49
|
+
export const withPublicPostReadScopes = (authData, post, neededCapabilities) => {
|
|
50
|
+
var _a;
|
|
51
|
+
if (post.visibility !== 'public' ||
|
|
52
|
+
!neededCapabilities.every((c) => c.endsWith('-read'))) {
|
|
53
|
+
return authData;
|
|
54
|
+
}
|
|
55
|
+
const publicReadScope = getPublicPostReadScope(post.id);
|
|
56
|
+
const scopes = (_a = authData.scopes) !== null && _a !== void 0 ? _a : [];
|
|
57
|
+
if (scopeMatches({ scopes, requiredScope: publicReadScope })) {
|
|
58
|
+
return authData;
|
|
59
|
+
}
|
|
60
|
+
return { ...authData, scopes: [...scopes, publicReadScope] };
|
|
61
|
+
};
|
|
62
|
+
export const getPublicGroupReadScope = (groupId) => ({
|
|
63
|
+
scopeLevel: 'read',
|
|
64
|
+
resource: { type: 'groups', id: groupId },
|
|
65
|
+
});
|
|
66
|
+
/**
|
|
67
|
+
* Groups that grant the needed *-read caps to relationship `none` are readable
|
|
68
|
+
* without auth (same pattern as {@link withPublicPostReadScopes}).
|
|
69
|
+
*/
|
|
70
|
+
export const withPublicGroupReadScopes = (authData, group, neededCapabilities) => {
|
|
71
|
+
var _a, _b, _c, _d;
|
|
72
|
+
if (!neededCapabilities.every((c) => c.endsWith('-read'))) {
|
|
73
|
+
return authData;
|
|
74
|
+
}
|
|
75
|
+
const noneAdd = (_c = (_b = (_a = group.capabilities) === null || _a === void 0 ? void 0 : _a.none) === null || _b === void 0 ? void 0 : _b.add) !== null && _c !== void 0 ? _c : [];
|
|
76
|
+
if (!neededCapabilities.every((c) => noneAdd.includes(c))) {
|
|
77
|
+
return authData;
|
|
78
|
+
}
|
|
79
|
+
const publicReadScope = getPublicGroupReadScope(group.id);
|
|
80
|
+
const scopes = (_d = authData.scopes) !== null && _d !== void 0 ? _d : [];
|
|
81
|
+
if (scopeMatches({ scopes, requiredScope: publicReadScope })) {
|
|
82
|
+
return authData;
|
|
83
|
+
}
|
|
84
|
+
return { ...authData, scopes: [...scopes, publicReadScope] };
|
|
85
|
+
};
|
package/dist/lib/text.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export const truncateText = (text, maxLength = 15) => {
|
|
2
|
+
if (!text)
|
|
3
|
+
return '';
|
|
4
|
+
if (text.length <= maxLength)
|
|
5
|
+
return text;
|
|
6
|
+
return text.length > maxLength ? `${text.substring(0, maxLength)}...` : text;
|
|
7
|
+
};
|
|
8
|
+
export const randomString = (length, characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') => {
|
|
9
|
+
let result = '';
|
|
10
|
+
const charactersLength = characters.length;
|
|
11
|
+
let counter = 0;
|
|
12
|
+
while (counter < length) {
|
|
13
|
+
result += characters.charAt(Math.floor(Math.random() * charactersLength));
|
|
14
|
+
counter += 1;
|
|
15
|
+
}
|
|
16
|
+
return result;
|
|
17
|
+
};
|
|
18
|
+
export const capitalizeFirstLetter = (string) => string.charAt(0).toUpperCase() + string.slice(1);
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type JWTPayload } from 'jose';
|
|
2
|
+
import type { Scope } from '../types/models';
|
|
3
|
+
export declare const decodeJwtPayloadUnverified: (token: string) => JWTPayload;
|
|
4
|
+
/**
|
|
5
|
+
* Reads `scopes` from a JWT by validating the payload as {@link Authorization} (no signature verification).
|
|
6
|
+
* Session and access tokens embed that shape in the claim set.
|
|
7
|
+
*/
|
|
8
|
+
export declare const parseScopesFromJwt: (token: string | undefined | null) => Scope[];
|
|
9
|
+
/**
|
|
10
|
+
* True for JWTs that authenticate a service identity without a profile
|
|
11
|
+
* (e.g. jam observer / egress links). These cannot load `profiles/current`.
|
|
12
|
+
*/
|
|
13
|
+
export declare const isServiceOnlyJwt: (token: string | undefined | null) => boolean;
|
|
14
|
+
/**
|
|
15
|
+
* True when the token has a numeric `exp`, is not expired yet, and seconds until expiry is at least
|
|
16
|
+
* `minRemainingSeconds`. Non-finite or negative `minRemainingSeconds` yields false. Invalid or undecodable
|
|
17
|
+
* tokens return false.
|
|
18
|
+
*/
|
|
19
|
+
export declare const jwtHasRemainingValidityAtLeast: (token: string | undefined | null, minRemainingSeconds: number) => boolean;
|
|
20
|
+
export declare const verifyJwt: (token: string, publicKey: string) => Promise<JWTPayload | undefined>;
|
|
21
|
+
export declare const parseJwtKeyId: (token: string) => string | undefined;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { decodeJwt, decodeProtectedHeader, importJWK, jwtVerify, } from 'jose';
|
|
2
|
+
import { authorizationSchema } from '../types/auth.js';
|
|
3
|
+
export const decodeJwtPayloadUnverified = (token) => decodeJwt(token);
|
|
4
|
+
/**
|
|
5
|
+
* Reads `scopes` from a JWT by validating the payload as {@link Authorization} (no signature verification).
|
|
6
|
+
* Session and access tokens embed that shape in the claim set.
|
|
7
|
+
*/
|
|
8
|
+
export const parseScopesFromJwt = (token) => {
|
|
9
|
+
if (!(token === null || token === void 0 ? void 0 : token.trim())) {
|
|
10
|
+
return [];
|
|
11
|
+
}
|
|
12
|
+
try {
|
|
13
|
+
const parsed = authorizationSchema.safeParse(decodeJwt(token));
|
|
14
|
+
return parsed.success ? parsed.data.scopes : [];
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return [];
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* True for JWTs that authenticate a service identity without a profile
|
|
22
|
+
* (e.g. jam observer / egress links). These cannot load `profiles/current`.
|
|
23
|
+
*/
|
|
24
|
+
export const isServiceOnlyJwt = (token) => {
|
|
25
|
+
if (!(token === null || token === void 0 ? void 0 : token.trim())) {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
try {
|
|
29
|
+
const parsed = authorizationSchema.safeParse(decodeJwt(token));
|
|
30
|
+
if (!parsed.success)
|
|
31
|
+
return false;
|
|
32
|
+
const { service, profile } = parsed.data.identities;
|
|
33
|
+
return !!service && !profile;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* True when the token has a numeric `exp`, is not expired yet, and seconds until expiry is at least
|
|
41
|
+
* `minRemainingSeconds`. Non-finite or negative `minRemainingSeconds` yields false. Invalid or undecodable
|
|
42
|
+
* tokens return false.
|
|
43
|
+
*/
|
|
44
|
+
export const jwtHasRemainingValidityAtLeast = (token, minRemainingSeconds) => {
|
|
45
|
+
if (!Number.isFinite(minRemainingSeconds) ||
|
|
46
|
+
minRemainingSeconds < 0 ||
|
|
47
|
+
!(token === null || token === void 0 ? void 0 : token.trim())) {
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
try {
|
|
51
|
+
const { exp } = decodeJwt(token);
|
|
52
|
+
if (typeof exp !== 'number') {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
const nowSec = Date.now() / 1000;
|
|
56
|
+
return exp - nowSec >= minRemainingSeconds;
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
export const verifyJwt = async (token, publicKey) => {
|
|
63
|
+
const jwkPublicKey = await importJWK({
|
|
64
|
+
kty: 'OKP',
|
|
65
|
+
crv: 'Ed25519',
|
|
66
|
+
x: publicKey,
|
|
67
|
+
});
|
|
68
|
+
const verification = await jwtVerify(token, jwkPublicKey, {
|
|
69
|
+
algorithms: ['EdDSA'],
|
|
70
|
+
}).catch(() => undefined);
|
|
71
|
+
return verification === null || verification === void 0 ? void 0 : verification.payload;
|
|
72
|
+
};
|
|
73
|
+
export const parseJwtKeyId = (token) => {
|
|
74
|
+
try {
|
|
75
|
+
const { kid } = decodeProtectedHeader(token);
|
|
76
|
+
return typeof kid === 'string' ? kid : undefined;
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
};
|