@defra/lis-hubs-infra-access 0.2.0 → 0.3.0-lreg-176.alpha.7

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defra/lis-hubs-infra-access",
3
- "version": "0.2.0",
3
+ "version": "0.3.0-lreg-176.alpha.7",
4
4
  "description": "Shared hub access and capability resolution for the livestock platform.",
5
5
  "main": "src/index.js",
6
6
  "repository": {
@@ -33,18 +33,20 @@
33
33
  "author": "Defra DDTS",
34
34
  "license": "OGL-UK-3.0",
35
35
  "dependencies": {
36
+ "@defra/hapi-auth-oidc": "^0.5.6",
36
37
  "@defra/lis-hubs-infra-core": "^0.2.0",
37
38
  "@defra/lis-hubs-infra-registry": "^0.1.0",
38
- "jose": "6.2.8",
39
+ "convict": "6.2.5",
40
+ "convict-format-with-validator": "6.2.0",
39
41
  "eslint-plugin-jsdoc": "^63.0.8",
40
42
  "eslint-plugin-sonarjs": "^4.1.0",
43
+ "jose": "6.2.8",
41
44
  "neostandard": "0.13.0",
42
- "convict": "6.2.5",
43
- "convict-format-with-validator": "6.2.0"
45
+ "openid-client": "^6.8.2"
44
46
  },
45
47
  "peerDependencies": {
46
- "eslint": "^9.0.0",
47
- "@hapi/wreck": "18.1.2"
48
+ "@hapi/wreck": "18.1.2",
49
+ "eslint": "^9.0.0"
48
50
  },
49
51
  "devDependencies": {
50
52
  "@defra/lis-infra-eslint-config": "^0.6.0",
@@ -0,0 +1,54 @@
1
+ import * as openidClient from 'openid-client'
2
+
3
+ import { createHubAuthFlow, setHubAuthFlow } from '../session.js'
4
+ import { getReturnUrlFromRequest } from '../tokens.js'
5
+
6
+ function getRedirectUri(provider, hubOrigin) {
7
+ return new URL(provider.redirectPath, hubOrigin).toString()
8
+ }
9
+
10
+ /**
11
+ * Starts a hub login: stores a fresh PKCE/state/nonce flow in the session
12
+ * and builds the provider's authorization URL to redirect the user to.
13
+ * @param {object} options
14
+ * @param {object} options.oidcConfig - The resolved `openid-client` config.
15
+ * @param {object} options.provider - The provider config (redirectPath, serviceId?).
16
+ * @param {string} options.hubOrigin - The hub's public origin.
17
+ * @param {object} options.request - The Hapi request, for its session.
18
+ * @returns {Promise<string>} The provider's authorization URL.
19
+ */
20
+ export async function buildAuthorizationUrl({
21
+ oidcConfig,
22
+ provider,
23
+ hubOrigin,
24
+ request
25
+ }) {
26
+ const authFlow = createHubAuthFlow({
27
+ returnUrl: getReturnUrlFromRequest(request)
28
+ })
29
+
30
+ setHubAuthFlow(request, authFlow)
31
+
32
+ const codeChallenge = await openidClient.calculatePKCECodeChallenge(
33
+ authFlow.codeVerifier
34
+ )
35
+ const parameters = {
36
+ redirect_uri: getRedirectUri(provider, hubOrigin),
37
+ scope: 'openid',
38
+ state: authFlow.state,
39
+ nonce: authFlow.nonce,
40
+ code_challenge: codeChallenge,
41
+ code_challenge_method: 'S256'
42
+ }
43
+
44
+ if (provider.serviceId) {
45
+ parameters.serviceId = provider.serviceId
46
+ }
47
+
48
+ const authorizationUrl = openidClient.buildAuthorizationUrl(
49
+ oidcConfig,
50
+ parameters
51
+ )
52
+
53
+ return authorizationUrl.toString()
54
+ }
@@ -0,0 +1,22 @@
1
+ import { getHubAuthSession } from '../session.js'
2
+
3
+ /**
4
+ * Builds the provider's logout URL for the current hub session.
5
+ * @param {object} options
6
+ * @param {object} options.metadata - The resolved OIDC server metadata.
7
+ * @param {string} options.hubOrigin - The hub's public origin.
8
+ * @param {object} options.request - The Hapi request, for its session.
9
+ * @returns {string} The provider's end-session URL.
10
+ */
11
+ export function buildLogoutUrl({ metadata, hubOrigin, request }) {
12
+ const authSession = getHubAuthSession(request)
13
+ const logoutUrl = new URL(metadata.end_session_endpoint)
14
+
15
+ logoutUrl.searchParams.set('post_logout_redirect_uri', hubOrigin)
16
+
17
+ if (authSession?.idToken) {
18
+ logoutUrl.searchParams.set('id_token_hint', authSession.idToken)
19
+ }
20
+
21
+ return logoutUrl.toString()
22
+ }
@@ -0,0 +1,99 @@
1
+ import * as openidClient from 'openid-client'
2
+
3
+ import { clearHubAuthFlow, getHubAuthFlow } from '../session.js'
4
+ import { sanitizeReturnUrl } from '../tokens.js'
5
+
6
+ function getCurrentCallbackUrl(request, hubOrigin) {
7
+ const url = new URL(hubOrigin)
8
+ url.pathname = request.path
9
+ url.search = request.url.search
10
+
11
+ return url
12
+ }
13
+
14
+ function validateServiceIdClaim(claims, provider) {
15
+ if (
16
+ provider.serviceId &&
17
+ claims.serviceId &&
18
+ claims.serviceId !== provider.serviceId
19
+ ) {
20
+ throw new Error('Unexpected serviceId claim')
21
+ }
22
+ }
23
+
24
+ function exchangeAuthorizationCode({
25
+ oidcConfig,
26
+ request,
27
+ hubOrigin,
28
+ provider,
29
+ authFlow
30
+ }) {
31
+ const tokenEndpointParameters = provider.serviceId
32
+ ? { serviceId: provider.serviceId }
33
+ : undefined
34
+
35
+ return openidClient.authorizationCodeGrant(
36
+ oidcConfig,
37
+ getCurrentCallbackUrl(request, hubOrigin),
38
+ {
39
+ pkceCodeVerifier: authFlow.codeVerifier,
40
+ expectedState: authFlow.state,
41
+ expectedNonce: authFlow.nonce,
42
+ idTokenExpected: true
43
+ },
44
+ tokenEndpointParameters
45
+ )
46
+ }
47
+
48
+ /**
49
+ * Completes a hub login: exchanges the authorization code for tokens,
50
+ * validates the flow and serviceId claim, and maps the user.
51
+ * @param {object} options
52
+ * @param {object} options.oidcConfig - The resolved `openid-client` config.
53
+ * @param {object} options.provider - The provider config (serviceId?).
54
+ * @param {string} options.hubOrigin - The hub's public origin.
55
+ * @param {(claims: object, context: { providerConfig: object }) => object} options.mapUser
56
+ * Maps verified ID token claims to the hub's user shape.
57
+ * @param {object} options.request - The Hapi request, for its session.
58
+ * @returns {Promise<object>} `{ user, authSession, accessToken, returnUrl }`.
59
+ */
60
+ export async function completeAuthorizationCodeGrant({
61
+ oidcConfig,
62
+ provider,
63
+ hubOrigin,
64
+ mapUser,
65
+ request
66
+ }) {
67
+ const authFlow = getHubAuthFlow(request)
68
+
69
+ if (!authFlow?.state || !authFlow?.nonce || !authFlow?.codeVerifier) {
70
+ throw new Error('Authentication flow session was not found')
71
+ }
72
+
73
+ const tokenSet = await exchangeAuthorizationCode({
74
+ oidcConfig,
75
+ request,
76
+ hubOrigin,
77
+ provider,
78
+ authFlow
79
+ })
80
+
81
+ const claims = tokenSet.claims()
82
+ validateServiceIdClaim(claims, provider)
83
+
84
+ const user = mapUser(claims, { providerConfig: provider })
85
+ const authSession = {
86
+ ...user,
87
+ idToken: tokenSet.id_token,
88
+ authenticatedAt: new Date().toISOString()
89
+ }
90
+
91
+ clearHubAuthFlow(request)
92
+
93
+ return {
94
+ user,
95
+ authSession,
96
+ accessToken: tokenSet.access_token ?? null,
97
+ returnUrl: sanitizeReturnUrl(authFlow.returnUrl)
98
+ }
99
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Builds the client_secret_post auth provider used when a provider config
3
+ * doesn't supply its own `authProvider`.
4
+ * @param {object} provider - The provider config, for its `clientSecret`.
5
+ * @returns {object} An `@defra/hapi-auth-oidc` auth provider.
6
+ */
7
+ export function defaultAuthProvider(provider) {
8
+ return {
9
+ type: 'client_secret',
10
+ getCredentials: async () => provider.clientSecret
11
+ }
12
+ }
package/src/auth/oidc.js CHANGED
@@ -1,330 +1,52 @@
1
- import crypto from 'node:crypto'
1
+ import { createOidcConfig } from '@defra/hapi-auth-oidc'
2
2
 
3
- import { createRemoteJWKSet, jwtVerify } from 'jose'
4
-
5
- import {
6
- clearHubAuthFlow,
7
- createHubAuthFlow,
8
- getHubAuthFlow,
9
- getHubAuthSession,
10
- setHubAuthFlow
11
- } from './session.js'
12
- import { getReturnUrlFromRequest, sanitizeReturnUrl } from './tokens.js'
13
-
14
- async function fetchJson(url, options = {}) {
15
- const response = await fetch(url, options)
16
-
17
- if (!response.ok) {
18
- throw new Error(`Failed to fetch ${url}: ${response.status}`)
19
- }
20
-
21
- return response.json()
22
- }
23
-
24
- function createProviderResolver({ getProviderConfig, getPrimaryProviderId }) {
25
- function resolveProviderId(providerId) {
26
- const resolvedProviderId = providerId ?? getPrimaryProviderId?.()
27
-
28
- if (!resolvedProviderId) {
29
- throw new Error('Authentication provider id is required')
30
- }
31
-
32
- return resolvedProviderId
33
- }
34
-
35
- return function resolveProviderConfig(providerId) {
36
- const resolvedProviderId = resolveProviderId(providerId)
37
- const providerConfig = getProviderConfig(resolvedProviderId)
38
-
39
- if (!providerConfig?.discoveryUrl) {
40
- throw new Error(
41
- `OIDC discovery URL is not configured for provider ${resolvedProviderId}`
42
- )
43
- }
44
-
45
- return { providerId: resolvedProviderId, ...providerConfig }
46
- }
47
- }
48
-
49
- function createMetadataLoader(resolveProviderConfig) {
50
- const providerMetadata = new Map()
51
-
52
- return async function getOidcMetadata(providerId) {
53
- const providerConfig = resolveProviderConfig(providerId)
54
-
55
- if (!providerMetadata.has(providerConfig.providerId)) {
56
- providerMetadata.set(
57
- providerConfig.providerId,
58
- fetchJson(providerConfig.discoveryUrl)
59
- )
60
- }
61
-
62
- return providerMetadata.get(providerConfig.providerId)
63
- }
64
- }
65
-
66
- function createRedirectUriResolver(resolveProviderConfig, getHubOrigin) {
67
- return function getRedirectUri(providerId) {
68
- const providerConfig = resolveProviderConfig(providerId)
69
- return new URL(providerConfig.redirectPath, getHubOrigin()).toString()
70
- }
71
- }
72
-
73
- function createCodeExchanger({
74
- resolveProviderConfig,
75
- getOidcMetadata,
76
- getRedirectUri
77
- }) {
78
- return async function exchangeCodeForTokens(providerId, code, codeVerifier) {
79
- const providerConfig = resolveProviderConfig(providerId)
80
- const metadata = await getOidcMetadata(providerConfig.providerId)
81
- const body = new URLSearchParams({
82
- grant_type: 'authorization_code',
83
- code,
84
- redirect_uri: getRedirectUri(providerConfig.providerId),
85
- client_id: providerConfig.clientId,
86
- client_secret: providerConfig.clientSecret,
87
- code_verifier: codeVerifier
88
- })
89
-
90
- if (providerConfig.serviceId) {
91
- body.set('serviceId', providerConfig.serviceId)
92
- }
93
-
94
- return fetchJson(metadata.token_endpoint, {
95
- method: 'POST',
96
- headers: { 'content-type': 'application/x-www-form-urlencoded' },
97
- body
98
- })
99
- }
100
- }
101
-
102
- function addAuthorizationParameters(
103
- authorizationUrl,
104
- { providerConfig, redirectUri, authFlow }
105
- ) {
106
- const parameters = {
107
- client_id: providerConfig.clientId,
108
- response_type: 'code',
109
- scope: 'openid',
110
- redirect_uri: redirectUri,
111
- state: authFlow.state,
112
- nonce: authFlow.nonce,
113
- code_challenge: crypto
114
- .createHash('sha256')
115
- .update(authFlow.codeVerifier)
116
- .digest('base64url'),
117
- code_challenge_method: 'S256'
118
- }
119
-
120
- for (const [name, value] of Object.entries(parameters)) {
121
- authorizationUrl.searchParams.set(name, value)
122
- }
123
-
124
- if (providerConfig.serviceId) {
125
- authorizationUrl.searchParams.set('serviceId', providerConfig.serviceId)
126
- }
127
- }
128
-
129
- function createAuthorizationUrlBuilder({
130
- resolveProviderConfig,
131
- getOidcMetadata,
132
- getRedirectUri
133
- }) {
134
- return async function buildAuthorizationUrl(request, providerId) {
135
- const providerConfig = resolveProviderConfig(providerId)
136
- const metadata = await getOidcMetadata(providerConfig.providerId)
137
- const authFlow = {
138
- ...createHubAuthFlow({ returnUrl: getReturnUrlFromRequest(request) }),
139
- providerId: providerConfig.providerId
140
- }
141
-
142
- setHubAuthFlow(request, authFlow)
143
-
144
- const authorizationUrl = new URL(metadata.authorization_endpoint)
145
- addAuthorizationParameters(authorizationUrl, {
146
- providerConfig,
147
- redirectUri: getRedirectUri(providerConfig.providerId),
148
- authFlow
149
- })
150
- return authorizationUrl.toString()
151
- }
152
- }
153
-
154
- function resolveAuthorizationFlow(request, getPrimaryProviderId) {
155
- const authFlow = getHubAuthFlow(request)
156
- const providerId = authFlow?.providerId ?? getPrimaryProviderId?.()
157
-
158
- if (
159
- !authFlow?.state ||
160
- !authFlow?.nonce ||
161
- !authFlow?.codeVerifier ||
162
- !providerId
163
- ) {
164
- throw new Error('Authentication flow session was not found')
165
- }
166
-
167
- return { authFlow, providerId }
168
- }
169
-
170
- function validateAuthorizationResponse(request, authFlow) {
171
- if (request.query?.state !== authFlow.state) {
172
- throw new Error('State mismatch')
173
- }
174
-
175
- if (!request.query?.code) {
176
- throw new Error('Authorization code was not returned')
177
- }
178
- }
179
-
180
- function validateTokenResponse(tokens) {
181
- if (!tokens.id_token) {
182
- throw new Error('Token response did not include an ID token')
183
- }
184
- }
185
-
186
- function validateIdTokenClaims(payload, authFlow, providerConfig) {
187
- if (payload.nonce !== authFlow.nonce) {
188
- throw new Error('Nonce mismatch')
189
- }
190
-
191
- if (
192
- providerConfig.serviceId &&
193
- payload.serviceId &&
194
- payload.serviceId !== providerConfig.serviceId
195
- ) {
196
- throw new Error('Unexpected serviceId claim')
197
- }
198
- }
199
-
200
- function createIdTokenVerifier() {
201
- const providerJwks = new Map()
202
-
203
- return async function verifyIdToken(tokens, providerConfig, metadata) {
204
- if (!providerJwks.has(providerConfig.providerId)) {
205
- providerJwks.set(
206
- providerConfig.providerId,
207
- createRemoteJWKSet(new URL(metadata.jwks_uri))
208
- )
209
- }
210
-
211
- return jwtVerify(
212
- tokens.id_token,
213
- providerJwks.get(providerConfig.providerId),
214
- { issuer: metadata.issuer, audience: providerConfig.clientId }
215
- )
216
- }
217
- }
218
-
219
- function createAuthorizationCodeCompleter({
220
- getPrimaryProviderId,
221
- resolveProviderConfig,
222
- getOidcMetadata,
223
- exchangeCodeForTokens,
224
- verifyIdToken,
225
- mapUser
226
- }) {
227
- return async function completeAuthorizationCodeGrant(request) {
228
- const { authFlow, providerId } = resolveAuthorizationFlow(
229
- request,
230
- getPrimaryProviderId
231
- )
232
- validateAuthorizationResponse(request, authFlow)
233
-
234
- const providerConfig = resolveProviderConfig(providerId)
235
- const metadata = await getOidcMetadata(providerConfig.providerId)
236
- const tokens = await exchangeCodeForTokens(
237
- providerConfig.providerId,
238
- request.query.code,
239
- authFlow.codeVerifier
240
- )
241
- validateTokenResponse(tokens)
242
-
243
- const { payload } = await verifyIdToken(tokens, providerConfig, metadata)
244
- validateIdTokenClaims(payload, authFlow, providerConfig)
245
-
246
- const user = mapUser(payload, {
247
- providerId: providerConfig.providerId,
248
- providerConfig
249
- })
250
- const authSession = {
251
- ...user,
252
- idToken: tokens.id_token,
253
- authenticatedAt: new Date().toISOString()
254
- }
255
-
256
- clearHubAuthFlow(request)
257
-
258
- return {
259
- user,
260
- authSession,
261
- accessToken: tokens.access_token ?? null,
262
- providerId: providerConfig.providerId,
263
- returnUrl: sanitizeReturnUrl(authFlow.returnUrl)
264
- }
265
- }
266
- }
267
-
268
- function createLogoutUrlBuilder({
269
- getPrimaryProviderId,
270
- getOidcMetadata,
271
- getHubOrigin
272
- }) {
273
- return async function buildLogoutUrl(request) {
274
- const authSession = getHubAuthSession(request)
275
- const providerId = authSession?.authProvider ?? getPrimaryProviderId?.()
276
- const metadata = await getOidcMetadata(providerId)
277
- const logoutUrl = new URL(metadata.end_session_endpoint)
278
-
279
- logoutUrl.searchParams.set('post_logout_redirect_uri', getHubOrigin())
280
-
281
- if (authSession?.idToken) {
282
- logoutUrl.searchParams.set('id_token_hint', authSession.idToken)
283
- }
284
-
285
- return logoutUrl.toString()
286
- }
287
- }
3
+ import { buildAuthorizationUrl } from './oidc/build-authorization-url.js'
4
+ import { buildLogoutUrl } from './oidc/build-logout-url.js'
5
+ import { completeAuthorizationCodeGrant } from './oidc/complete-authorization-code-grant.js'
6
+ import { defaultAuthProvider } from './oidc/default-auth-provider.js'
288
7
 
289
8
  /**
290
- * Creates the OIDC operations used by the hub authentication plugin.
291
- * @param {object} options OIDC client dependencies.
292
- * @returns {object} OIDC client operations.
9
+ * Creates the OIDC operations used by the hub authentication plugin, for a
10
+ * single, statically-configured provider. Discovery happens once, here,
11
+ * before the client is returned - the hub awaits this at server boot.
12
+ *
13
+ * Client authentication defaults to client_secret_post. The provider config
14
+ * can opt into federated credentials instead by supplying its own
15
+ * `authProvider: { type: 'federated', getCredentials }` (e.g. an
16
+ * `@defra/hapi-auth-oidc` WebIdentityTokenProvider or MockProvider) - this
17
+ * package just passes it through to createOidcConfig unchanged.
18
+ *
19
+ * @param {object} options
20
+ * @param {object} options.provider
21
+ * `{ discoveryUrl, clientId, clientSecret, redirectPath, serviceId?, authProvider? }`.
22
+ * @param {string} options.hubOrigin
23
+ * The hub's own public origin, used to build redirect/logout URIs.
24
+ * @param {(claims: object, context: { providerConfig: object }) => object} options.mapUser
25
+ * Maps verified ID token claims to the hub's user shape.
26
+ * @returns {Promise<object>} OIDC client operations.
293
27
  */
294
- export function createOidcClient(options) {
295
- const { getProviderConfig, getPrimaryProviderId, getHubOrigin, mapUser } =
296
- options
297
- const resolveProviderConfig = createProviderResolver({
298
- getProviderConfig,
299
- getPrimaryProviderId
28
+ export async function createOidcClient({ provider, hubOrigin, mapUser }) {
29
+ const oidcConfig = await createOidcConfig({
30
+ discoveryUri: provider.discoveryUrl,
31
+ clientId: provider.clientId,
32
+ authProvider: provider.authProvider ?? defaultAuthProvider(provider)
300
33
  })
301
- const getOidcMetadata = createMetadataLoader(resolveProviderConfig)
302
- const getRedirectUri = createRedirectUriResolver(
303
- resolveProviderConfig,
304
- getHubOrigin
305
- )
306
- const sharedDependencies = {
307
- resolveProviderConfig,
308
- getOidcMetadata,
309
- getRedirectUri
310
- }
311
- const exchangeCodeForTokens = createCodeExchanger(sharedDependencies)
34
+ const metadata = oidcConfig.serverMetadata()
312
35
 
313
36
  return {
314
- buildAuthorizationUrl: createAuthorizationUrlBuilder(sharedDependencies),
315
- buildLogoutUrl: createLogoutUrlBuilder({
316
- getPrimaryProviderId,
317
- getOidcMetadata,
318
- getHubOrigin
319
- }),
320
- completeAuthorizationCodeGrant: createAuthorizationCodeCompleter({
321
- getPrimaryProviderId,
322
- resolveProviderConfig,
323
- getOidcMetadata,
324
- exchangeCodeForTokens,
325
- verifyIdToken: createIdTokenVerifier(),
326
- mapUser
327
- }),
328
- getOidcMetadata
37
+ buildAuthorizationUrl: (request) =>
38
+ buildAuthorizationUrl({ oidcConfig, provider, hubOrigin, request }),
39
+
40
+ completeAuthorizationCodeGrant: (request) =>
41
+ completeAuthorizationCodeGrant({
42
+ oidcConfig,
43
+ provider,
44
+ hubOrigin,
45
+ mapUser,
46
+ request
47
+ }),
48
+
49
+ buildLogoutUrl: (request) =>
50
+ buildLogoutUrl({ metadata, hubOrigin, request })
329
51
  }
330
52
  }
@@ -1,3 +1,4 @@
1
+ import { createOidcClient } from './oidc.js'
1
2
  import {
2
3
  clearHubAuthSession,
3
4
  getHubAuthSession,
@@ -17,7 +18,6 @@ function createLoginController({
17
18
  getCookieOptions,
18
19
  getHubJwtConfig,
19
20
  getHubJwtCookieName,
20
- providerId,
21
21
  buildAuthorizationUrl
22
22
  }) {
23
23
  return {
@@ -36,15 +36,10 @@ function createLoginController({
36
36
  .state(getHubJwtCookieName(), jwt, getCookieOptions())
37
37
  }
38
38
 
39
- const resolvedProviderId =
40
- typeof providerId === 'function' ? providerId() : providerId
41
39
  let authorizationUrl
42
40
 
43
41
  try {
44
- authorizationUrl = await buildAuthorizationUrl(
45
- request,
46
- resolvedProviderId
47
- )
42
+ authorizationUrl = await buildAuthorizationUrl(request)
48
43
  } catch (error) {
49
44
  request.logger?.error?.(error)
50
45
 
@@ -135,7 +130,9 @@ export function createHubCookieOptions({ ttlSeconds, isSecure }) {
135
130
  }
136
131
 
137
132
  /**
138
- * Creates a Hapi plugin for hub authentication with OIDC support.
133
+ * Creates a Hapi plugin for hub authentication with OIDC support. Builds its
134
+ * own OIDC client from the given provider config - see createOidcClient's
135
+ * JSDoc for what `provider`/`hubOrigin`/`mapUser` should look like.
139
136
  *
140
137
  * @param {object} options - Plugin configuration options.
141
138
  * @param {string} [options.pluginName='auth'] - Name of the plugin.
@@ -143,23 +140,35 @@ export function createHubCookieOptions({ ttlSeconds, isSecure }) {
143
140
  * @param {Function} options.getCookieOptions - Function that returns cookie options.
144
141
  * @param {Function} options.getHubJwtConfig - Function that returns JWT configuration.
145
142
  * @param {Function} options.resolveAuthSession - Function to resolve and enrich auth session with authorization data.
146
- * @param {Function} options.buildAuthorizationUrl - Function to build OIDC authorization URL.
147
- * @param {Function} options.completeAuthorizationCodeGrant - Function to complete OIDC authorization code flow.
148
- * @param {Function} options.buildLogoutUrl - Function to build logout URL.
149
- * @param {Array<{path: string, providerId: string|Function}>} options.loginRoutes - Array of login route configurations.
150
- * @returns {{plugin: {name: string, register: Function}}} Hapi plugin object with registration function.
143
+ * @param {object} options.provider - The OIDC provider config passed to createOidcClient.
144
+ * @param {string} options.hubOrigin - The hub's own public origin, passed to createOidcClient.
145
+ * @param {Function} options.mapUser - Maps verified ID token claims to the hub's user shape.
146
+ * @param {string} options.loginPath - Path to register the login route on.
147
+ * @returns {Promise<{plugin: {name: string, register: Function}}>} Hapi plugin object with registration function.
151
148
  */
152
- export function createHubAuthPlugin({
149
+ export async function createHubAuthPlugin({
153
150
  pluginName = 'auth',
154
151
  getHubJwtCookieName,
155
152
  getCookieOptions,
156
153
  getHubJwtConfig,
157
154
  resolveAuthSession,
158
- buildAuthorizationUrl,
159
- completeAuthorizationCodeGrant,
160
- buildLogoutUrl,
161
- loginRoutes
155
+ provider,
156
+ hubOrigin,
157
+ mapUser,
158
+ loginPath
162
159
  }) {
160
+ const {
161
+ buildAuthorizationUrl,
162
+ completeAuthorizationCodeGrant,
163
+ buildLogoutUrl
164
+ } = await createOidcClient({ provider, hubOrigin, mapUser })
165
+
166
+ const loginController = createLoginController({
167
+ getCookieOptions,
168
+ getHubJwtConfig,
169
+ getHubJwtCookieName,
170
+ buildAuthorizationUrl
171
+ })
163
172
  const callbackController = createCallbackController({
164
173
  getCookieOptions,
165
174
  getHubJwtConfig,
@@ -191,17 +200,11 @@ export function createHubAuthPlugin({
191
200
  })
192
201
 
193
202
  server.route([
194
- ...loginRoutes.map(({ path, providerId }) => ({
203
+ {
195
204
  method: 'GET',
196
- path,
197
- ...createLoginController({
198
- getCookieOptions,
199
- getHubJwtConfig,
200
- getHubJwtCookieName,
201
- providerId,
202
- buildAuthorizationUrl
203
- })
204
- })),
205
+ path: loginPath,
206
+ ...loginController
207
+ },
205
208
  {
206
209
  method: 'GET',
207
210
  path: '/sso',
package/src/auth.js CHANGED
@@ -1,5 +1,3 @@
1
- export { createOidcClient } from './auth/oidc.js'
2
-
3
1
  export { createHubAuthPlugin, createHubCookieOptions } from './auth/plugin.js'
4
2
 
5
3
  export {