@foundrykit/hub-plugin 0.1.4 → 0.3.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.
package/README.md CHANGED
@@ -1,12 +1,19 @@
1
1
  # @foundrykit/hub-plugin
2
2
 
3
- Tells the Foundry Hub what a Payload 3 site is actually running. Each time the
4
- site starts it sends one report: every `@foundrykit/*` package with its
5
- installed version, the FoundryKit plugins switched on, the environment, the
6
- site URL, the git commit, and the Payload and Next.js versions. The Hub shows it
7
- on the site's page, per environment.
3
+ Connects a Payload 3 site to the Foundry Hub:
8
4
 
9
- It never holds up or breaks boot: the request gives up after 3 seconds and
5
+ - **Reports** what the site is actually running. Each time the site starts it
6
+ sends one report: every `@foundrykit/*` package with its installed version,
7
+ the FoundryKit plugins switched on, the environment, the site URL, the git
8
+ commit, and the Payload and Next.js versions. The Hub shows it on the site's
9
+ page, per environment.
10
+ - **One-click admin.** Umi staff click **Open admin** on the site's page in the
11
+ Hub and land in this site's Payload admin, already signed in.
12
+ - **Offboarding.** When a Umi staff member is deactivated or removed from Umi in
13
+ the Hub, their account here is locked and signed out; reactivating them
14
+ unlocks it. Client users are never touched.
15
+
16
+ None of it holds up or breaks boot: each request gives up after 3 seconds and
10
17
  failures are logged as a warning.
11
18
 
12
19
  ## Install
@@ -50,3 +57,63 @@ FOUNDRY_ENV=production # or staging, …
50
57
  - Installed versions are read from `node_modules`. If a package's
51
58
  `package.json` isn't there (for example a pruned standalone build), the
52
59
  declared range is sent instead and the Hub shows its status as unknown.
