@openpeepshq/common 0.1.45 → 0.2.0

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.
Files changed (126) hide show
  1. package/dist/lib/adminSections.js +1 -1
  2. package/dist/lib/capabilitiesHelpers.d.ts +9 -7
  3. package/dist/lib/capabilitiesHelpers.js +43 -38
  4. package/dist/lib/csvHelpers.js +1 -1
  5. package/dist/lib/eventIcs.d.ts +17 -0
  6. package/dist/lib/eventIcs.js +91 -15
  7. package/dist/lib/eventRecurrence.d.ts +19 -0
  8. package/dist/lib/eventRecurrence.js +82 -20
  9. package/dist/lib/eventTime.d.ts +7 -0
  10. package/dist/lib/eventTime.js +23 -9
  11. package/dist/lib/federationHosts.d.ts +3 -0
  12. package/dist/lib/federationHosts.js +17 -0
  13. package/dist/lib/feedCursor.d.ts +14 -0
  14. package/dist/lib/feedCursor.js +22 -0
  15. package/dist/lib/feedFormat.d.ts +12 -0
  16. package/dist/lib/feedFormat.js +14 -0
  17. package/dist/lib/groupHelpers.js +13 -34
  18. package/dist/lib/groupTemplateHelpers.js +6 -10
  19. package/dist/lib/index.d.ts +7 -0
  20. package/dist/lib/index.js +7 -0
  21. package/dist/lib/jamHelpers.d.ts +11 -2
  22. package/dist/lib/jamHelpers.js +43 -9
  23. package/dist/lib/legacyThemeRoot.d.ts +3 -0
  24. package/dist/lib/legacyThemeRoot.js +10 -0
  25. package/dist/lib/markdownHelpers.d.ts +8 -0
  26. package/dist/lib/markdownHelpers.js +34 -6
  27. package/dist/lib/postHelpers.d.ts +142 -3
  28. package/dist/lib/postHelpers.js +323 -47
  29. package/dist/lib/profileHelpers.d.ts +11 -0
  30. package/dist/lib/profileHelpers.js +34 -10
  31. package/dist/lib/pushHelpers.js +3 -4
  32. package/dist/lib/reactions.d.ts +17 -0
  33. package/dist/lib/reactions.js +37 -0
  34. package/dist/lib/scopeHelpers.d.ts +31 -2
  35. package/dist/lib/scopeHelpers.js +39 -8
  36. package/dist/lib/ssoLoginUrl.js +4 -6
  37. package/dist/lib/ssoProviders.d.ts +72 -0
  38. package/dist/lib/ssoProviders.js +366 -0
  39. package/dist/lib/timeZone.d.ts +9 -0
  40. package/dist/lib/timeZone.js +44 -0
  41. package/dist/lib/tokenHelpers.js +5 -5
  42. package/dist/lib/utils.js +6 -7
  43. package/dist/types/admin-db.js +1 -1
  44. package/dist/types/analytics.d.ts +20 -0
  45. package/dist/types/analytics.js +4 -0
  46. package/dist/types/api.d.ts +41800 -11853
  47. package/dist/types/api.js +53 -5
  48. package/dist/types/auth.d.ts +20 -6
  49. package/dist/types/capabilities.d.ts +15 -1
  50. package/dist/types/capabilities.js +51 -0
  51. package/dist/types/config.d.ts +99 -0
  52. package/dist/types/config.js +56 -4
  53. package/dist/types/db.d.ts +1155 -164
  54. package/dist/types/db.js +14 -0
  55. package/dist/types/export.d.ts +120 -0
  56. package/dist/types/export.js +7 -0
  57. package/dist/types/index.d.ts +2 -0
  58. package/dist/types/index.js +2 -0
  59. package/dist/types/internal.d.ts +2577 -524
  60. package/dist/types/internal.js +6 -0
  61. package/dist/types/models.d.ts +63 -7
  62. package/dist/types/models.js +40 -3
  63. package/dist/types/plugins.d.ts +22 -0
  64. package/dist/types/plugins.js +66 -0
  65. package/dist/types/roleDefaults.d.ts +31 -0
  66. package/dist/types/roleDefaults.js +110 -0
  67. package/dist/types/stats.d.ts +54606 -6065
  68. package/dist/types/stats.js +30 -0
  69. package/dist/types/utils.d.ts +2 -0
  70. package/dist/types/utils.js +1 -3
  71. package/dist/zod.d.ts +1 -0
  72. package/dist/zod.js +1 -0
  73. package/package.json +36 -6
  74. package/src/index.ts +4 -0
  75. package/src/lib/adminSections.ts +84 -0
  76. package/src/lib/attachmentHelpers.ts +14 -0
  77. package/src/lib/capabilitiesHelpers.ts +532 -0
  78. package/src/lib/colors.ts +20 -0
  79. package/src/lib/csvHelpers.ts +31 -0
  80. package/src/lib/eventIcs.ts +265 -0
  81. package/src/lib/eventRecurrence.ts +495 -0
  82. package/src/lib/eventTime.ts +206 -0
  83. package/src/lib/federationHosts.ts +22 -0
  84. package/src/lib/feedCursor.ts +27 -0
  85. package/src/lib/feedFormat.ts +24 -0
  86. package/src/lib/groupHelpers.ts +421 -0
  87. package/src/lib/groupTemplateHelpers.ts +83 -0
  88. package/src/lib/index.ts +29 -0
  89. package/src/lib/jamHelpers.ts +164 -0
  90. package/src/lib/legacyThemeRoot.ts +14 -0
  91. package/src/lib/markdownHelpers.ts +122 -0
  92. package/src/lib/mediaDimensions.ts +21 -0
  93. package/src/lib/postHelpers.ts +783 -0
  94. package/src/lib/profileHelpers.ts +220 -0
  95. package/src/lib/pushHelpers.ts +34 -0
  96. package/src/lib/reactions.ts +52 -0
  97. package/src/lib/reportHelpers.ts +7 -0
  98. package/src/lib/scopeHelpers.ts +176 -0
  99. package/src/lib/ssoLoginUrl.ts +93 -0
  100. package/src/lib/ssoProviders.ts +472 -0
  101. package/src/lib/text.ts +26 -0
  102. package/src/lib/timeZone.ts +52 -0
  103. package/src/lib/tokenHelpers.ts +119 -0
  104. package/src/lib/utils.ts +322 -0
  105. package/src/types/admin-db.ts +74 -0
  106. package/src/types/admin-email.ts +55 -0
  107. package/src/types/admin-jobs.ts +17 -0
  108. package/src/types/admin-performance.ts +20 -0
  109. package/src/types/analytics.ts +318 -0
  110. package/src/types/api.ts +871 -0
  111. package/src/types/apple-app-site-association.ts +54 -0
  112. package/src/types/auth.ts +22 -0
  113. package/src/types/capabilities.ts +280 -0
  114. package/src/types/config.ts +546 -0
  115. package/src/types/db.ts +138 -0
  116. package/src/types/export.ts +10 -0
  117. package/src/types/index.ts +20 -0
  118. package/src/types/internal.ts +338 -0
  119. package/src/types/models.ts +939 -0
  120. package/src/types/notifications.ts +92 -0
  121. package/src/types/plugins.ts +150 -0
  122. package/src/types/roleDefaults.ts +132 -0
  123. package/src/types/stats.ts +195 -0
  124. package/src/types/stripe.ts +45 -0
  125. package/src/types/utils.ts +100 -0
  126. package/src/zod.ts +1 -0
