@foundrykit/hub-plugin 0.1.3 → 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.
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,58 @@ 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 keeps two lists (`GET /api/sites/staff`): **active** (Umi members who
89
+ aren't deactivated) and **locked** (deactivated Umi members, and anyone the Hub
90
+ knows with no organisation left, i.e. removed from Umi). Client users are on
91
+ neither list and are left alone.
92
+
93
+ The plugin pulls the lists **on boot** and whenever the Hub calls
94
+ `POST /api/hub/sync` (it does after deactivating, reactivating, removing from or
95
+ adding to Umi, or deleting someone). That endpoint takes no input and trusts
96
+ nothing: it only makes the site pull from the Hub with its own key, and calls
97
+ within 10 seconds of the last one are ignored.
98
+
99
+ - **Lock**: `lockUntil` is set to `9999-12-31T00:00:00.000Z` and every session
100
+ is removed.
101
+ - **Unlock**: only accounts locked with that exact date (not ones locked by too
102
+ many wrong passwords) whose email is active again.
103
+ - **Password logins** (and the sign-in after a password reset) ask the Hub about
104
+ that email first (2 s at most). If it says locked, the login is refused and
105
+ the account is locked. If the Hub doesn't answer or isn't configured, the
106
+ login goes ahead.
107
+
108
+ Locking needs `lockUntil`, which Payload only adds when `auth.maxLoginAttempts`
109
+ is above 0 (the default is 5). With `maxLoginAttempts: 0` the plugin logs once
110
+ and doesn't lock, but still refuses password logins the Hub says are locked.
111
+ Without `auth.useSessions` (on by default), existing tokens can't be revoked and
112
+ stay valid until they expire.
113
+
114
+ `fk run` (local dev) has no **Open admin** yet.
@@ -0,0 +1,32 @@
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
+ /** Pulls the staff lists and applies them. Never throws; false when it couldn't. */
28
+ export declare function syncStaff(payload: Payload, settings: HubSettings): Promise<boolean>;
29
+ /** Refuses a password login (or a reset's sign-in) for someone the Hub has offboarded. Fails open. */
30
+ export declare const hubLockHook: (settings: () => HubSettings | null) => CollectionBeforeLoginHook;
31
+ export declare function adminEndpoints(settings: () => HubSettings | null): Endpoint[];
32
+ export {};
package/dist/admin.js ADDED
@@ -0,0 +1,307 @@
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 pull
4
+ * the Hub's staff lists 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 } 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
+ /** Pulls the staff lists and applies them. Never throws; false when it couldn't. */ export async function syncStaff(payload, settings) {
79
+ try {
80
+ const config = authConfig(payload);
81
+ if (!canLock(config)) {
82
+ 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).`);
83
+ warnedNoLock = true;
84
+ return false;
85
+ }
86
+ const lists = await fetchStaff(settings);
87
+ if (!lists) {
88
+ payload.logger.warn('[hub-plugin] Couldn’t fetch the staff lists from the Foundry Hub.');
89
+ return false;
90
+ }
91
+ const emails = [
92
+ ...lists.locked,
93
+ ...lists.active
94
+ ];
95
+ if (!emails.length) return true;
96
+ const { docs } = await payload.find({
97
+ collection: config.slug,
98
+ depth: 0,
99
+ overrideAccess: true,
100
+ pagination: false,
101
+ showHiddenFields: true,
102
+ where: {
103
+ email: {
104
+ in: emails
105
+ }
106
+ }
107
+ });
108
+ const plan = syncPlan(docs, lists);
109
+ for (const u of plan.lock)await lockUser(payload, u.id);
110
+ for (const u of plan.unlock)await unlockUser(payload, u.id);
111
+ if (plan.lock.length || plan.unlock.length) payload.logger.info(`[hub-plugin] Staff sync: locked ${plan.lock.length}, unlocked ${plan.unlock.length}.`);
112
+ return true;
113
+ } catch (err) {
114
+ payload.logger.error({
115
+ err,
116
+ msg: '[hub-plugin] Staff sync failed.'
117
+ });
118
+ return false;
119
+ }
120
+ }
121
+ /** 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 })=>{
122
+ const s = settings();
123
+ const email = user.email;
124
+ if (!s || !email) return user;
125
+ if (await fetchStaffStatus(s, email) !== 'locked') return user;
126
+ // Not awaited: the login's transaction rolls back anything written with
127
+ // it, and a write outside it waits for that rollback.
128
+ void lockUser(req.payload, user.id).catch((err)=>req.payload.logger.error({
129
+ err,
130
+ msg: '[hub-plugin] Couldn’t lock user.'
131
+ }));
132
+ throw new LockedAuth(req.t);
133
+ };
134
+ /** Same steps as Payload's login operation, with an 8-hour token and session. */ async function signIn(req, user) {
135
+ const { payload } = req;
136
+ const base = authConfig(payload);
137
+ const collectionConfig = {
138
+ ...base,
139
+ auth: {
140
+ ...base.auth,
141
+ tokenExpiration: SESSION_SECONDS
142
+ }
143
+ };
144
+ const doc = {
145
+ ...user,
146
+ collection: base.slug,
147
+ _strategy: 'local-jwt'
148
+ };
149
+ const { sid } = await addSessionToUser({
150
+ collectionConfig,
151
+ payload,
152
+ req,
153
+ user: doc
154
+ });
155
+ const fieldsToSign = getFieldsToSign({
156
+ collectionConfig,
157
+ email: user.email,
158
+ user: doc,
159
+ ...sid ? {
160
+ sid
161
+ } : {}
162
+ });
163
+ const { token } = await jwtSign({
164
+ fieldsToSign,
165
+ secret: payload.secret,
166
+ tokenExpiration: SESSION_SECONDS
167
+ });
168
+ return generatePayloadCookie({
169
+ collectionAuthConfig: collectionConfig.auth,
170
+ cookiePrefix: payload.config.cookiePrefix,
171
+ token
172
+ });
173
+ }
174
+ /** A new CMS user for this person, with the matching permissions-plugin role if there is one. */ async function createUser(req, who) {
175
+ const { payload } = req;
176
+ const config = authConfig(payload);
177
+ const has = (name)=>config.flattenedFields.find((f)=>f.name === name);
178
+ const data = {
179
+ email: who.email,
180
+ // Unusable: they can still choose one with forgot-password.
181
+ password: randomBytes(32).toString('base64url')
182
+ };
183
+ if (has('name')?.type === 'text' && who.name) data.name = who.name;
184
+ if (config.auth.verify) data._verified = true;
185
+ const role = has('role');
186
+ if (role?.type === 'relationship' && role.relationTo === 'roles') {
187
+ const name = payloadRoleName(who.role);
188
+ const { docs } = await payload.find({
189
+ collection: 'roles',
190
+ depth: 0,
191
+ limit: 1,
192
+ overrideAccess: true,
193
+ req,
194
+ where: {
195
+ name: {
196
+ equals: name
197
+ }
198
+ }
199
+ });
200
+ if (docs[0]) data.role = docs[0].id;
201
+ else payload.logger.warn(`[hub-plugin] No "${name}" role, so ${who.email} was created without one.`);
202
+ }
203
+ return await payload.create({
204
+ collection: config.slug,
205
+ data: data,
206
+ depth: 0,
207
+ disableVerificationEmail: true,
208
+ overrideAccess: true,
209
+ req,
210
+ showHiddenFields: true
211
+ });
212
+ }
213
+ /** Only ever the site's own admin path: never a full or protocol-relative URL. */ const adminPath = (payload)=>{
214
+ const route = payload.config.routes.admin;
215
+ return /^\/(?!\/)/.test(route) ? route : '/admin';
216
+ };
217
+ const redirect = (location, cookie)=>new Response(null, {
218
+ status: 302,
219
+ headers: {
220
+ location,
221
+ 'cache-control': 'no-store',
222
+ 'referrer-policy': 'no-referrer',
223
+ ...cookie ? {
224
+ 'set-cookie': cookie
225
+ } : {}
226
+ }
227
+ });
228
+ export function adminEndpoints(settings) {
229
+ let lastSync = 0;
230
+ return [
231
+ {
232
+ path: '/hub/login',
233
+ method: 'get',
234
+ handler: async (req)=>{
235
+ const admin = adminPath(req.payload);
236
+ const fail = (reason)=>redirect(`${admin}/login?hub=${reason}`);
237
+ const s = settings();
238
+ if (!s) return fail('not-configured');
239
+ const ticket = req.searchParams.get('ticket');
240
+ if (!ticket) return fail('invalid');
241
+ const who = await redeemTicket(s, ticket);
242
+ if (!who) return fail('expired');
243
+ try {
244
+ const { docs } = await req.payload.find({
245
+ collection: authConfig(req.payload).slug,
246
+ depth: 0,
247
+ limit: 1,
248
+ overrideAccess: true,
249
+ req,
250
+ showHiddenFields: true,
251
+ where: {
252
+ email: {
253
+ equals: who.email
254
+ }
255
+ }
256
+ });
257
+ let user = docs[0];
258
+ if (!user) user = await createUser(req, who);
259
+ else if (isHubLocked(user.lockUntil)) {
260
+ await unlockUser(req.payload, user.id, req);
261
+ // signIn writes the whole doc back when it adds the session.
262
+ user = {
263
+ ...user,
264
+ lockUntil: null,
265
+ loginAttempts: 0
266
+ };
267
+ }
268
+ return redirect(admin, await signIn(req, user));
269
+ } catch (err) {
270
+ req.payload.logger.error({
271
+ err,
272
+ msg: '[hub-plugin] One-click sign-in failed.'
273
+ });
274
+ return fail('failed');
275
+ }
276
+ }
277
+ },
278
+ {
279
+ path: '/hub/sync',
280
+ method: 'post',
281
+ // No input and no trust: it only makes the site pull from the Hub with its own key.
282
+ handler: async (req)=>{
283
+ const s = settings();
284
+ if (!s) return Response.json({
285
+ ok: false
286
+ }, {
287
+ status: 503
288
+ });
289
+ if (Date.now() - lastSync < SYNC_INTERVAL_MS) return Response.json({
290
+ ok: true,
291
+ skipped: true
292
+ }, {
293
+ status: 202
294
+ });
295
+ lastSync = Date.now();
296
+ const ok = await syncStaff(req.payload, s);
297
+ return Response.json({
298
+ ok
299
+ }, {
300
+ status: ok ? 200 : 502
301
+ });
302
+ }
303
+ }
304
+ ];
305
+ }
306
+
307
+ //# 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 pull\n * the Hub's staff lists 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 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/** Pulls the staff lists and applies them. Never throws; false when it couldn't. */\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 const lists = await fetchStaff(settings);\n if (!lists) {\n payload.logger.warn(\n '[hub-plugin] Couldn’t fetch the staff lists from the Foundry Hub.'\n );\n return false;\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","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","emails","docs","find","depth","overrideAccess","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","limit","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,QAEP,WAAW;AAEl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EAAEW;wBACvC,6DAA6D;wBAC7DnB,OAAO;4BAAE,GAAGA,IAAI;4BAAE9B,WAAW;4BAAMkD,eAAe;wBAAE;oBACtD;oBACA,OAAOoD,SAASzE,OAAO,MAAM4C,OAAOxB,KAAKnB;gBAC3C,EAAE,OAAOoC,KAAK;oBACZjB,IAAIvB,OAAO,CAAC4B,MAAM,CAACa,KAAK,CAAC;wBACvBD;wBACAE,KAAK;oBACP;oBACA,OAAO6C,KAAK;gBACd;YACF;QACF;QACA;YACEH,MAAM;YACNC,QAAQ;YACR,oFAAoF;YACpFC,SAAS,OAAM/D;gBACb,MAAMqB,IAAIjB;gBACV,IAAI,CAACiB,GAAG,OAAOmC,SAASa,IAAI,CAAC;oBAAEC,IAAI;gBAAM,GAAG;oBAAEb,QAAQ;gBAAI;gBAC1D,IAAIxG,KAAKsH,GAAG,KAAKX,WAAWjH,kBAC1B,OAAO6G,SAASa,IAAI,CAAC;oBAAEC,IAAI;oBAAME,SAAS;gBAAK,GAAG;oBAAEf,QAAQ;gBAAI;gBAClEG,WAAW3G,KAAKsH,GAAG;gBACnB,MAAMD,KAAK,MAAMnE,UAAUH,IAAIvB,OAAO,EAAE4C;gBACxC,OAAOmC,SAASa,IAAI,CAAC;oBAAEC;gBAAG,GAAG;oBAAEb,QAAQa,KAAK,MAAM;gBAAI;YACxD;QACF;KACD;AACH"}
package/dist/hub.d.ts ADDED
@@ -0,0 +1,24 @@
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
+ /** Every email the Hub wants unlocked (`active`) or locked. */
21
+ export declare function fetchStaff(s: HubSettings, fetchImpl?: Fetch): Promise<StaffLists | null>;
22
+ /** One email's status, waiting 2 s at most (it sits in front of a password login). */
23
+ export declare function fetchStaffStatus(s: HubSettings, email: string, fetchImpl?: Fetch): Promise<StaffStatus | null>;
24
+ export {};
package/dist/hub.js ADDED
@@ -0,0 +1,46 @@
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
+ /** Every email the Hub wants unlocked (`active`) or locked. */ export async function fetchStaff(s, fetchImpl) {
34
+ const body = await call(s, '/api/sites/staff', 3000, {}, fetchImpl);
35
+ return isEmails(body?.active) && isEmails(body?.locked) ? {
36
+ active: body.active,
37
+ locked: body.locked
38
+ } : null;
39
+ }
40
+ /** One email's status, waiting 2 s at most (it sits in front of a password login). */ export async function fetchStaffStatus(s, email, fetchImpl) {
41
+ const body = await call(s, `/api/sites/staff?email=${encodeURIComponent(email)}`, 2000, {}, fetchImpl);
42
+ const status = body?.status;
43
+ return status === 'active' || status === 'locked' || status === 'unknown' ? status : null;
44
+ }
45
+
46
+ //# 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/** Every email the Hub wants unlocked (`active`) or locked. */\nexport async function fetchStaff(\n s: HubSettings,\n fetchImpl?: Fetch\n): Promise<StaffLists | null> {\n const body = (await call(\n s,\n '/api/sites/staff',\n 3000,\n {},\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","fetchStaff","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,6DAA6D,GAC7D,OAAO,eAAeG,WACpBlC,CAAc,EACdI,SAAiB;IAEjB,MAAMqB,OAAQ,MAAM1B,KAClBC,GACA,oBACA,MACA,CAAC,GACDI;IAEF,OAAOa,SAASQ,MAAMU,WAAWlB,SAASQ,MAAMW,UAC5C;QAAED,QAAQV,KAAKU,MAAM;QAAEC,QAAQX,KAAKW,MAAM;IAAC,IAC3C;AACN;AAEA,oFAAoF,GACpF,OAAO,eAAeC,iBACpBrC,CAAc,EACd8B,KAAa,EACb1B,SAAiB;IAEjB,MAAMqB,OAAQ,MAAM1B,KAClBC,GACA,CAAC,uBAAuB,EAAEsC,mBAAmBR,QAAQ,EACrD,MACA,CAAC,GACD1B;IAEF,MAAMmC,SAASd,MAAMc;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","serverUR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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,WAA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,KAAKP,WACP;oBACE,GAAGK,CAAC;oBACJI,OAAO;wBACL,GAAGJ,EAAEI,KAAK;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/dist/report.d.ts CHANGED
@@ -5,6 +5,7 @@ export type SiteReport = {
5
5
  commit: string | null;
6
6
  payloadVersion: string | null;
7
7
  nextVersion: string | null;
8
+ reactVersion: string | null;
8
9
  activePlugins: string[];
9
10
  packages: {
10
11
  name: string;
package/dist/report.js CHANGED
@@ -51,6 +51,7 @@ export function buildReport(input) {
51
51
  commit: env.SOURCE_COMMIT || env.VERCEL_GIT_COMMIT_SHA || env.GIT_COMMIT || null,
52
52
  payloadVersion: readInstalled(cwd, 'payload'),
53
53
  nextVersion: readInstalled(cwd, 'next'),
54
+ reactVersion: readInstalled(cwd, 'react'),
54
55
  activePlugins: input.activePlugins,
55
56
  packages
56
57
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/report.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/** What the Hub accepts at /api/sites/report. Keep in step with apps/hub/src/lib/site-report.ts. */\nexport type SiteReport = {\n environment: string;\n url: string | null;\n commit: string | null;\n payloadVersion: string | null;\n nextVersion: string | null;\n activePlugins: string[];\n packages: { name: string; version: string; resolved: boolean }[];\n};\n\n/**\n * The environment to report as, or null to stay quiet. A Vercel preview only\n * reports when FOUNDRY_ENV names it, so a PR branch can't overwrite production.\n */\nexport function resolveEnvironment(\n env: NodeJS.ProcessEnv,\n option?: string\n): string | null {\n const named = option ?? env.FOUNDRY_ENV;\n if (named) return named.trim().toLowerCase();\n if (env.VERCEL_ENV === 'preview') return null;\n return (env.VERCEL_ENV ?? 'production').toLowerCase();\n}\n\nconst readJson = (path: string) =>\n JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>;\n\n/**\n * The installed version, read straight from node_modules: `require.resolve`\n * can't reach package.json when a package's `exports` doesn't list it.\n */\nexport function readInstalled(cwd: string, name: string): string | null {\n try {\n const { version } = readJson(\n join(cwd, 'node_modules', name, 'package.json')\n );\n return typeof version === 'string' ? version : null;\n } catch {\n return null;\n }\n}\n\nexport function buildReport(input: {\n cwd: string;\n env: NodeJS.ProcessEnv;\n environment: string;\n serverURL?: string;\n activePlugins: string[];\n}): SiteReport {\n const { cwd, env } = input;\n let declared: Record<string, string> = {};\n try {\n const pkg = readJson(join(cwd, 'package.json')) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n declared = { ...pkg.devDependencies, ...pkg.dependencies };\n } catch {\n // No package.json where we expected it: report no packages rather than fail.\n }\n const packages = Object.entries(declared)\n .filter(([name]) => name.startsWith('@foundrykit/'))\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([name, specifier]) => {\n const installed = readInstalled(cwd, name);\n return installed\n ? { name, version: installed, resolved: true }\n : { name, version: specifier, resolved: false };\n });\n\n return {\n environment: input.environment,\n url: input.serverURL || null,\n commit:\n env.SOURCE_COMMIT || env.VERCEL_GIT_COMMIT_SHA || env.GIT_COMMIT || null,\n payloadVersion: readInstalled(cwd, 'payload'),\n nextVersion: readInstalled(cwd, 'next'),\n activePlugins: input.activePlugins,\n packages,\n };\n}\n\n/** Sends the report. Never throws and never waits more than 3 seconds. */\nexport async function sendReport(\n url: string,\n key: string,\n report: SiteReport,\n fetchImpl: (url: string, init?: RequestInit) => Promise<Response> = fetch\n): Promise<boolean> {\n try {\n const res = await fetchImpl(`${url.replace(/\\/$/, '')}/api/sites/report`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${key}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(report),\n signal: AbortSignal.timeout(3000),\n // A redirect (e.g. to sign-in) is not a delivered report.\n redirect: 'manual',\n });\n return res.ok;\n } catch {\n return false;\n }\n}\n"],"names":["readFileSync","join","resolveEnvironment","env","option","named","FOUNDRY_ENV","trim","toLowerCase","VERCEL_ENV","readJson","path","JSON","parse","readInstalled","cwd","name","version","buildReport","input","declared","pkg","devDependencies","dependencies","packages","Object","entries","filter","startsWith","sort","a","b","localeCompare","map","specifier","installed","resolved","environment","url","serverURL","commit","SOURCE_COMMIT","VERCEL_GIT_COMMIT_SHA","GIT_COMMIT","payloadVersion","nextVersion","activePlugins","sendReport","key","report","fetchImpl","fetch","res","replace","method","headers","authorization","body","stringify","signal","AbortSignal","timeout","redirect","ok"],"mappings":"AAAA,SAASA,YAAY,QAAQ,UAAU;AACvC,SAASC,IAAI,QAAQ,YAAY;AAajC;;;CAGC,GACD,OAAO,SAASC,mBACdC,GAAsB,EACtBC,MAAe;IAEf,MAAMC,QAAQD,UAAUD,IAAIG,WAAW;IACvC,IAAID,OAAO,OAAOA,MAAME,IAAI,GAAGC,WAAW;IAC1C,IAAIL,IAAIM,UAAU,KAAK,WAAW,OAAO;IACzC,OAAO,AAACN,CAAAA,IAAIM,UAAU,IAAI,YAAW,EAAGD,WAAW;AACrD;AAEA,MAAME,WAAW,CAACC,OAChBC,KAAKC,KAAK,CAACb,aAAaW,MAAM;AAEhC;;;CAGC,GACD,OAAO,SAASG,cAAcC,GAAW,EAAEC,IAAY;IACrD,IAAI;QACF,MAAM,EAAEC,OAAO,EAAE,GAAGP,SAClBT,KAAKc,KAAK,gBAAgBC,MAAM;QAElC,OAAO,OAAOC,YAAY,WAAWA,UAAU;IACjD,EAAE,OAAM;QACN,OAAO;IACT;AACF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,KAAK8C,SAAS,CAACT;YACrBU,QAAQC,YAAYC,OAAO,CAAC;YAC5B,0DAA0D;YAC1DC,UAAU;QACZ;QACA,OAAOV,IAAIW,EAAE;IACf,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
1
+ {"version":3,"sources":["../src/report.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/** What the Hub accepts at /api/sites/report. Keep in step with apps/hub/src/lib/site-report.ts. */\nexport type SiteReport = {\n environment: string;\n url: string | null;\n commit: string | null;\n payloadVersion: string | null;\n nextVersion: string | null;\n reactVersion: string | null;\n activePlugins: string[];\n packages: { name: string; version: string; resolved: boolean }[];\n};\n\n/**\n * The environment to report as, or null to stay quiet. A Vercel preview only\n * reports when FOUNDRY_ENV names it, so a PR branch can't overwrite production.\n */\nexport function resolveEnvironment(\n env: NodeJS.ProcessEnv,\n option?: string\n): string | null {\n const named = option ?? env.FOUNDRY_ENV;\n if (named) return named.trim().toLowerCase();\n if (env.VERCEL_ENV === 'preview') return null;\n return (env.VERCEL_ENV ?? 'production').toLowerCase();\n}\n\nconst readJson = (path: string) =>\n JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>;\n\n/**\n * The installed version, read straight from node_modules: `require.resolve`\n * can't reach package.json when a package's `exports` doesn't list it.\n */\nexport function readInstalled(cwd: string, name: string): string | null {\n try {\n const { version } = readJson(\n join(cwd, 'node_modules', name, 'package.json')\n );\n return typeof version === 'string' ? version : null;\n } catch {\n return null;\n }\n}\n\nexport function buildReport(input: {\n cwd: string;\n env: NodeJS.ProcessEnv;\n environment: string;\n serverURL?: string;\n activePlugins: string[];\n}): SiteReport {\n const { cwd, env } = input;\n let declared: Record<string, string> = {};\n try {\n const pkg = readJson(join(cwd, 'package.json')) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n declared = { ...pkg.devDependencies, ...pkg.dependencies };\n } catch {\n // No package.json where we expected it: report no packages rather than fail.\n }\n const packages = Object.entries(declared)\n .filter(([name]) => name.startsWith('@foundrykit/'))\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([name, specifier]) => {\n const installed = readInstalled(cwd, name);\n return installed\n ? { name, version: installed, resolved: true }\n : { name, version: specifier, resolved: false };\n });\n\n return {\n environment: input.environment,\n url: input.serverURL || null,\n commit:\n env.SOURCE_COMMIT || env.VERCEL_GIT_COMMIT_SHA || env.GIT_COMMIT || null,\n payloadVersion: readInstalled(cwd, 'payload'),\n nextVersion: readInstalled(cwd, 'next'),\n reactVersion: readInstalled(cwd, 'react'),\n activePlugins: input.activePlugins,\n packages,\n };\n}\n\n/** Sends the report. Never throws and never waits more than 3 seconds. */\nexport async function sendReport(\n url: string,\n key: string,\n report: SiteReport,\n fetchImpl: (url: string, init?: RequestInit) => Promise<Response> = fetch\n): Promise<boolean> {\n try {\n const res = await fetchImpl(`${url.replace(/\\/$/, '')}/api/sites/report`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${key}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(report),\n signal: AbortSignal.timeout(3000),\n // A redirect (e.g. to sign-in) is not a delivered report.\n redirect: 'manual',\n });\n return res.ok;\n } catch {\n return false;\n }\n}\n"],"names":["readFileSync","join","resolveEnvironment","env","option","named","FOUNDRY_ENV","trim","toLowerCase","VERCEL_ENV","readJson","path","JSON","parse","readInstalled","cwd","name","version","buildReport","input","declared","pkg","devDependencies","dependencies","packages","Object","entries","filter","startsWith","sort","a","b","localeCompare","map","specifier","installed","resolved","environment","url","serverURL","commit","SOURCE_COMMIT","VERCEL_GIT_COMMIT_SHA","GIT_COMMIT","payloadVersion","nextVersion","reactVersion","activePlugins","sendReport","key","report","fetchImpl","fetch","res","replace","method","headers","authorization","body","stringify","signal","AbortSignal","timeout","redirect","ok"],"mappings":"AAAA,SAASA,YAAY,QAAQ,UAAU;AACvC,SAASC,IAAI,QAAQ,YAAY;AAcjC;;;CAGC,GACD,OAAO,SAASC,mBACdC,GAAsB,EACtBC,MAAe;I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ACxBC,QACErC,IAAIsC,aAAa,IAAItC,IAAIuC,qBAAqB,IAAIvC,IAAIwC,UAAU,IAAI;QACtEC,gBAAgB9B,cAAcC,KAAK;QACnC8B,aAAa/B,cAAcC,KAAK;QAChC+B,cAAchC,cAAcC,KAAK;QACjCgC,eAAe5B,MAAM4B,aAAa;QAClCvB;IACF;AACF;AAEA,wEAAwE,GACxE,OAAO,eAAewB,WACpBV,GAAW,EACXW,GAAW,EACXC,MAAkB,EAClBC,YAAoEC,KAAK;IAEzE,IAAI;QACF,MAAMC,MAAM,MAAMF,UAAU,GAAGb,IAAIgB,OAAO,CAAC,OAAO,IAAI,iBAAiB,CAAC,EAAE;YACxEC,QAAQ;YACRC,SAAS;gBACPC,eAAe,CAAC,OAAO,EAAER,KAAK;gBAC9B,gBAAgB;YAClB;YACAS,MAAM9C,KAAK+C,SAAS,CAACT;YACrBU,QAAQC,YAAYC,OAAO,CAAC;YAC5B,0DAA0D;YAC1DC,UAAU;QACZ;QACA,OAAOV,IAAIW,EAAE;IACf,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@foundrykit/hub-plugin",
3
- "version": "0.1.3",
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.2.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
  }