60
+
61
+ ## One-click admin
62
+
63
+ **Open admin** (shown to Umi staff on each environment that has a domain in the
64
+ Hub) sends the browser to `https://<domain>/api/hub/login?ticket=…`. The plugin:
65
+
66
+ 1. redeems the ticket with the Hub (`POST /api/sites/admin-login`, with the site
67
+ key and environment). A ticket works once, for 60 seconds, only for this
68
+ site's key and environment, and only while the person is still active Umi
69
+ staff;
70
+ 2. finds the user by email in the admin's auth collection (`admin.user`), or
71
+ **creates** one with a random password (they can still choose a password with
72
+ forgot-password). If the collection has the permissions plugin's `role`
73
+ field, a new Umi admin or developer gets the `Admin` role and other staff
74
+ get `Editor`; if that role doesn't exist, the user is created without one and
75
+ a warning is logged. An existing user's role is never changed;
76
+ 3. signs them in for **8 hours** (its own session and token; password logins keep
77
+ the collection's `tokenExpiration`) and redirects to the admin.
78
+
79
+ Anything that fails redirects to `/admin/login?hub=<reason>` (`expired`,
80
+ `invalid`, `not-configured` or `failed`) and logs the error. The redirect only
81
+ ever goes to this site's own admin route.
82
+
83
+ Passwords keep working for everyone: the Hub is the main way in, not the only
84
+ one.
85
+
86
+ ## Offboarding
87
+
88
+ The Hub sorts Umi staff into **active** (Umi members who aren't deactivated)
89
+ and **locked** (deactivated Umi members, anyone the Hub knows with no
90
+ organisation left, i.e. removed from Umi, and staff deleted from the Hub).
91
+ Client users are in neither and are left alone.
92
+
93
+ A site never gets those lists whole. To sync, the plugin reads the emails of its
94
+ own admin users (2,000 at a time) and sends them to `POST /api/sites/staff`; the
95
+ Hub answers with which of _those_ are active or locked. So a leaked site key
96
+ only reveals the status of emails the caller already knows.
97
+
98
+ The plugin syncs **on boot** and whenever the Hub calls `POST /api/hub/sync` (it
99
+ does after deactivating, reactivating, removing from or adding to Umi, inviting
100
+ to Umi, or deleting someone). That endpoint takes no input and trusts nothing:
101
+ it only makes the site sync with the Hub using its own key, and calls within 10
102
+ seconds of the last one are ignored.
103
+
104
+ - **Lock**: `lockUntil` is set to `9999-12-31T00:00:00.000Z` and every session
105
+ is removed.
106
+ - **Unlock**: only accounts locked with that exact date (not ones locked by too
107
+ many wrong passwords) whose email is active again.
108
+ - **Password logins** (and the sign-in after a password reset) ask the Hub about
109
+ that email first (2 s at most). If it says locked, the login is refused and
110
+ the account is locked. If the Hub doesn't answer or isn't configured, the
111
+ login goes ahead.
112
+
113
+ Locking needs `lockUntil`, which Payload only adds when `auth.maxLoginAttempts`
114
+ is above 0 (the default is 5). With `maxLoginAttempts: 0` the plugin logs once
115
+ and doesn't lock, but still refuses password logins the Hub says are locked.
116
+ Without `auth.useSessions` (on by default), existing tokens can't be revoked and
117
+ stay valid until they expire.
118
+
119
+ `fk run` (local dev) has no **Open admin** yet.
@@ -0,0 +1,35 @@
1
+ import { type CollectionBeforeLoginHook, type Endpoint, type Payload } from 'payload';
2
+ import { type AdminLogin, type HubSettings, type StaffLists } from './hub.js';
3
+ /** `lockUntil` for accounts the Hub locked: far enough away that only a sync unlocks it. */
4
+ export declare const LOCK_SENTINEL = "9999-12-31T00:00:00.000Z";
5
+ /** One-click sessions last 8 hours. */
6
+ export declare const SESSION_SECONDS: number;
7
+ /** /api/hub/sync ignores calls closer together than this. */
8
+ export declare const SYNC_INTERVAL_MS = 10000;
9
+ export declare const payloadRoleName: (role: AdminLogin["role"]) => "Admin" | "Editor";
10
+ export declare function isHubLocked(lockUntil: unknown): boolean;
11
+ type UserDoc = {
12
+ id: number | string;
13
+ email?: string | null;
14
+ lockUntil?: unknown;
15
+ loginAttempts?: number | null;
16
+ sessions?: unknown[] | null;
17
+ };
18
+ /**
19
+ * Who to lock (on the Hub's locked list and not already locked and signed
20
+ * out) and who to unlock (active again, and locked by us, not by bad
21
+ * passwords). Everyone else is left alone.
22
+ */
23
+ export declare function syncPlan(users: UserDoc[], lists: StaffLists): {
24
+ lock: UserDoc[];
25
+ unlock: UserDoc[];
26
+ };
27
+ /**
28
+ * Sends the Hub this site's user emails, gets back which are staff to lock or
29
+ * unlock, and applies that. Never throws; false when it couldn't.
30
+ */
31
+ export declare function syncStaff(payload: Payload, settings: HubSettings): Promise<boolean>;
32
+ /** Refuses a password login (or a reset's sign-in) for someone the Hub has offboarded. Fails open. */
33
+ export declare const hubLockHook: (settings: () => HubSettings | null) => CollectionBeforeLoginHook;
34
+ export declare function adminEndpoints(settings: () => HubSettings | null): Endpoint[];
35
+ export {};
package/dist/admin.js ADDED
@@ -0,0 +1,336 @@
1
+ /**
2
+ * One-click admin and staff offboarding. The Hub mints a ticket, /api/hub/login
3
+ * redeems it and signs the person in for 8 hours; /api/hub/sync and boot ask
4
+ * the Hub about this site's users and lock or unlock Umi staff accounts.
5
+ */ import { randomBytes } from 'node:crypto';
6
+ import { getFieldsToSign, jwtSign, LockedAuth } from 'payload';
7
+ import { addSessionToUser, generatePayloadCookie } from 'payload/shared';
8
+ import { fetchStaff, fetchStaffStatus, redeemTicket, STAFF_BATCH } from './hub.js';
9
+ /** `lockUntil` for accounts the Hub locked: far enough away that only a sync unlocks it. */ export const LOCK_SENTINEL = '9999-12-31T00:00:00.000Z';
10
+ /** One-click sessions last 8 hours. */ export const SESSION_SECONDS = 8 * 60 * 60;
11
+ /** /api/hub/sync ignores calls closer together than this. */ export const SYNC_INTERVAL_MS = 10_000;
12
+ export const payloadRoleName = (role)=>role === 'admin' ? 'Admin' : 'Editor';
13
+ export function isHubLocked(lockUntil) {
14
+ if (!lockUntil) return false;
15
+ const d = new Date(lockUntil);
16
+ return !Number.isNaN(d.getTime()) && d.toISOString() === LOCK_SENTINEL;
17
+ }
18
+ /**
19
+ * Who to lock (on the Hub's locked list and not already locked and signed
20
+ * out) and who to unlock (active again, and locked by us, not by bad
21
+ * passwords). Everyone else is left alone.
22
+ */ export function syncPlan(users, lists) {
23
+ const lower = (e)=>(e ?? '').toLowerCase();
24
+ const locked = new Set(lists.locked.map(lower));
25
+ const active = new Set(lists.active.map(lower));
26
+ return {
27
+ lock: users.filter((u)=>locked.has(lower(u.email)) && (!isHubLocked(u.lockUntil) || !!u.sessions?.length)),
28
+ unlock: users.filter((u)=>!locked.has(lower(u.email)) && active.has(lower(u.email)) && isHubLocked(u.lockUntil))
29
+ };
30
+ }
31
+ /** The auth collection people sign in to the admin with. */ const authConfig = (payload)=>{
32
+ const slug = payload.config.admin.user;
33
+ const collection = payload.collections[slug];
34
+ if (!collection) throw new Error(`no "${slug}" collection`);
35
+ return collection.config;
36
+ };
37
+ const canLock = (config)=>config.auth.maxLoginAttempts > 0;
38
+ /** Locks with the sentinel and signs them out everywhere. */ async function lockUser(payload, id) {
39
+ const config = authConfig(payload);
40
+ if (!canLock(config)) return;
41
+ // The whole row, as Payload's own session writes do: on Postgres, clearing
42
+ // the sessions array upserts the row, so every NOT NULL column must be there.
43
+ const doc = await payload.db.findOne({
44
+ collection: config.slug,
45
+ where: {
46
+ id: {
47
+ equals: id
48
+ }
49
+ }
50
+ });
51
+ if (!doc) return;
52
+ await payload.db.updateOne({
53
+ collection: config.slug,
54
+ id,
55
+ data: {
56
+ ...doc,
57
+ lockUntil: LOCK_SENTINEL,
58
+ ...config.auth.useSessions ? {
59
+ sessions: []
60
+ } : {}
61
+ },
62
+ returning: false
63
+ });
64
+ }
65
+ async function unlockUser(payload, id, req) {
66
+ await payload.db.updateOne({
67
+ collection: authConfig(payload).slug,
68
+ id,
69
+ data: {
70
+ lockUntil: null,
71
+ loginAttempts: 0
72
+ },
73
+ req,
74
+ returning: false
75
+ });
76
+ }
77
+ let warnedNoLock = false;
78
+ /**
79
+ * Sends the Hub this site's user emails, gets back which are staff to lock or
80
+ * unlock, and applies that. Never throws; false when it couldn't.
81
+ */ export async function syncStaff(payload, settings) {
82
+ try {
83
+ const config = authConfig(payload);
84
+ if (!canLock(config)) {
85
+ if (!warnedNoLock) payload.logger.warn(`[hub-plugin] "${config.slug}" has maxLoginAttempts: 0, so it has no lockUntil and staff the Hub offboards can't be locked here (password logins are still refused).`);
86
+ warnedNoLock = true;
87
+ return false;
88
+ }
89
+ // Ask only about people this site has, a page at a time.
90
+ const lists = {
91
+ active: [],
92
+ locked: []
93
+ };
94
+ for(let page = 1;; page++){
95
+ const { docs, hasNextPage } = await payload.find({
96
+ collection: config.slug,
97
+ depth: 0,
98
+ limit: STAFF_BATCH,
99
+ overrideAccess: true,
100
+ page,
101
+ select: {
102
+ email: true
103
+ },
104
+ sort: 'id'
105
+ });
106
+ const emails = docs.flatMap((d)=>d.email ? [
107
+ d.email.toLowerCase()
108
+ ] : []);
109
+ const got = emails.length ? await fetchStaff(settings, emails) : lists;
110
+ if (!got) {
111
+ payload.logger.warn('[hub-plugin] Couldn’t fetch the staff lists from the Foundry Hub.');
112
+ return false;
113
+ }
114
+ if (got !== lists) {
115
+ lists.active.push(...got.active);
116
+ lists.locked.push(...got.locked);
117
+ }
118
+ if (!hasNextPage) break;
119
+ }
120
+ const emails = [
121
+ ...lists.locked,
122
+ ...lists.active
123
+ ];
124
+ if (!emails.length) return true;
125
+ const { docs } = await payload.find({
126
+ collection: config.slug,
127
+ depth: 0,
128
+ overrideAccess: true,
129
+ pagination: false,
130
+ showHiddenFields: true,
131
+ where: {
132
+ email: {
133
+ in: emails
134
+ }
135
+ }
136
+ });
137
+ const plan = syncPlan(docs, lists);
138
+ for (const u of plan.lock)await lockUser(payload, u.id);
139
+ for (const u of plan.unlock)await unlockUser(payload, u.id);
140
+ if (plan.lock.length || plan.unlock.length) payload.logger.info(`[hub-plugin] Staff sync: locked ${plan.lock.length}, unlocked ${plan.unlock.length}.`);
141
+ return true;
142
+ } catch (err) {
143
+ payload.logger.error({
144
+ err,
145
+ msg: '[hub-plugin] Staff sync failed.'
146
+ });
147
+ return false;
148
+ }
149
+ }
150
+ /** Refuses a password login (or a reset's sign-in) for someone the Hub has offboarded. Fails open. */ export const hubLockHook = (settings)=>async ({ req, user })=>{
151
+ const s = settings();
152
+ const email = user.email;
153
+ if (!s || !email) return user;
154
+ if (await fetchStaffStatus(s, email) !== 'locked') return user;
155
+ // Not awaited: the login's transaction rolls back anything written with
156
+ // it, and a write outside it waits for that rollback.
157
+ void lockUser(req.payload, user.id).catch((err)=>req.payload.logger.error({
158
+ err,
159
+ msg: '[hub-plugin] Couldn’t lock user.'
160
+ }));
161
+ throw new LockedAuth(req.t);
162
+ };
163
+ /** Same steps as Payload's login operation, with an 8-hour token and session. */ async function signIn(req, user) {
164
+ const { payload } = req;
165
+ const base = authConfig(payload);
166
+ const collectionConfig = {
167
+ ...base,
168
+ auth: {
169
+ ...base.auth,
170
+ tokenExpiration: SESSION_SECONDS
171
+ }
172
+ };
173
+ const doc = {
174
+ ...user,
175
+ collection: base.slug,
176
+ _strategy: 'local-jwt'
177
+ };
178
+ const { sid } = await addSessionToUser({
179
+ collectionConfig,
180
+ payload,
181
+ req,
182
+ user: doc
183
+ });
184
+ const fieldsToSign = getFieldsToSign({
185
+ collectionConfig,
186
+ email: user.email,
187
+ user: doc,
188
+ ...sid ? {
189
+ sid
190
+ } : {}
191
+ });
192
+ const { token } = await jwtSign({
193
+ fieldsToSign,
194
+ secret: payload.secret,
195
+ tokenExpiration: SESSION_SECONDS
196
+ });
197
+ return generatePayloadCookie({
198
+ collectionAuthConfig: collectionConfig.auth,
199
+ cookiePrefix: payload.config.cookiePrefix,
200
+ token
201
+ });
202
+ }
203
+ /** A new CMS user for this person, with the matching permissions-plugin role if there is one. */ async function createUser(req, who) {
204
+ const { payload } = req;
205
+ const config = authConfig(payload);
206
+ const has = (name)=>config.flattenedFields.find((f)=>f.name === name);
207
+ const data = {
208
+ email: who.email,
209
+ // Unusable: they can still choose one with forgot-password.
210
+ password: randomBytes(32).toString('base64url')
211
+ };
212
+ if (has('name')?.type === 'text' && who.name) data.name = who.name;
213
+ if (config.auth.verify) data._verified = true;
214
+ const role = has('role');
215
+ if (role?.type === 'relationship' && role.relationTo === 'roles') {
216
+ const name = payloadRoleName(who.role);
217
+ const { docs } = await payload.find({
218
+ collection: 'roles',
219
+ depth: 0,
220
+ limit: 1,
221
+ overrideAccess: true,
222
+ req,
223
+ where: {
224
+ name: {
225
+ equals: name
226
+ }
227
+ }
228
+ });
229
+ if (docs[0]) data.role = docs[0].id;
230
+ else payload.logger.warn(`[hub-plugin] No "${name}" role, so ${who.email} was created without one.`);
231
+ }
232
+ return await payload.create({
233
+ collection: config.slug,
234
+ data: data,
235
+ depth: 0,
236
+ disableVerificationEmail: true,
237
+ overrideAccess: true,
238
+ req,
239
+ showHiddenFields: true
240
+ });
241
+ }
242
+ /** Only ever the site's own admin path: never a full or protocol-relative URL. */ const adminPath = (payload)=>{
243
+ const route = payload.config.routes.admin;
244
+ return /^\/(?!\/)/.test(route) ? route : '/admin';
245
+ };
246
+ const redirect = (location, cookie)=>new Response(null, {
247
+ status: 302,
248
+ headers: {
249
+ location,
250
+ 'cache-control': 'no-store',
251
+ 'referrer-policy': 'no-referrer',
252
+ ...cookie ? {
253
+ 'set-cookie': cookie
254
+ } : {}
255
+ }
256
+ });
257
+ export function adminEndpoints(settings) {
258
+ let lastSync = 0;
259
+ return [
260
+ {
261
+ path: '/hub/login',
262
+ method: 'get',
263
+ handler: async (req)=>{
264
+ const admin = adminPath(req.payload);
265
+ const fail = (reason)=>redirect(`${admin}/login?hub=${reason}`);
266
+ const s = settings();
267
+ if (!s) return fail('not-configured');
268
+ const ticket = req.searchParams.get('ticket');
269
+ if (!ticket) return fail('invalid');
270
+ const who = await redeemTicket(s, ticket);
271
+ if (!who) return fail('expired');
272
+ try {
273
+ const { docs } = await req.payload.find({
274
+ collection: authConfig(req.payload).slug,
275
+ depth: 0,
276
+ limit: 1,
277
+ overrideAccess: true,
278
+ req,
279
+ showHiddenFields: true,
280
+ where: {
281
+ email: {
282
+ equals: who.email
283
+ }
284
+ }
285
+ });
286
+ let user = docs[0];
287
+ if (!user) user = await createUser(req, who);
288
+ else if (isHubLocked(user.lockUntil)) {
289
+ await unlockUser(req.payload, user.id, req);
290
+ // signIn writes the whole doc back when it adds the session.
291
+ user = {
292
+ ...user,
293
+ lockUntil: null,
294
+ loginAttempts: 0
295
+ };
296
+ }
297
+ return redirect(admin, await signIn(req, user));
298
+ } catch (err) {
299
+ req.payload.logger.error({
300
+ err,
301
+ msg: '[hub-plugin] One-click sign-in failed.'
302
+ });
303
+ return fail('failed');
304
+ }
305
+ }
306
+ },
307
+ {
308
+ path: '/hub/sync',
309
+ method: 'post',
310
+ // No input and no trust: it only makes the site pull from the Hub with its own key.
311
+ handler: async (req)=>{
312
+ const s = settings();
313
+ if (!s) return Response.json({
314
+ ok: false
315
+ }, {
316
+ status: 503
317
+ });
318
+ if (Date.now() - lastSync < SYNC_INTERVAL_MS) return Response.json({
319
+ ok: true,
320
+ skipped: true
321
+ }, {
322
+ status: 202
323
+ });
324
+ lastSync = Date.now();
325
+ const ok = await syncStaff(req.payload, s);
326
+ return Response.json({
327
+ ok
328
+ }, {
329
+ status: ok ? 200 : 502
330
+ });
331
+ }
332
+ }
333
+ ];
334
+ }
335
+
336
+ //# sourceMappingURL=admin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/admin.ts"],"sourcesContent":["/**\n * One-click admin and staff offboarding. The Hub mints a ticket, /api/hub/login\n * redeems it and signs the person in for 8 hours; /api/hub/sync and boot ask\n * the Hub about this site's users and lock or unlock Umi staff accounts.\n */\nimport { randomBytes } from 'node:crypto';\nimport {\n type CollectionBeforeLoginHook,\n type CollectionSlug,\n type Endpoint,\n getFieldsToSign,\n jwtSign,\n LockedAuth,\n type Payload,\n type PayloadRequest,\n type SanitizedCollectionConfig,\n} from 'payload';\nimport { addSessionToUser, generatePayloadCookie } from 'payload/shared';\nimport {\n type AdminLogin,\n fetchStaff,\n fetchStaffStatus,\n type HubSettings,\n redeemTicket,\n STAFF_BATCH,\n type StaffLists,\n} from './hub.js';\n\n/** `lockUntil` for accounts the Hub locked: far enough away that only a sync unlocks it. */\nexport const LOCK_SENTINEL = '9999-12-31T00:00:00.000Z';\n/** One-click sessions last 8 hours. */\nexport const SESSION_SECONDS = 8 * 60 * 60;\n/** /api/hub/sync ignores calls closer together than this. */\nexport const SYNC_INTERVAL_MS = 10_000;\n\nexport const payloadRoleName = (role: AdminLogin['role']) =>\n role === 'admin' ? 'Admin' : 'Editor';\n\nexport function isHubLocked(lockUntil: unknown): boolean {\n if (!lockUntil) return false;\n const d = new Date(lockUntil as string);\n return !Number.isNaN(d.getTime()) && d.toISOString() === LOCK_SENTINEL;\n}\n\ntype UserDoc = {\n id: number | string;\n email?: string | null;\n lockUntil?: unknown;\n loginAttempts?: number | null;\n sessions?: unknown[] | null;\n};\n\n/**\n * Who to lock (on the Hub's locked list and not already locked and signed\n * out) and who to unlock (active again, and locked by us, not by bad\n * passwords). Everyone else is left alone.\n */\nexport function syncPlan(users: UserDoc[], lists: StaffLists) {\n const lower = (e?: string | null) => (e ?? '').toLowerCase();\n const locked = new Set(lists.locked.map(lower));\n const active = new Set(lists.active.map(lower));\n return {\n lock: users.filter(\n u =>\n locked.has(lower(u.email)) &&\n (!isHubLocked(u.lockUntil) || !!u.sessions?.length)\n ),\n unlock: users.filter(\n u =>\n !locked.has(lower(u.email)) &&\n active.has(lower(u.email)) &&\n isHubLocked(u.lockUntil)\n ),\n };\n}\n\n/** The auth collection people sign in to the admin with. */\nconst authConfig = (payload: Payload): SanitizedCollectionConfig => {\n const slug = payload.config.admin.user;\n const collection = payload.collections[slug as CollectionSlug];\n if (!collection) throw new Error(`no \"${slug}\" collection`);\n return collection.config;\n};\n\nconst canLock = (config: SanitizedCollectionConfig) =>\n config.auth.maxLoginAttempts > 0;\n\n/** Locks with the sentinel and signs them out everywhere. */\nasync function lockUser(payload: Payload, id: UserDoc['id']) {\n const config = authConfig(payload);\n if (!canLock(config)) return;\n // The whole row, as Payload's own session writes do: on Postgres, clearing\n // the sessions array upserts the row, so every NOT NULL column must be there.\n const doc = await payload.db.findOne<UserDoc>({\n collection: config.slug,\n where: { id: { equals: id } },\n });\n if (!doc) return;\n await payload.db.updateOne({\n collection: config.slug,\n id,\n data: {\n ...doc,\n lockUntil: LOCK_SENTINEL,\n ...(config.auth.useSessions ? { sessions: [] } : {}),\n },\n returning: false,\n });\n}\n\nasync function unlockUser(\n payload: Payload,\n id: UserDoc['id'],\n req?: PayloadRequest\n) {\n await payload.db.updateOne({\n collection: authConfig(payload).slug,\n id,\n data: { lockUntil: null, loginAttempts: 0 },\n req,\n returning: false,\n });\n}\n\nlet warnedNoLock = false;\n\n/**\n * Sends the Hub this site's user emails, gets back which are staff to lock or\n * unlock, and applies that. Never throws; false when it couldn't.\n */\nexport async function syncStaff(\n payload: Payload,\n settings: HubSettings\n): Promise<boolean> {\n try {\n const config = authConfig(payload);\n if (!canLock(config)) {\n if (!warnedNoLock)\n payload.logger.warn(\n `[hub-plugin] \"${config.slug}\" has maxLoginAttempts: 0, so it has no lockUntil and staff the Hub offboards can't be locked here (password logins are still refused).`\n );\n warnedNoLock = true;\n return false;\n }\n // Ask only about people this site has, a page at a time.\n const lists: StaffLists = { active: [], locked: [] };\n for (let page = 1; ; page++) {\n const { docs, hasNextPage } = await payload.find({\n collection: config.slug as CollectionSlug,\n depth: 0,\n limit: STAFF_BATCH,\n overrideAccess: true,\n page,\n select: { email: true },\n sort: 'id',\n });\n const emails = (docs as unknown as UserDoc[]).flatMap(d =>\n d.email ? [d.email.toLowerCase()] : []\n );\n const got = emails.length ? await fetchStaff(settings, emails) : lists;\n if (!got) {\n payload.logger.warn(\n '[hub-plugin] Couldn’t fetch the staff lists from the Foundry Hub.'\n );\n return false;\n }\n if (got !== lists) {\n lists.active.push(...got.active);\n lists.locked.push(...got.locked);\n }\n if (!hasNextPage) break;\n }\n const emails = [...lists.locked, ...lists.active];\n if (!emails.length) return true;\n const { docs } = await payload.find({\n collection: config.slug as CollectionSlug,\n depth: 0,\n overrideAccess: true,\n pagination: false,\n showHiddenFields: true,\n where: { email: { in: emails } },\n });\n const plan = syncPlan(docs as unknown as UserDoc[], lists);\n for (const u of plan.lock) await lockUser(payload, u.id);\n for (const u of plan.unlock) await unlockUser(payload, u.id);\n if (plan.lock.length || plan.unlock.length)\n payload.logger.info(\n `[hub-plugin] Staff sync: locked ${plan.lock.length}, unlocked ${plan.unlock.length}.`\n );\n return true;\n } catch (err) {\n payload.logger.error({ err, msg: '[hub-plugin] Staff sync failed.' });\n return false;\n }\n}\n\n/** Refuses a password login (or a reset's sign-in) for someone the Hub has offboarded. Fails open. */\nexport const hubLockHook =\n (settings: () => HubSettings | null): CollectionBeforeLoginHook =>\n async ({ req, user }) => {\n const s = settings();\n const email = (user as UserDoc).email;\n if (!s || !email) return user;\n if ((await fetchStaffStatus(s, email)) !== 'locked') return user;\n // Not awaited: the login's transaction rolls back anything written with\n // it, and a write outside it waits for that rollback.\n void lockUser(req.payload, (user as UserDoc).id).catch(err =>\n req.payload.logger.error({ err, msg: '[hub-plugin] Couldn’t lock user.' })\n );\n throw new LockedAuth(req.t);\n };\n\n/** Same steps as Payload's login operation, with an 8-hour token and session. */\nasync function signIn(req: PayloadRequest, user: UserDoc & { email: string }) {\n const { payload } = req;\n const base = authConfig(payload);\n const collectionConfig = {\n ...base,\n auth: { ...base.auth, tokenExpiration: SESSION_SECONDS },\n };\n const doc = { ...user, collection: base.slug, _strategy: 'local-jwt' };\n const { sid } = await addSessionToUser({\n collectionConfig,\n payload,\n req,\n user: doc as never,\n });\n const fieldsToSign = getFieldsToSign({\n collectionConfig,\n email: user.email,\n user: doc as never,\n ...(sid ? { sid } : {}),\n });\n const { token } = await jwtSign({\n fieldsToSign,\n secret: payload.secret,\n tokenExpiration: SESSION_SECONDS,\n });\n return generatePayloadCookie({\n collectionAuthConfig: collectionConfig.auth,\n cookiePrefix: payload.config.cookiePrefix,\n token,\n });\n}\n\n/** A new CMS user for this person, with the matching permissions-plugin role if there is one. */\nasync function createUser(req: PayloadRequest, who: AdminLogin) {\n const { payload } = req;\n const config = authConfig(payload);\n const has = (name: string) =>\n config.flattenedFields.find(f => f.name === name);\n const data: Record<string, unknown> = {\n email: who.email,\n // Unusable: they can still choose one with forgot-password.\n password: randomBytes(32).toString('base64url'),\n };\n if (has('name')?.type === 'text' && who.name) data.name = who.name;\n if (config.auth.verify) data._verified = true;\n const role = has('role');\n if (role?.type === 'relationship' && role.relationTo === 'roles') {\n const name = payloadRoleName(who.role);\n const { docs } = await payload.find({\n collection: 'roles' as CollectionSlug,\n depth: 0,\n limit: 1,\n overrideAccess: true,\n req,\n where: { name: { equals: name } },\n });\n if (docs[0]) data.role = docs[0].id;\n else\n payload.logger.warn(\n `[hub-plugin] No \"${name}\" role, so ${who.email} was created without one.`\n );\n }\n return (await payload.create({\n collection: config.slug as CollectionSlug,\n data: data as never,\n depth: 0,\n disableVerificationEmail: true,\n overrideAccess: true,\n req,\n showHiddenFields: true,\n })) as unknown as UserDoc & { email: string };\n}\n\n/** Only ever the site's own admin path: never a full or protocol-relative URL. */\nconst adminPath = (payload: Payload) => {\n const route = payload.config.routes.admin;\n return /^\\/(?!\\/)/.test(route) ? route : '/admin';\n};\n\nconst redirect = (location: string, cookie?: string) =>\n new Response(null, {\n status: 302,\n headers: {\n location,\n 'cache-control': 'no-store',\n 'referrer-policy': 'no-referrer',\n ...(cookie ? { 'set-cookie': cookie } : {}),\n },\n });\n\nexport function adminEndpoints(settings: () => HubSettings | null): Endpoint[] {\n let lastSync = 0;\n return [\n {\n path: '/hub/login',\n method: 'get',\n handler: async req => {\n const admin = adminPath(req.payload);\n const fail = (reason: string) =>\n redirect(`${admin}/login?hub=${reason}`);\n const s = settings();\n if (!s) return fail('not-configured');\n const ticket = req.searchParams.get('ticket');\n if (!ticket) return fail('invalid');\n const who = await redeemTicket(s, ticket);\n if (!who) return fail('expired');\n try {\n const { docs } = await req.payload.find({\n collection: authConfig(req.payload).slug as CollectionSlug,\n depth: 0,\n limit: 1,\n overrideAccess: true,\n req,\n showHiddenFields: true,\n where: { email: { equals: who.email } },\n });\n let user = docs[0] as unknown as\n | (UserDoc & { email: string })\n | undefined;\n if (!user) user = await createUser(req, who);\n // The Hub has just confirmed they're active staff.\n else if (isHubLocked(user.lockUntil)) {\n await unlockUser(req.payload, user.id, req);\n // signIn writes the whole doc back when it adds the session.\n user = { ...user, lockUntil: null, loginAttempts: 0 };\n }\n return redirect(admin, await signIn(req, user));\n } catch (err) {\n req.payload.logger.error({\n err,\n msg: '[hub-plugin] One-click sign-in failed.',\n });\n return fail('failed');\n }\n },\n },\n {\n path: '/hub/sync',\n method: 'post',\n // No input and no trust: it only makes the site pull from the Hub with its own key.\n handler: async req => {\n const s = settings();\n if (!s) return Response.json({ ok: false }, { status: 503 });\n if (Date.now() - lastSync < SYNC_INTERVAL_MS)\n return Response.json({ ok: true, skipped: true }, { status: 202 });\n lastSync = Date.now();\n const ok = await syncStaff(req.payload, s);\n return Response.json({ ok }, { status: ok ? 200 : 502 });\n },\n },\n ];\n}\n"],"names":["randomBytes","getFieldsToSign","jwtSign","LockedAuth","addSessionToUser","generatePayloadCookie","fetchStaff","fetchStaffStatus","redeemTicket","STAFF_BATCH","LOCK_SENTINEL","SESSION_SECONDS","SYNC_INTERVAL_MS","payloadRoleName","role","isHubLocked","lockUntil","d","Date","Number","isNaN","getTime","toISOString","syncPlan","users","lists","lower","e","toLowerCase","locked","Set","map","active","lock","filter","u","has","email","sessions","length","unlock","authConfig","payload","slug","config","admin","user","collection","collections","Error","canLock","auth","maxLoginAttempts","lockUser","id","doc","db","findOne","where","equals","updateOne","data","useSessions","returning","unlockUser","req","loginAttempts","warnedNoLock","syncStaff","settings","logger","warn","page","docs","hasNextPage","find","depth","limit","overrideAccess","select","sort","emails","flatMap","got","push","pagination","showHiddenFields","in","plan","info","err","error","msg","hubLockHook","s","catch","t","signIn","base","collectionConfig","tokenExpiration","_strategy","sid","fieldsToSign","token","secret","collectionAuthConfig","cookiePrefix","createUser","who","name","flattenedFields","f","password","toString","type","verify","_verified","relationTo","create","disableVerificationEmail","adminPath","route","routes","test","redirect","location","cookie","Response","status","headers","adminEndpoints","lastSync","path","method","handler","fail","reason","ticket","searchParams","get","json","ok","now","skipped"],"mappings":"AAAA;;;;CAIC,GACD,SAASA,WAAW,QAAQ,cAAc;AAC1C,SAIEC,eAAe,EACfC,OAAO,EACPC,UAAU,QAIL,UAAU;AACjB,SAASC,gBAAgB,EAAEC,qBAAqB,QAAQ,iBAAiB;AACzE,SAEEC,UAAU,EACVC,gBAAgB,EAEhBC,YAAY,EACZC,WAAW,QAEN,WAAW;AAElB,0FAA0F,GAC1F,OAAO,MAAMC,gBAAgB,2BAA2B;AACxD,qCAAqC,GACrC,OAAO,MAAMC,kBAAkB,IAAI,KAAK,GAAG;AAC3C,2DAA2D,GA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,WAAWlH,KAAK6H,GAAG;gBACnB,MAAMD,KAAK,MAAM1E,UAAUH,IAAIvB,OAAO,EAAEoD;gBACxC,OAAOkC,SAASa,IAAI,CAAC;oBAAEC;gBAAG,GAAG;oBAAEb,QAAQa,KAAK,MAAM;gBAAI;YACxD;QACF;KACD;AACH"}
package/dist/hub.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ /** Calls to the Foundry Hub with this site's key. Never throw: null means "no answer". */
2
+ export type HubSettings = {
3
+ hubUrl: string;
4
+ key: string;
5
+ environment: string;
6
+ };
7
+ export type StaffLists = {
8
+ active: string[];
9
+ locked: string[];
10
+ };
11
+ export type StaffStatus = 'active' | 'locked' | 'unknown';
12
+ export type AdminLogin = {
13
+ email: string;
14
+ name: string;
15
+ role: 'admin' | 'editor';
16
+ };
17
+ type Fetch = (url: string, init?: RequestInit) => Promise<Response>;
18
+ /** Redeems a one-click ticket: who to sign in, or null. */
19
+ export declare function redeemTicket(s: HubSettings, ticket: string, fetchImpl?: Fetch): Promise<AdminLogin | null>;
20
+ /** Most emails the Hub takes in one staff request. */
21
+ export declare const STAFF_BATCH = 2000;
22
+ /**
23
+ * Of these emails (at most STAFF_BATCH, the site's own users), which the Hub
24
+ * wants unlocked (`active`) or locked. The Hub never sends anyone else.
25
+ */
26
+ export declare function fetchStaff(s: HubSettings, emails: string[], fetchImpl?: Fetch): Promise<StaffLists | null>;
27
+ /** One email's status, waiting 2 s at most (it sits in front of a password login). */
28
+ export declare function fetchStaffStatus(s: HubSettings, email: string, fetchImpl?: Fetch): Promise<StaffStatus | null>;
29
+ export {};
package/dist/hub.js ADDED
@@ -0,0 +1,55 @@
1
+ /** Calls to the Foundry Hub with this site's key. Never throw: null means "no answer". */ async function call(s, path, timeout, init = {}, fetchImpl = fetch) {
2
+ try {
3
+ const res = await fetchImpl(`${s.hubUrl.replace(/\/$/, '')}${path}`, {
4
+ ...init,
5
+ headers: {
6
+ authorization: `Bearer ${s.key}`,
7
+ 'content-type': 'application/json'
8
+ },
9
+ signal: AbortSignal.timeout(timeout),
10
+ redirect: 'manual'
11
+ });
12
+ return res.ok ? await res.json() : null;
13
+ } catch {
14
+ return null;
15
+ }
16
+ }
17
+ const isEmails = (v)=>Array.isArray(v) && v.every((e)=>typeof e === 'string');
18
+ /** Redeems a one-click ticket: who to sign in, or null. */ export async function redeemTicket(s, ticket, fetchImpl) {
19
+ const body = await call(s, '/api/sites/admin-login', 3000, {
20
+ method: 'POST',
21
+ body: JSON.stringify({
22
+ ticket,
23
+ environment: s.environment
24
+ })
25
+ }, fetchImpl);
26
+ if (typeof body?.email !== 'string' || body.role !== 'admin' && body.role !== 'editor') return null;
27
+ return {
28
+ email: body.email.toLowerCase(),
29
+ name: typeof body.name === 'string' ? body.name : '',
30
+ role: body.role
31
+ };
32
+ }
33
+ /** Most emails the Hub takes in one staff request. */ export const STAFF_BATCH = 2000;
34
+ /**
35
+ * Of these emails (at most STAFF_BATCH, the site's own users), which the Hub
36
+ * wants unlocked (`active`) or locked. The Hub never sends anyone else.
37
+ */ export async function fetchStaff(s, emails, fetchImpl) {
38
+ const body = await call(s, '/api/sites/staff', 3000, {
39
+ method: 'POST',
40
+ body: JSON.stringify({
41
+ emails
42
+ })
43
+ }, fetchImpl);
44
+ return isEmails(body?.active) && isEmails(body?.locked) ? {
45
+ active: body.active,
46
+ locked: body.locked
47
+ } : null;
48
+ }
49
+ /** One email's status, waiting 2 s at most (it sits in front of a password login). */ export async function fetchStaffStatus(s, email, fetchImpl) {
50
+ const body = await call(s, `/api/sites/staff?email=${encodeURIComponent(email)}`, 2000, {}, fetchImpl);
51
+ const status = body?.status;
52
+ return status === 'active' || status === 'locked' || status === 'unknown' ? status : null;
53
+ }
54
+
55
+ //# sourceMappingURL=hub.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hub.ts"],"sourcesContent":["/** Calls to the Foundry Hub with this site's key. Never throw: null means \"no answer\". */\n\nexport type HubSettings = { hubUrl: string; key: string; environment: string };\nexport type StaffLists = { active: string[]; locked: string[] };\nexport type StaffStatus = 'active' | 'locked' | 'unknown';\nexport type AdminLogin = {\n email: string;\n name: string;\n role: 'admin' | 'editor';\n};\n\ntype Fetch = (url: string, init?: RequestInit) => Promise<Response>;\n\nasync function call(\n s: HubSettings,\n path: string,\n timeout: number,\n init: RequestInit = {},\n fetchImpl: Fetch = fetch\n): Promise<unknown> {\n try {\n const res = await fetchImpl(`${s.hubUrl.replace(/\\/$/, '')}${path}`, {\n ...init,\n headers: {\n authorization: `Bearer ${s.key}`,\n 'content-type': 'application/json',\n },\n signal: AbortSignal.timeout(timeout),\n redirect: 'manual',\n });\n return res.ok ? await res.json() : null;\n } catch {\n return null;\n }\n}\n\nconst isEmails = (v: unknown): v is string[] =>\n Array.isArray(v) && v.every(e => typeof e === 'string');\n\n/** Redeems a one-click ticket: who to sign in, or null. */\nexport async function redeemTicket(\n s: HubSettings,\n ticket: string,\n fetchImpl?: Fetch\n): Promise<AdminLogin | null> {\n const body = (await call(\n s,\n '/api/sites/admin-login',\n 3000,\n {\n method: 'POST',\n body: JSON.stringify({ ticket, environment: s.environment }),\n },\n fetchImpl\n )) as Partial<AdminLogin> | null;\n if (\n typeof body?.email !== 'string' ||\n (body.role !== 'admin' && body.role !== 'editor')\n )\n return null;\n return {\n email: body.email.toLowerCase(),\n name: typeof body.name === 'string' ? body.name : '',\n role: body.role,\n };\n}\n\n/** Most emails the Hub takes in one staff request. */\nexport const STAFF_BATCH = 2000;\n\n/**\n * Of these emails (at most STAFF_BATCH, the site's own users), which the Hub\n * wants unlocked (`active`) or locked. The Hub never sends anyone else.\n */\nexport async function fetchStaff(\n s: HubSettings,\n emails: string[],\n fetchImpl?: Fetch\n): Promise<StaffLists | null> {\n const body = (await call(\n s,\n '/api/sites/staff',\n 3000,\n { method: 'POST', body: JSON.stringify({ emails }) },\n fetchImpl\n )) as Partial<StaffLists> | null;\n return isEmails(body?.active) && isEmails(body?.locked)\n ? { active: body.active, locked: body.locked }\n : null;\n}\n\n/** One email's status, waiting 2 s at most (it sits in front of a password login). */\nexport async function fetchStaffStatus(\n s: HubSettings,\n email: string,\n fetchImpl?: Fetch\n): Promise<StaffStatus | null> {\n const body = (await call(\n s,\n `/api/sites/staff?email=${encodeURIComponent(email)}`,\n 2000,\n {},\n fetchImpl\n )) as { status?: unknown } | null;\n const status = body?.status;\n return status === 'active' || status === 'locked' || status === 'unknown'\n ? status\n : null;\n}\n"],"names":["call","s","path","timeout","init","fetchImpl","fetch","res","hubUrl","replace","headers","authorization","key","signal","AbortSignal","redirect","ok","json","isEmails","v","Array","isArray","every","e","redeemTicket","ticket","body","method","JSON","stringify","environment","email","role","toLowerCase","name","STAFF_BATCH","fetchStaff","emails","active","locked","fetchStaffStatus","encodeURIComponent","status"],"mappings":"AAAA,wFAAwF,GAaxF,eAAeA,KACbC,CAAc,EACdC,IAAY,EACZC,OAAe,EACfC,OAAoB,CAAC,CAAC,EACtBC,YAAmBC,KAAK;IAExB,IAAI;QACF,MAAMC,MAAM,MAAMF,UAAU,GAAGJ,EAAEO,MAAM,CAACC,OAAO,CAAC,OAAO,MAAMP,MAAM,EAAE;YACnE,GAAGE,IAAI;YACPM,SAAS;gBACPC,eAAe,CAAC,OAAO,EAAEV,EAAEW,GAAG,EAAE;gBAChC,gBAAgB;YAClB;YACAC,QAAQC,YAAYX,OAAO,CAACA;YAC5BY,UAAU;QACZ;QACA,OAAOR,IAAIS,EAAE,GAAG,MAAMT,IAAIU,IAAI,KAAK;IACrC,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEA,MAAMC,WAAW,CAACC,IAChBC,MAAMC,OAAO,CAACF,MAAMA,EAAEG,KAAK,CAACC,CAAAA,IAAK,OAAOA,MAAM;AAEhD,yDAAyD,GACzD,OAAO,eAAeC,aACpBvB,CAAc,EACdwB,MAAc,EACdpB,SAAiB;IAEjB,MAAMqB,OAAQ,MAAM1B,KAClBC,GACA,0BACA,MACA;QACE0B,QAAQ;QACRD,MAAME,KAAKC,SAAS,CAAC;YAAEJ;YAAQK,aAAa7B,EAAE6B,WAAW;QAAC;IAC5D,GACAzB;IAEF,IACE,OAAOqB,MAAMK,UAAU,YACtBL,KAAKM,IAAI,KAAK,WAAWN,KAAKM,IAAI,KAAK,UAExC,OAAO;IACT,OAAO;QACLD,OAAOL,KAAKK,KAAK,CAACE,WAAW;QAC7BC,MAAM,OAAOR,KAAKQ,IAAI,KAAK,WAAWR,KAAKQ,IAAI,GAAG;QAClDF,MAAMN,KAAKM,IAAI;IACjB;AACF;AAEA,oDAAoD,GACpD,OAAO,MAAMG,cAAc,KAAK;AAEhC;;;CAGC,GACD,OAAO,eAAeC,WACpBnC,CAAc,EACdoC,MAAgB,EAChBhC,SAAiB;IAEjB,MAAMqB,OAAQ,MAAM1B,KAClBC,GACA,oBACA,MACA;QAAE0B,QAAQ;QAAQD,MAAME,KAAKC,SAAS,CAAC;YAAEQ;QAAO;IAAG,GACnDhC;IAEF,OAAOa,SAASQ,MAAMY,WAAWpB,SAASQ,MAAMa,UAC5C;QAAED,QAAQZ,KAAKY,MAAM;QAAEC,QAAQb,KAAKa,MAAM;IAAC,IAC3C;AACN;AAEA,oFAAoF,GACpF,OAAO,eAAeC,iBACpBvC,CAAc,EACd8B,KAAa,EACb1B,SAAiB;IAEjB,MAAMqB,OAAQ,MAAM1B,KAClBC,GACA,CAAC,uBAAuB,EAAEwC,mBAAmBV,QAAQ,EACrD,MACA,CAAC,GACD1B;IAEF,MAAMqC,SAAShB,MAAMgB;IACrB,OAAOA,WAAW,YAAYA,WAAW,YAAYA,WAAW,YAC5DA,SACA;AACN"}
package/dist/index.js CHANGED
@@ -1,7 +1,17 @@
1
1
  import { recordActivePlugin } from './activePlugins.js';
2
+ import { adminEndpoints, hubLockHook, syncStaff } from './admin.js';
2
3
  import { buildReport, resolveEnvironment, sendReport } from './report.js';
4
+ /** The Hub's address, this site's key and environment; null when any is missing. */ const settingsFrom = (options)=>{
5
+ const hubUrl = options.hubUrl ?? process.env.FOUNDRY_HUB_URL;
6
+ const key = options.key ?? process.env.FOUNDRY_HUB_KEY;
7
+ const environment = resolveEnvironment(process.env, options.environment);
8
+ return hubUrl && key && environment ? {
9
+ hubUrl,
10
+ key,
11
+ environment
12
+ } : null;
13
+ };
3
14
  /** Reports what the site is running, once per start. Never holds up or breaks boot. */ async function report(payload, options) {
4
- if (process.env.NEXT_PHASE === 'phase-production-build') return;
5
15
  const hubUrl = options.hubUrl ?? process.env.FOUNDRY_HUB_URL;
6
16
  const key = options.key ?? process.env.FOUNDRY_HUB_KEY;
7
17
  if (!hubUrl || !key) {
@@ -24,11 +34,33 @@ export const hubPlugin = (options = {})=>(incoming)=>{
24
34
  if (options.enabled === false) return incoming;
25
35
  const config = recordActivePlugin(incoming, '@foundrykit/hub-plugin');
26
36
  const previous = config.onInit;
37
+ const settings = ()=>settingsFrom(options);
38
+ // Payload's default: the first collection with auth.
39
+ const authSlug = config.admin?.user ?? config.collections?.find((c)=>c.auth)?.slug;
27
40
  return {
28
41
  ...config,
42
+ collections: config.collections?.map((c)=>c.slug === authSlug ? {
43
+ ...c,
44
+ hooks: {
45
+ ...c.hooks,
46
+ beforeLogin: [
47
+ ...c.hooks?.beforeLogin ?? [],
48
+ hubLockHook(settings)
49
+ ]
50
+ }
51
+ } : c),
52
+ endpoints: [
53
+ ...config.endpoints ?? [],
54
+ ...adminEndpoints(settings)
55
+ ],
29
56
  onInit: async (payload)=>{
30
57
  await previous?.(payload);
31
- await report(payload, options);
58
+ if (process.env.NEXT_PHASE === 'phase-production-build') return;
59
+ const s = settings();
60
+ await Promise.all([
61
+ report(payload, options),
62
+ s ? syncStaff(payload, s) : undefined
63
+ ]);
32
64
  }
33
65
  };
34
66
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Config, Payload } from 'payload';\nimport { recordActivePlugin } from './activePlugins.js';\nimport { buildReport, resolveEnvironment, sendReport } from './report.js';\n\nexport type { SiteReport } from './report.js';\n\nexport type HubPluginConfig = {\n /** The Hub's address. Default: FOUNDRY_HUB_URL. */\n hubUrl?: string;\n /** This site's key from Hub › Admin › Projects. Default: FOUNDRY_HUB_KEY. */\n key?: string;\n /** Default: FOUNDRY_ENV, else VERCEL_ENV, else production. */\n environment?: string;\n enabled?: boolean;\n};\n\n/** Reports what the site is running, once per start. Never holds up or breaks boot. */\nasync function report(payload: Payload, options: HubPluginConfig) {\n if (process.env.NEXT_PHASE === 'phase-production-build') return;\n const hubUrl = options.hubUrl ?? process.env.FOUNDRY_HUB_URL;\n const key = options.key ?? process.env.FOUNDRY_HUB_KEY;\n if (!hubUrl || !key) {\n payload.logger.warn(\n '[hub-plugin] FOUNDRY_HUB_URL or FOUNDRY_HUB_KEY is not set, so this site is not reporting to the Foundry Hub.'\n );\n return;\n }\n const environment = resolveEnvironment(process.env, options.environment);\n if (!environment) return;\n\n const foundrykit = payload.config.custom?.foundrykit as\n | { activePlugins?: string[] }\n | undefined;\n const ok = await sendReport(\n hubUrl,\n key,\n buildReport({\n cwd: process.cwd(),\n env: process.env,\n environment,\n serverURL: payload.config.serverURL,\n activePlugins: foundrykit?.activePlugins ?? [],\n })\n );\n if (!ok)\n payload.logger.warn(\n `[hub-plugin] Couldn't report to the Foundry Hub at ${hubUrl}.`\n );\n}\n\nexport const hubPlugin =\n (options: HubPluginConfig = {}) =>\n (incoming: Config): Config => {\n if (options.enabled === false) return incoming;\n const config = recordActivePlugin(incoming, '@foundrykit/hub-plugin');\n const previous = config.onInit;\n return {\n ...config,\n onInit: async payload => {\n await previous?.(payload);\n await report(payload, options);\n },\n };\n };\n\nexport default hubPlugin;\n"],"names":["recordActivePlugin","buildReport","resolveEnvironment","sendReport","report","payload","options","process","env","NEXT_PHASE","hubUrl","FOUNDRY_HUB_URL","key","FOUNDRY_HUB_KEY","logger","warn","environment","foundrykit","config","custom","ok","cwd","serverURL","activePlugins","hubPlugin","incoming","enabled","previous","onInit"],"mappings":"AACA,SAASA,kBAAkB,QAAQ,qBAAqB;AACxD,SAASC,WAAW,EAAEC,kBAAkB,EAAEC,UAAU,QAAQ,cAAc;AAc1E,qFAAqF,GACrF,eAAeC,OAAOC,OAAgB,EAAEC,OAAwB;IAC9D,IAAIC,QAAQC,GAAG,CAACC,UAAU,KAAK,0BAA0B;IACzD,MAAMC,SAASJ,QAAQI,MAAM,IAAIH,QAAQC,GAAG,CAACG,eAAe;IAC5D,MAAMC,MAAMN,QAAQM,GAAG,IAAIL,QAAQC,GAAG,CAACK,eAAe;IACtD,IAAI,CAACH,UAAU,CAACE,KAAK;QACnBP,QAAQS,MAAM,CAACC,IAAI,CACjB;QAEF;IACF;IACA,MAAMC,cAAcd,mBAAmBK,QAAQC,GAAG,EAAEF,QAAQU,WAAW;IACvE,IAAI,CAACA,aAAa;IAElB,MAAMC,aAAaZ,QAAQa,MAAM,CAACC,MAAM,EAAEF;IAG1C,MAAMG,KAAK,MAAMjB,WACfO,QACAE,KACAX,YAAY;QACVoB,KAAKd,QAAQc,GAAG;QAChBb,KAAKD,QAAQC,GAAG;QAChBQ;QACAM,WAAWjB,QAAQa,MAAM,CAACI,SAAS;QACnCC,eAAeN,YAAYM,iBAAiB,EAAE;IAChD;IAEF,IAAI,CAACH,IACHf,QAAQS,MAAM,CAACC,IAAI,CACjB,CAAC,mDAAmD,EAAEL,OAAO,CAAC,CAAC;AAErE;AAEA,OAAO,MAAMc,YACX,CAAClB,UAA2B,CAAC,CAAC,GAC9B,CAACmB;QACC,IAAInB,QAAQoB,OAAO,KAAK,OAAO,OAAOD;QACtC,MAAMP,SAASlB,mBAAmByB,UAAU;QAC5C,MAAME,WAAWT,OAAOU,MAAM;QAC9B,OAAO;YACL,GAAGV,MAAM;YACTU,QAAQ,OAAMvB;gBACZ,MAAMsB,WAAWtB;gBACjB,MAAMD,OAAOC,SAASC;YACxB;QACF;IACF,EAAE;AAEJ,eAAekB,UAAU"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Config, Payload } from 'payload';\nimport { recordActivePlugin } from './activePlugins.js';\nimport { adminEndpoints, hubLockHook, syncStaff } from './admin.js';\nimport type { HubSettings } from './hub.js';\nimport { buildReport, resolveEnvironment, sendReport } from './report.js';\n\nexport type { SiteReport } from './report.js';\n\nexport type HubPluginConfig = {\n /** The Hub's address. Default: FOUNDRY_HUB_URL. */\n hubUrl?: string;\n /** This site's key from Hub › Admin › Projects. Default: FOUNDRY_HUB_KEY. */\n key?: string;\n /** Default: FOUNDRY_ENV, else VERCEL_ENV, else production. */\n environment?: string;\n enabled?: boolean;\n};\n\n/** The Hub's address, this site's key and environment; null when any is missing. */\nconst settingsFrom = (options: HubPluginConfig): HubSettings | null => {\n const hubUrl = options.hubUrl ?? process.env.FOUNDRY_HUB_URL;\n const key = options.key ?? process.env.FOUNDRY_HUB_KEY;\n const environment = resolveEnvironment(process.env, options.environment);\n return hubUrl && key && environment ? { hubUrl, key, environment } : null;\n};\n\n/** Reports what the site is running, once per start. Never holds up or breaks boot. */\nasync function report(payload: Payload, options: HubPluginConfig) {\n const hubUrl = options.hubUrl ?? process.env.FOUNDRY_HUB_URL;\n const key = options.key ?? process.env.FOUNDRY_HUB_KEY;\n if (!hubUrl || !key) {\n payload.logger.warn(\n '[hub-plugin] FOUNDRY_HUB_URL or FOUNDRY_HUB_KEY is not set, so this site is not reporting to the Foundry Hub.'\n );\n return;\n }\n const environment = resolveEnvironment(process.env, options.environment);\n if (!environment) return;\n\n const foundrykit = payload.config.custom?.foundrykit as\n | { activePlugins?: string[] }\n | undefined;\n const ok = await sendReport(\n hubUrl,\n key,\n buildReport({\n cwd: process.cwd(),\n env: process.env,\n environment,\n serverURL: payload.config.serverURL,\n activePlugins: foundrykit?.activePlugins ?? [],\n })\n );\n if (!ok)\n payload.logger.warn(\n `[hub-plugin] Couldn't report to the Foundry Hub at ${hubUrl}.`\n );\n}\n\nexport const hubPlugin =\n (options: HubPluginConfig = {}) =>\n (incoming: Config): Config => {\n if (options.enabled === false) return incoming;\n const config = recordActivePlugin(incoming, '@foundrykit/hub-plugin');\n const previous = config.onInit;\n const settings = () => settingsFrom(options);\n // Payload's default: the first collection with auth.\n const authSlug =\n config.admin?.user ?? config.collections?.find(c => c.auth)?.slug;\n return {\n ...config,\n collections: config.collections?.map(c =>\n c.slug === authSlug\n ? {\n ...c,\n hooks: {\n ...c.hooks,\n beforeLogin: [\n ...(c.hooks?.beforeLogin ?? []),\n hubLockHook(settings),\n ],\n },\n }\n : c\n ),\n endpoints: [...(config.endpoints ?? []), ...adminEndpoints(settings)],\n onInit: async payload => {\n await previous?.(payload);\n if (process.env.NEXT_PHASE === 'phase-production-build') return;\n const s = settings();\n await Promise.all([\n report(payload, options),\n s ? syncStaff(payload, s) : undefined,\n ]);\n },\n };\n };\n\nexport default hubPlugin;\n"],"names":["recordActivePlugin","adminEndpoints","hubLockHook","syncStaff","buildReport","resolveEnvironment","sendReport","settingsFrom","options","hubUrl","process","env","FOUNDRY_HUB_URL","key","FOUNDRY_HUB_KEY","environment","report","payload","logger","warn","foundrykit","config","custom","ok","cwd","serverURL","activePlugins","hubPlugin","incoming","enabled","previous","onInit","settings","authSlug","admin","user","collections","find","c","auth","slug","map","hooks","beforeLogin","endpoints","NEXT_PHASE","s","Promise","all","undefined"],"mappings":"AACA,SAASA,kBAAkB,QAAQ,qBAAqB;AACxD,SAASC,cAAc,EAAEC,WAAW,EAAEC,SAAS,QAAQ,aAAa;AAEpE,SAASC,WAAW,EAAEC,kBAAkB,EAAEC,UAAU,QAAQ,cAAc;AAc1E,kFAAkF,GAClF,MAAMC,eAAe,CAACC;IACpB,MAAMC,SAASD,QAAQC,MAAM,IAAIC,QAAQC,GAAG,CAACC,eAAe;IAC5D,MAAMC,MAAML,QAAQK,GAAG,IAAIH,QAAQC,GAAG,CAACG,eAAe;IACtD,MAAMC,cAAcV,mBAAmBK,QAAQC,GAAG,EAAEH,QAAQO,WAAW;IACvE,OAAON,UAAUI,OAAOE,cAAc;QAAEN;QAAQI;QAAKE;IAAY,IAAI;AACvE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wBACVC,aAAa;+BACPL,EAAEI,KAAK,EAAEC,eAAe,EAAE;4BAC9BzC,YAAY8B;yBACb;oBACH;gBACF,IACAM;YAENM,WAAW;mBAAKvB,OAAOuB,SAAS,IAAI,EAAE;mBAAM3C,eAAe+B;aAAU;YACrED,QAAQ,OAAMd;gBACZ,MAAMa,WAAWb;gBACjB,IAAIP,QAAQC,GAAG,CAACkC,UAAU,KAAK,0BAA0B;gBACzD,MAAMC,IAAId;gBACV,MAAMe,QAAQC,GAAG,CAAC;oBAChBhC,OAAOC,SAAST;oBAChBsC,IAAI3C,UAAUc,SAAS6B,KAAKG;iBAC7B;YACH;QACF;IACF,EAAE;AAEJ,eAAetB,UAAU"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@foundrykit/hub-plugin",
3
- "version": "0.1.4",
4
- "description": "Reports the FoundryKit versions a Payload 3 site is actually running to the Foundry Hub, once each time the site starts.",
3
+ "version": "0.3.0",
4
+ "description": "Connects a Payload 3 site to the Foundry Hub: reports the FoundryKit versions it runs, signs Umi staff in from the Hub in one click, and locks offboarded staff.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "author": {
@@ -27,8 +27,11 @@
27
27
  "dist"
28
28
  ],
29
29
  "devDependencies": {
30
+ "@payloadcms/db-mongodb": "3.90.0",
31
+ "@payloadcms/db-postgres": "3.90.0",
30
32
  "@swc/cli": "0.6.0",
31
33
  "@types/node": "22.19.9",
34
+ "mongodb-memory-server": "10.1.4",
32
35
  "payload": "3.90.0",
33
36
  "rimraf": "3.0.2",
34
37
  "typescript": "5.9.2",
@@ -58,7 +61,8 @@
58
61
  "build:types": "tsc --outDir dist --rootDir ./src",
59
62
  "clean": "rimraf {dist,*.tsbuildinfo}",
60
63
  "verify:pack": "node scripts/verify-pack.mjs",
61
- "test": "pnpm test:unit",
62
- "test:unit": "vitest run src"
64
+ "test": "pnpm test:unit && pnpm test:int",
65
+ "test:unit": "vitest run src",
66
+ "test:int": "vitest run dev/int.spec.ts"
63
67
  }
64
68
  }