@@ -45,15 +45,22 @@ export const getPublicPostReadScope = (postId) => ({
45
45
  scopeLevel: 'read',
46
46
  resource: { type: 'posts', id: postId },
47
47
  });
48
- /** Public posts are readable without auth; grant read scope for that post id. */
48
+ /**
49
+ * Posts with `public` visibility — and posts in groups that grant the needed
50
+ * *-read caps to `none` — are readable without auth; grant read scope for
51
+ * that post id (same pattern as {@link withPublicGroupReadScopes}).
52
+ */
49
53
  export const withPublicPostReadScopes = (authData, post, neededCapabilities) => {
50
- var _a;
51
- if (post.visibility !== 'public' ||
52
- !neededCapabilities.every((c) => c.endsWith('-read'))) {
54
+ if (!neededCapabilities.every((c) => c.endsWith('-read'))) {
55
+ return authData;
56
+ }
57
+ const publicGroupPost = post.visibility === 'group' &&
58
+ neededCapabilities.every((c) => post.group?.capabilities?.none?.add?.includes(c) ?? false);
59
+ if (post.visibility !== 'public' && !publicGroupPost) {
53
60
  return authData;
54
61
  }
55
62
  const publicReadScope = getPublicPostReadScope(post.id);
56
- const scopes = (_a = authData.scopes) !== null && _a !== void 0 ? _a : [];
63
+ const scopes = authData.scopes ?? [];
57
64
  if (scopeMatches({ scopes, requiredScope: publicReadScope })) {
58
65
  return authData;
59
66
  }
@@ -68,16 +75,40 @@ export const getPublicGroupReadScope = (groupId) => ({
68
75
  * without auth (same pattern as {@link withPublicPostReadScopes}).
69
76
  */
70
77
  export const withPublicGroupReadScopes = (authData, group, neededCapabilities) => {
71
- var _a, _b, _c, _d;
72
78
  if (!neededCapabilities.every((c) => c.endsWith('-read'))) {
73
79
  return authData;
74
80
  }
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 : [];
81
+ const noneAdd = group.capabilities?.none?.add ?? [];
76
82
  if (!neededCapabilities.every((c) => noneAdd.includes(c))) {
77
83
  return authData;
78
84
  }
79
85
  const publicReadScope = getPublicGroupReadScope(group.id);
80
- const scopes = (_d = authData.scopes) !== null && _d !== void 0 ? _d : [];
86
+ const scopes = authData.scopes ?? [];
87
+ if (scopeMatches({ scopes, requiredScope: publicReadScope })) {
88
+ return authData;
89
+ }
90
+ return { ...authData, scopes: [...scopes, publicReadScope] };
91
+ };
92
+ export const getPublicProfileReadScope = (profileId) => ({
93
+ scopeLevel: 'read',
94
+ resource: { type: 'profiles', id: profileId },
95
+ });
96
+ /**
97
+ * Profiles whose capabilities config grants the needed *-read caps to
98
+ * relationship `none` are readable without auth (same pattern as
99
+ * {@link withPublicGroupReadScopes}). Community-wide `publicContent` is
100
+ * still enforced by `ensureAccess` on the profile endpoints.
101
+ */
102
+ export const withPublicProfileReadScopes = (authData, profile, neededCapabilities, config) => {
103
+ if (!neededCapabilities.every((c) => c.endsWith('-read'))) {
104
+ return authData;
105
+ }
106
+ const noneAdd = config.profile?.none?.add ?? [];
107
+ if (!neededCapabilities.every((c) => noneAdd.includes(c))) {
108
+ return authData;
109
+ }
110
+ const publicReadScope = getPublicProfileReadScope(profile.id);
111
+ const scopes = authData.scopes ?? [];
81
112
  if (scopeMatches({ scopes, requiredScope: publicReadScope })) {
82
113
  return authData;
83
114
  }
@@ -16,16 +16,15 @@ export const isAllowedSsoLoginUrl = (url) => {
16
16
  };
17
17
  export const oidcAuthorizePath = (id) => `/api/openpeeps/core/v1/sso/oidc/${encodeURIComponent(id)}/authorize`;
18
18
  export const ssoLoginDestinations = (sso) => {
19
- var _a, _b;
20
19
  const destinations = [];
21
- for (const provider of (_a = sso === null || sso === void 0 ? void 0 : sso.generic) !== null && _a !== void 0 ? _a : []) {
20
+ for (const provider of sso?.generic ?? []) {
22
21
  destinations.push({
23
22
  href: provider.loginLink,
24
23
  name: provider.name,
25
24
  testId: `auth-login-generic-${provider.id}`,
26
25
  });
27
26
  }
28
- for (const provider of (_b = sso === null || sso === void 0 ? void 0 : sso.oidc) !== null && _b !== void 0 ? _b : []) {
27
+ for (const provider of sso?.oidc ?? []) {
29
28
  destinations.push({
30
29
  href: oidcAuthorizePath(provider.id),
31
30
  name: provider.name,
@@ -35,7 +34,7 @@ export const ssoLoginDestinations = (sso) => {
35
34
  return destinations;
36
35
  };
37
36
  export const resolveOnlySsoView = (sso, searchParams) => {
38
- if (!(sso === null || sso === void 0 ? void 0 : sso.onlySSO) || searchParams.has(LOCAL_LOGIN_PARAM)) {
37
+ if (!sso?.onlySSO || searchParams.has(LOCAL_LOGIN_PARAM)) {
39
38
  return { mode: 'form' };
40
39
  }
41
40
  const destinations = ssoLoginDestinations(sso);
@@ -51,8 +50,7 @@ export const publicSsoInfo = (sso) => {
51
50
  name: provider.name,
52
51
  }));
53
52
  const generic = sso.generic.flatMap((provider) => {
54
- var _a;
55
- const loginLink = (_a = provider.loginLink) === null || _a === void 0 ? void 0 : _a.trim();
53
+ const loginLink = provider.loginLink?.trim();
56
54
  if (!loginLink || !isAllowedSsoLoginUrl(loginLink))
57
55
  return [];
58
56
  return [
@@ -0,0 +1,72 @@
1
+ import { type CoreConfig } from '../types';
2
+ export declare const SSO_OIDC_KINDS: readonly ["oidc", "github", "gitlab", "gitlab-selfhosted", "google", "entra", "auth0", "keycloak", "authentik", "okta", "discord", "pocketid"];
3
+ export type SsoOidcKind = (typeof SSO_OIDC_KINDS)[number];
4
+ export type SsoProviderKind = SsoOidcKind | 'generic';
5
+ export declare const SSO_ADD_KINDS: readonly ["gitlab", "gitlab-selfhosted", "github", "google", "entra", "discord", "auth0", "okta", "keycloak", "authentik", "pocketid", "oidc", "generic"];
6
+ export type OidcProvider = CoreConfig['sso']['oidc'][number];
7
+ export type GenericProvider = CoreConfig['sso']['generic'][number];
8
+ export type OidcClaimMapping = NonNullable<OidcProvider['claimMapping']>;
9
+ export type OidcEndpoints = {
10
+ authorizationUrl: string;
11
+ tokenUrl: string;
12
+ userinfoUrl: string;
13
+ emailsUrl?: string;
14
+ jwksUri?: string;
15
+ scope: string;
16
+ claimMapping: OidcClaimMapping;
17
+ };
18
+ export type TemplateFieldNeed = false | 'optional' | 'required';
19
+ export type OidcTemplateNeeds = {
20
+ instanceUrl: TemplateFieldNeed;
21
+ tenant: TemplateFieldNeed;
22
+ };
23
+ export declare const ssoOidcKind: (provider: {
24
+ kind?: string;
25
+ }) => SsoOidcKind;
26
+ export declare const oidcTemplateNeeds: (kind: SsoProviderKind) => OidcTemplateNeeds;
27
+ export declare const isSsoAddKind: (value: string) => value is SsoProviderKind;
28
+ export declare const ssoKindDefaultId: (kind: SsoProviderKind) => string;
29
+ export declare const uniqueSsoProviderId: (base: string, used: Iterable<string>) => string;
30
+ export declare const ssoKindDefaultName: (kind: SsoProviderKind) => string;
31
+ export declare const githubOidcEndpoints: (instanceUrl?: string) => OidcEndpoints;
32
+ export declare const gitlabOidcEndpoints: (instanceUrl?: string) => OidcEndpoints;
33
+ export declare const oidcEndpoints: (kind: SsoOidcKind, fields?: {
34
+ instanceUrl?: string;
35
+ tenant?: string;
36
+ }) => OidcEndpoints | undefined;
37
+ export type OidcProviderFields = {
38
+ id: string;
39
+ name: string;
40
+ instanceUrl?: string;
41
+ tenant?: string;
42
+ clientId: string;
43
+ clientSecret?: string;
44
+ scope?: string;
45
+ approvalRequired?: boolean;
46
+ authorizationUrl?: string;
47
+ tokenUrl?: string;
48
+ userinfoUrl?: string;
49
+ emailsUrl?: string;
50
+ jwksUri?: string;
51
+ claimMapping?: OidcProvider['claimMapping'];
52
+ };
53
+ export declare const applyOidcProvider: (kind: SsoOidcKind, fields: OidcProviderFields) => OidcProvider;
54
+ export declare const applyGenericProvider: (fields: {
55
+ id: string;
56
+ name: string;
57
+ loginLink?: string;
58
+ profileUrl: string;
59
+ authHeader?: string;
60
+ emailPath: string;
61
+ handlePath?: string;
62
+ displayNamePath?: string;
63
+ avatarPath?: string;
64
+ createAccounts?: boolean;
65
+ createProfiles?: boolean;
66
+ }) => GenericProvider;
67
+ export declare const githubEmailsUrl: (provider: OidcProvider) => string | undefined;
68
+ export declare const discordAvatarUrl: (claims: Record<string, unknown>) => string | undefined;
69
+ export declare const pickOAuthEmail: (emails: unknown) => string | undefined;
70
+ export declare const parseOAuthTokenBody: (body: string, contentType: string | null) => Record<string, unknown>;
71
+ /** Keep stored secrets when a sanitized patch still carries the placeholder. */
72
+ export declare const restorePasswordPlaceholders: (incoming: unknown, existing: unknown) => unknown;
@@ -0,0 +1,366 @@
1
+ import { passwordPlaceHolder } from '../types/index.js';
2
+ export const SSO_OIDC_KINDS = [
3
+ 'oidc',
4
+ 'github',
5
+ 'gitlab',
6
+ 'gitlab-selfhosted',
7
+ 'google',
8
+ 'entra',
9
+ 'auth0',
10
+ 'keycloak',
11
+ 'authentik',
12
+ 'okta',
13
+ 'discord',
14
+ 'pocketid',
15
+ ];
16
+ export const SSO_ADD_KINDS = [
17
+ 'gitlab',
18
+ 'gitlab-selfhosted',
19
+ 'github',
20
+ 'google',
21
+ 'entra',
22
+ 'discord',
23
+ 'auth0',
24
+ 'okta',
25
+ 'keycloak',
26
+ 'authentik',
27
+ 'pocketid',
28
+ 'oidc',
29
+ 'generic',
30
+ ];
31
+ const stripSlash = (url) => url.replace(/\/$/, '');
32
+ const withHttps = (url) => {
33
+ const trimmed = stripSlash(url.trim());
34
+ if (!trimmed)
35
+ return '';
36
+ return /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
37
+ };
38
+ const isGitHubDotCom = (web) => /^https?:\/\/(www\.)?github\.com$/i.test(web);
39
+ const oidcClaims = (handle = 'preferred_username', displayName = 'name', avatar = 'picture') => ({
40
+ email: 'email',
41
+ handle,
42
+ displayName,
43
+ avatar,
44
+ });
45
+ export const ssoOidcKind = (provider) => SSO_OIDC_KINDS.includes(provider.kind)
46
+ ? provider.kind
47
+ : 'oidc';
48
+ export const oidcTemplateNeeds = (kind) => {
49
+ switch (kind) {
50
+ case 'github':
51
+ return { instanceUrl: 'optional', tenant: false };
52
+ case 'gitlab-selfhosted':
53
+ case 'auth0':
54
+ case 'okta':
55
+ case 'pocketid':
56
+ return {
57
+ instanceUrl: 'required',
58
+ tenant: kind === 'okta' ? 'optional' : false,
59
+ };
60
+ case 'keycloak':
61
+ case 'authentik':
62
+ return { instanceUrl: 'required', tenant: 'required' };
63
+ case 'entra':
64
+ return { instanceUrl: false, tenant: 'optional' };
65
+ default:
66
+ return { instanceUrl: false, tenant: false };
67
+ }
68
+ };
69
+ export const isSsoAddKind = (value) => SSO_ADD_KINDS.includes(value);
70
+ export const ssoKindDefaultId = (kind) => {
71
+ switch (kind) {
72
+ case 'gitlab-selfhosted':
73
+ return 'gitlab';
74
+ case 'entra':
75
+ return 'microsoft';
76
+ default:
77
+ return kind;
78
+ }
79
+ };
80
+ export const uniqueSsoProviderId = (base, used) => {
81
+ const taken = new Set(used);
82
+ if (!taken.has(base))
83
+ return base;
84
+ let n = 2;
85
+ while (taken.has(`${base}-${n}`))
86
+ n += 1;
87
+ return `${base}-${n}`;
88
+ };
89
+ export const ssoKindDefaultName = (kind) => {
90
+ switch (kind) {
91
+ case 'gitlab':
92
+ case 'gitlab-selfhosted':
93
+ return 'GitLab';
94
+ case 'github':
95
+ return 'GitHub';
96
+ case 'google':
97
+ return 'Google';
98
+ case 'entra':
99
+ return 'Microsoft';
100
+ case 'discord':
101
+ return 'Discord';
102
+ case 'auth0':
103
+ return 'Auth0';
104
+ case 'okta':
105
+ return 'Okta';
106
+ case 'keycloak':
107
+ return 'Keycloak';
108
+ case 'authentik':
109
+ return 'Authentik';
110
+ case 'pocketid':
111
+ return 'Pocket ID';
112
+ default:
113
+ return '';
114
+ }
115
+ };
116
+ export const githubOidcEndpoints = (instanceUrl) => {
117
+ const web = withHttps(instanceUrl || '') || 'https://github.com';
118
+ const api = isGitHubDotCom(web) ? 'https://api.github.com' : `${web}/api/v3`;
119
+ return {
120
+ authorizationUrl: `${web}/login/oauth/authorize`,
121
+ tokenUrl: `${web}/login/oauth/access_token`,
122
+ userinfoUrl: `${api}/user`,
123
+ emailsUrl: `${api}/user/emails`,
124
+ scope: 'read:user user:email',
125
+ claimMapping: oidcClaims('login', 'name', 'avatar_url'),
126
+ };
127
+ };
128
+ export const gitlabOidcEndpoints = (instanceUrl) => {
129
+ const base = withHttps(instanceUrl || '') || 'https://gitlab.com';
130
+ return {
131
+ authorizationUrl: `${base}/oauth/authorize`,
132
+ tokenUrl: `${base}/oauth/token`,
133
+ userinfoUrl: `${base}/oauth/userinfo`,
134
+ jwksUri: `${base}/oauth/discovery/keys`,
135
+ scope: 'openid email profile',
136
+ claimMapping: oidcClaims('nickname'),
137
+ };
138
+ };
139
+ export const oidcEndpoints = (kind, fields = {}) => {
140
+ const instance = withHttps(fields.instanceUrl || '');
141
+ const tenant = fields.tenant?.trim();
142
+ switch (kind) {
143
+ case 'github':
144
+ return githubOidcEndpoints(fields.instanceUrl);
145
+ case 'gitlab':
146
+ case 'gitlab-selfhosted':
147
+ return gitlabOidcEndpoints(kind === 'gitlab-selfhosted' ? instance : fields.instanceUrl);
148
+ case 'google':
149
+ return {
150
+ authorizationUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
151
+ tokenUrl: 'https://oauth2.googleapis.com/token',
152
+ userinfoUrl: 'https://openidconnect.googleapis.com/v1/userinfo',
153
+ jwksUri: 'https://www.googleapis.com/oauth2/v3/certs',
154
+ scope: 'openid email profile',
155
+ claimMapping: oidcClaims('email'),
156
+ };
157
+ case 'entra': {
158
+ const directory = tenant || 'common';
159
+ return {
160
+ authorizationUrl: `https://login.microsoftonline.com/${directory}/oauth2/v2.0/authorize`,
161
+ tokenUrl: `https://login.microsoftonline.com/${directory}/oauth2/v2.0/token`,
162
+ userinfoUrl: 'https://graph.microsoft.com/oidc/userinfo',
163
+ jwksUri: `https://login.microsoftonline.com/${directory}/discovery/v2.0/keys`,
164
+ scope: 'openid email profile',
165
+ claimMapping: oidcClaims(),
166
+ };
167
+ }
168
+ case 'auth0':
169
+ return {
170
+ authorizationUrl: `${instance}/authorize`,
171
+ tokenUrl: `${instance}/oauth/token`,
172
+ userinfoUrl: `${instance}/userinfo`,
173
+ jwksUri: `${instance}/.well-known/jwks.json`,
174
+ scope: 'openid email profile',
175
+ claimMapping: oidcClaims(),
176
+ };
177
+ case 'keycloak': {
178
+ const realm = `${instance}/realms/${tenant || 'master'}`;
179
+ return {
180
+ authorizationUrl: `${realm}/protocol/openid-connect/auth`,
181
+ tokenUrl: `${realm}/protocol/openid-connect/token`,
182
+ userinfoUrl: `${realm}/protocol/openid-connect/userinfo`,
183
+ jwksUri: `${realm}/protocol/openid-connect/certs`,
184
+ scope: 'openid email profile',
185
+ claimMapping: oidcClaims(),
186
+ };
187
+ }
188
+ case 'authentik':
189
+ return {
190
+ authorizationUrl: `${instance}/application/o/authorize/`,
191
+ tokenUrl: `${instance}/application/o/token/`,
192
+ userinfoUrl: `${instance}/application/o/userinfo/`,
193
+ jwksUri: tenant
194
+ ? `${instance}/application/o/${tenant}/jwks/`
195
+ : undefined,
196
+ scope: 'openid email profile',
197
+ claimMapping: oidcClaims(),
198
+ };
199
+ case 'okta': {
200
+ const server = tenant || 'default';
201
+ return {
202
+ authorizationUrl: `${instance}/oauth2/${server}/v1/authorize`,
203
+ tokenUrl: `${instance}/oauth2/${server}/v1/token`,
204
+ userinfoUrl: `${instance}/oauth2/${server}/v1/userinfo`,
205
+ jwksUri: `${instance}/oauth2/${server}/v1/keys`,
206
+ scope: 'openid email profile',
207
+ claimMapping: oidcClaims(),
208
+ };
209
+ }
210
+ case 'discord':
211
+ return {
212
+ authorizationUrl: 'https://discord.com/api/oauth2/authorize',
213
+ tokenUrl: 'https://discord.com/api/oauth2/token',
214
+ userinfoUrl: 'https://discord.com/api/users/@me',
215
+ scope: 'identify email',
216
+ claimMapping: oidcClaims('username', 'global_name', 'avatar'),
217
+ };
218
+ case 'pocketid':
219
+ return {
220
+ authorizationUrl: `${instance}/authorize`,
221
+ tokenUrl: `${instance}/api/oidc/token`,
222
+ userinfoUrl: `${instance}/api/oidc/userinfo`,
223
+ jwksUri: `${instance}/.well-known/jwks.json`,
224
+ scope: 'openid email profile',
225
+ claimMapping: oidcClaims(),
226
+ };
227
+ default:
228
+ return undefined;
229
+ }
230
+ };
231
+ export const applyOidcProvider = (kind, fields) => {
232
+ const tpl = oidcEndpoints(kind, fields);
233
+ if (tpl) {
234
+ return {
235
+ kind,
236
+ id: fields.id.trim(),
237
+ name: fields.name.trim(),
238
+ instanceUrl: fields.instanceUrl?.trim() || undefined,
239
+ tenant: fields.tenant?.trim() || undefined,
240
+ clientId: fields.clientId.trim(),
241
+ clientSecret: fields.clientSecret,
242
+ approvalRequired: fields.approvalRequired,
243
+ scope: fields.scope?.trim() || tpl.scope,
244
+ authorizationUrl: tpl.authorizationUrl,
245
+ tokenUrl: tpl.tokenUrl,
246
+ userinfoUrl: tpl.userinfoUrl,
247
+ emailsUrl: tpl.emailsUrl,
248
+ jwksUri: tpl.jwksUri,
249
+ claimMapping: tpl.claimMapping,
250
+ };
251
+ }
252
+ return {
253
+ kind: 'oidc',
254
+ id: fields.id.trim(),
255
+ name: fields.name.trim(),
256
+ clientId: fields.clientId.trim(),
257
+ clientSecret: fields.clientSecret,
258
+ approvalRequired: fields.approvalRequired,
259
+ scope: fields.scope?.trim() || 'openid email profile',
260
+ authorizationUrl: fields.authorizationUrl?.trim() || '',
261
+ tokenUrl: fields.tokenUrl?.trim() || '',
262
+ userinfoUrl: fields.userinfoUrl?.trim() || '',
263
+ emailsUrl: fields.emailsUrl?.trim() || undefined,
264
+ jwksUri: fields.jwksUri?.trim() || undefined,
265
+ claimMapping: {
266
+ email: fields.claimMapping?.email || 'email',
267
+ handle: fields.claimMapping?.handle || 'preferred_username',
268
+ displayName: fields.claimMapping?.displayName || 'name',
269
+ avatar: fields.claimMapping?.avatar || 'picture',
270
+ },
271
+ };
272
+ };
273
+ export const applyGenericProvider = (fields) => ({
274
+ id: fields.id.trim(),
275
+ name: fields.name.trim(),
276
+ loginLink: fields.loginLink?.trim() || undefined,
277
+ userProfileRequest: {
278
+ url: fields.profileUrl.trim(),
279
+ authHeader: fields.authHeader?.trim() || undefined,
280
+ },
281
+ userProfilePaths: {
282
+ email: fields.emailPath.trim(),
283
+ handle: fields.handlePath?.trim() || undefined,
284
+ displayName: fields.displayNamePath?.trim() || undefined,
285
+ avatar: fields.avatarPath?.trim() || undefined,
286
+ },
287
+ createAccounts: fields.createAccounts,
288
+ createProfiles: fields.createProfiles,
289
+ });
290
+ export const githubEmailsUrl = (provider) => provider.emailsUrl ||
291
+ (ssoOidcKind(provider) === 'github'
292
+ ? githubOidcEndpoints(provider.instanceUrl).emailsUrl
293
+ : undefined);
294
+ export const discordAvatarUrl = (claims) => {
295
+ const id = claims.id;
296
+ if (typeof id !== 'string' || !id)
297
+ return undefined;
298
+ const avatar = claims.avatar;
299
+ if (typeof avatar === 'string' && avatar) {
300
+ const format = avatar.startsWith('a_') ? 'gif' : 'png';
301
+ return `https://cdn.discordapp.com/avatars/${id}/${avatar}.${format}`;
302
+ }
303
+ const discriminator = typeof claims.discriminator === 'string' ? claims.discriminator : '0';
304
+ const index = discriminator === '0'
305
+ ? Number(BigInt(id) >> BigInt(22)) % 6
306
+ : Number.parseInt(discriminator, 10) % 5;
307
+ return `https://cdn.discordapp.com/embed/avatars/${Number.isFinite(index) ? index : 0}.png`;
308
+ };
309
+ export const pickOAuthEmail = (emails) => {
310
+ if (!Array.isArray(emails))
311
+ return undefined;
312
+ const rows = emails.flatMap((entry) => {
313
+ if (!entry || typeof entry !== 'object')
314
+ return [];
315
+ const email = entry.email;
316
+ if (typeof email !== 'string' || !email.includes('@'))
317
+ return [];
318
+ return [
319
+ {
320
+ email,
321
+ primary: !!entry.primary,
322
+ verified: entry.verified !== false,
323
+ },
324
+ ];
325
+ });
326
+ return (rows.find((row) => row.primary && row.verified)?.email ??
327
+ rows.find((row) => row.verified)?.email ??
328
+ rows[0]?.email);
329
+ };
330
+ export const parseOAuthTokenBody = (body, contentType) => {
331
+ const trimmed = body.trim();
332
+ const type = contentType ?? '';
333
+ if (type.includes('application/json') || trimmed.startsWith('{')) {
334
+ return JSON.parse(trimmed);
335
+ }
336
+ return Object.fromEntries(new URLSearchParams(trimmed));
337
+ };
338
+ const isRecord = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
339
+ const recordId = (value) => {
340
+ if (!isRecord(value) || typeof value.id !== 'string')
341
+ return undefined;
342
+ return value.id;
343
+ };
344
+ /** Keep stored secrets when a sanitized patch still carries the placeholder. */
345
+ export const restorePasswordPlaceholders = (incoming, existing) => {
346
+ if (incoming === passwordPlaceHolder) {
347
+ return existing === undefined ? incoming : existing;
348
+ }
349
+ if (Array.isArray(incoming)) {
350
+ const existingArr = Array.isArray(existing) ? existing : [];
351
+ return incoming.map((item, index) => {
352
+ const id = recordId(item);
353
+ const match = id
354
+ ? existingArr.find((entry) => recordId(entry) === id)
355
+ : existingArr[index];
356
+ return restorePasswordPlaceholders(item, match);
357
+ });
358
+ }
359
+ if (isRecord(incoming) && isRecord(existing)) {
360
+ return Object.fromEntries(Object.entries(incoming).map(([key, value]) => [
361
+ key,
362
+ restorePasswordPlaceholders(value, existing[key]),
363
+ ]));
364
+ }
365
+ return incoming;
366
+ };
@@ -0,0 +1,9 @@
1
+ export declare const FALLBACK_TIME_ZONE = "UTC";
2
+ export declare const isIanaTimeZone: (value: string | null | undefined) => value is string;
3
+ export declare const browserTimeZone: () => string;
4
+ export declare const ianaTimeZones: () => string[];
5
+ /**
6
+ * Profile timezone, then community timezone, then `fallback` (browser TZ
7
+ * when omitted; emails pass UTC so the worker host TZ is never used).
8
+ */
9
+ export declare const resolveTimeZone: (profileTimeZone?: string | null, communityDefault?: string | null, fallback?: string | null) => string;
@@ -0,0 +1,44 @@
1
+ export const FALLBACK_TIME_ZONE = 'UTC';
2
+ export const isIanaTimeZone = (value) => {
3
+ if (!value)
4
+ return false;
5
+ try {
6
+ new Intl.DateTimeFormat('en-US', { timeZone: value }).format();
7
+ return true;
8
+ }
9
+ catch {
10
+ return false;
11
+ }
12
+ };
13
+ export const browserTimeZone = () => {
14
+ try {
15
+ const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
16
+ return isIanaTimeZone(timeZone) ? timeZone : FALLBACK_TIME_ZONE;
17
+ }
18
+ catch {
19
+ return FALLBACK_TIME_ZONE;
20
+ }
21
+ };
22
+ export const ianaTimeZones = () => {
23
+ const supportedValuesOf = Intl.supportedValuesOf;
24
+ if (typeof supportedValuesOf === 'function') {
25
+ return supportedValuesOf('timeZone');
26
+ }
27
+ const timeZone = browserTimeZone();
28
+ return timeZone === FALLBACK_TIME_ZONE
29
+ ? [FALLBACK_TIME_ZONE]
30
+ : [timeZone, FALLBACK_TIME_ZONE];
31
+ };
32
+ /**
33
+ * Profile timezone, then community timezone, then `fallback` (browser TZ
34
+ * when omitted; emails pass UTC so the worker host TZ is never used).
35
+ */
36
+ export const resolveTimeZone = (profileTimeZone, communityDefault, fallback) => {
37
+ if (isIanaTimeZone(profileTimeZone))
38
+ return profileTimeZone;
39
+ if (isIanaTimeZone(communityDefault))
40
+ return communityDefault;
41
+ if (isIanaTimeZone(fallback))
42
+ return fallback;
43
+ return browserTimeZone();
44
+ };
@@ -6,7 +6,7 @@ export const decodeJwtPayloadUnverified = (token) => decodeJwt(token);
6
6
  * Session and access tokens embed that shape in the claim set.
7
7
  */
8
8
  export const parseScopesFromJwt = (token) => {
9
- if (!(token === null || token === void 0 ? void 0 : token.trim())) {
9
+ if (!token?.trim()) {
10
10
  return [];
11
11
  }
12
12
  try {
@@ -22,7 +22,7 @@ export const parseScopesFromJwt = (token) => {
22
22
  * (e.g. jam observer / egress links). These cannot load `profiles/current`.
23
23
  */
24
24
  export const isServiceOnlyJwt = (token) => {
25
- if (!(token === null || token === void 0 ? void 0 : token.trim())) {
25
+ if (!token?.trim()) {
26
26
  return false;
27
27
  }
28
28
  try {
@@ -41,7 +41,7 @@ export const isServiceOnlyJwt = (token) => {
41
41
  * These must not use the login JWT refresh path or `/accounts/current`.
42
42
  */
43
43
  export const isAccountlessJwt = (token) => {
44
- if (!(token === null || token === void 0 ? void 0 : token.trim())) {
44
+ if (!token?.trim()) {
45
45
  return false;
46
46
  }
47
47
  try {
@@ -63,7 +63,7 @@ export const isAccountlessJwt = (token) => {
63
63
  export const jwtHasRemainingValidityAtLeast = (token, minRemainingSeconds) => {
64
64
  if (!Number.isFinite(minRemainingSeconds) ||
65
65
  minRemainingSeconds < 0 ||
66
- !(token === null || token === void 0 ? void 0 : token.trim())) {
66
+ !token?.trim()) {
67
67
  return false;
68
68
  }
69
69
  try {
@@ -87,7 +87,7 @@ export const verifyJwt = async (token, publicKey) => {
87
87
  const verification = await jwtVerify(token, jwkPublicKey, {
88
88
  algorithms: ['EdDSA'],
89
89
  }).catch(() => undefined);
90
- return verification === null || verification === void 0 ? void 0 : verification.payload;
90
+ return verification?.payload;
91
91
  };
92
92
  export const parseJwtKeyId = (token) => {
93
93
  try {