@backstage/plugin-auth-backend 0.18.8 → 0.18.9-next.2

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/dist/index.cjs.js CHANGED
@@ -2,26 +2,27 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ var backendPluginApi = require('@backstage/backend-plugin-api');
6
+ var pluginAuthNode = require('@backstage/plugin-auth-node');
7
+ var alpha = require('@backstage/plugin-catalog-node/alpha');
5
8
  var express = require('express');
6
9
  var Router = require('express-promise-router');
7
10
  var cookieParser = require('cookie-parser');
8
11
  var OAuth2Strategy = require('passport-oauth2');
9
- var errors = require('@backstage/errors');
10
- var pickBy = require('lodash/pickBy');
11
12
  var crypto = require('crypto');
12
13
  var url = require('url');
14
+ var errors = require('@backstage/errors');
13
15
  var jwtDecoder = require('jwt-decode');
14
16
  var Auth0InternalStrategy = require('passport-auth0');
15
17
  var fetch = require('node-fetch');
16
18
  var NodeCache = require('node-cache');
17
19
  var jose = require('jose');
18
20
  var passportBitbucketOauth2 = require('passport-bitbucket-oauth2');
19
- var googleAuthLibrary = require('google-auth-library');
20
- var passportGithub2 = require('passport-github2');
21
- var passportGitlab2 = require('passport-gitlab2');
22
- var passportGoogleOauth20 = require('passport-google-oauth20');
21
+ var pluginAuthBackendModuleGcpIapProvider = require('@backstage/plugin-auth-backend-module-gcp-iap-provider');
22
+ var pluginAuthBackendModuleGithubProvider = require('@backstage/plugin-auth-backend-module-github-provider');
23
+ var pluginAuthBackendModuleGitlabProvider = require('@backstage/plugin-auth-backend-module-gitlab-provider');
24
+ var pluginAuthBackendModuleGoogleProvider = require('@backstage/plugin-auth-backend-module-google-provider');
23
25
  var passportMicrosoft = require('passport-microsoft');
24
- var pluginAuthNode = require('@backstage/plugin-auth-node');
25
26
  var openidClient = require('openid-client');
26
27
  var passportOktaOauth = require('@davidzemon/passport-okta-oauth');
27
28
  var passportOneloginOauth = require('passport-onelogin-oauth');
@@ -63,7 +64,6 @@ var express__default = /*#__PURE__*/_interopDefaultLegacy(express);
63
64
  var Router__default = /*#__PURE__*/_interopDefaultLegacy(Router);
64
65
  var cookieParser__default = /*#__PURE__*/_interopDefaultLegacy(cookieParser);
65
66
  var OAuth2Strategy__default = /*#__PURE__*/_interopDefaultLegacy(OAuth2Strategy);
66
- var pickBy__default = /*#__PURE__*/_interopDefaultLegacy(pickBy);
67
67
  var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto);
68
68
  var crypto__namespace = /*#__PURE__*/_interopNamespace(crypto);
69
69
  var jwtDecoder__default = /*#__PURE__*/_interopDefaultLegacy(jwtDecoder);
@@ -74,10 +74,10 @@ var session__default = /*#__PURE__*/_interopDefaultLegacy(session);
74
74
  var connectSessionKnex__default = /*#__PURE__*/_interopDefaultLegacy(connectSessionKnex);
75
75
  var passport__default = /*#__PURE__*/_interopDefaultLegacy(passport);
76
76
 
77
- var __defProp$m = Object.defineProperty;
78
- var __defNormalProp$m = (obj, key, value) => key in obj ? __defProp$m(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
79
- var __publicField$m = (obj, key, value) => {
80
- __defNormalProp$m(obj, typeof key !== "symbol" ? key + "" : key, value);
77
+ var __defProp$i = Object.defineProperty;
78
+ var __defNormalProp$i = (obj, key, value) => key in obj ? __defProp$i(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
79
+ var __publicField$i = (obj, key, value) => {
80
+ __defNormalProp$i(obj, typeof key !== "symbol" ? key + "" : key, value);
81
81
  return value;
82
82
  };
83
83
  const defaultScopes = ["offline_access", "read:me"];
@@ -94,7 +94,7 @@ class AtlassianStrategy extends OAuth2Strategy__default["default"] {
94
94
  scope: Array.from(/* @__PURE__ */ new Set([...defaultScopes, ...scopes]))
95
95
  };
96
96
  super(optionsWithURLs, verify);
97
- __publicField$m(this, "profileURL");
97
+ __publicField$i(this, "profileURL");
98
98
  this.profileURL = "https://api.atlassian.com/me";
99
99
  this.name = "atlassian";
100
100
  this._oauth2.useAuthorizationHeaderforGET(true);
@@ -142,22 +142,10 @@ class AtlassianStrategy extends OAuth2Strategy__default["default"] {
142
142
  }
143
143
  }
144
144
 
145
- const readState = (stateString) => {
146
- var _a, _b;
147
- const state = Object.fromEntries(
148
- new URLSearchParams(Buffer.from(stateString, "hex").toString("utf-8"))
149
- );
150
- if (!state.nonce || !state.env || ((_a = state.nonce) == null ? void 0 : _a.length) === 0 || ((_b = state.env) == null ? void 0 : _b.length) === 0) {
151
- throw Error(`Invalid state passed via request`);
152
- }
153
- return state;
154
- };
155
- const encodeState = (state) => {
156
- const stateString = new URLSearchParams(
157
- pickBy__default["default"](state, (value) => value !== void 0)
158
- ).toString();
159
- return Buffer.from(stateString, "utf-8").toString("hex");
160
- };
145
+ const OAuthEnvironmentHandler = pluginAuthNode.OAuthEnvironmentHandler;
146
+
147
+ const readState = pluginAuthNode.decodeOAuthState;
148
+ const encodeState = pluginAuthNode.encodeOAuthState;
161
149
  const verifyNonce = (req, providerId) => {
162
150
  var _a, _b;
163
151
  const cookieNonce = req.cookies[`${providerId}-nonce`];
@@ -188,66 +176,6 @@ const defaultCookieConfigurer = ({
188
176
  return { domain, path, secure, sameSite };
189
177
  };
190
178
 
191
- class OAuthEnvironmentHandler {
192
- constructor(handlers) {
193
- this.handlers = handlers;
194
- }
195
- static mapConfig(config, factoryFunc) {
196
- const envs = config.keys();
197
- const handlers = /* @__PURE__ */ new Map();
198
- for (const env of envs) {
199
- const envConfig = config.getConfig(env);
200
- const handler = factoryFunc(envConfig);
201
- handlers.set(env, handler);
202
- }
203
- return new OAuthEnvironmentHandler(handlers);
204
- }
205
- async start(req, res) {
206
- const provider = this.getProviderForEnv(req);
207
- await provider.start(req, res);
208
- }
209
- async frameHandler(req, res) {
210
- const provider = this.getProviderForEnv(req);
211
- await provider.frameHandler(req, res);
212
- }
213
- async refresh(req, res) {
214
- var _a;
215
- const provider = this.getProviderForEnv(req);
216
- await ((_a = provider.refresh) == null ? void 0 : _a.call(provider, req, res));
217
- }
218
- async logout(req, res) {
219
- var _a;
220
- const provider = this.getProviderForEnv(req);
221
- await ((_a = provider.logout) == null ? void 0 : _a.call(provider, req, res));
222
- }
223
- getRequestFromEnv(req) {
224
- var _a, _b;
225
- const reqEnv = (_a = req.query.env) == null ? void 0 : _a.toString();
226
- if (reqEnv) {
227
- return reqEnv;
228
- }
229
- const stateParams = (_b = req.query.state) == null ? void 0 : _b.toString();
230
- if (!stateParams) {
231
- return void 0;
232
- }
233
- const env = readState(stateParams).env;
234
- return env;
235
- }
236
- getProviderForEnv(req) {
237
- const env = this.getRequestFromEnv(req);
238
- if (!env) {
239
- throw new errors.InputError(`Must specify 'env' query to select environment`);
240
- }
241
- const handler = this.handlers.get(env);
242
- if (!handler) {
243
- throw new errors.NotFoundError(
244
- `No configuration available for the '${env}' environment of this provider.`
245
- );
246
- }
247
- return handler;
248
- }
249
- }
250
-
251
179
  const safelyEncodeURIComponent = (value) => {
252
180
  return encodeURIComponent(value).replace(/'/g, "%27");
253
181
  };
@@ -279,26 +207,12 @@ const ensuresXRequestedWith = (req) => {
279
207
  return true;
280
208
  };
281
209
 
282
- function parseJwtPayload(token) {
283
- const [_header, payload, _signature] = token.split(".");
284
- return JSON.parse(Buffer.from(payload, "base64").toString());
285
- }
286
- function prepareBackstageIdentityResponse(result) {
287
- const { sub, ent } = parseJwtPayload(result.token);
288
- return {
289
- ...result,
290
- identity: {
291
- type: "user",
292
- userEntityRef: sub,
293
- ownershipEntityRefs: ent != null ? ent : []
294
- }
295
- };
296
- }
210
+ const prepareBackstageIdentityResponse = pluginAuthNode.prepareBackstageIdentityResponse;
297
211
 
298
- var __defProp$l = Object.defineProperty;
299
- var __defNormalProp$l = (obj, key, value) => key in obj ? __defProp$l(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
300
- var __publicField$l = (obj, key, value) => {
301
- __defNormalProp$l(obj, typeof key !== "symbol" ? key + "" : key, value);
212
+ var __defProp$h = Object.defineProperty;
213
+ var __defNormalProp$h = (obj, key, value) => key in obj ? __defProp$h(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
214
+ var __publicField$h = (obj, key, value) => {
215
+ __defNormalProp$h(obj, typeof key !== "symbol" ? key + "" : key, value);
302
216
  return value;
303
217
  };
304
218
  const THOUSAND_DAYS_MS = 1e3 * 24 * 60 * 60 * 1e3;
@@ -307,8 +221,8 @@ class OAuthAdapter {
307
221
  constructor(handlers, options) {
308
222
  this.handlers = handlers;
309
223
  this.options = options;
310
- __publicField$l(this, "baseCookieOptions");
311
- __publicField$l(this, "setNonceCookie", (res, nonce, cookieConfig) => {
224
+ __publicField$h(this, "baseCookieOptions");
225
+ __publicField$h(this, "setNonceCookie", (res, nonce, cookieConfig) => {
312
226
  res.cookie(`${this.options.providerId}-nonce`, nonce, {
313
227
  maxAge: TEN_MINUTES_MS,
314
228
  ...this.baseCookieOptions,
@@ -316,34 +230,34 @@ class OAuthAdapter {
316
230
  path: `${cookieConfig.path}/handler`
317
231
  });
318
232
  });
319
- __publicField$l(this, "setGrantedScopeCookie", (res, scope, cookieConfig) => {
233
+ __publicField$h(this, "setGrantedScopeCookie", (res, scope, cookieConfig) => {
320
234
  res.cookie(`${this.options.providerId}-granted-scope`, scope, {
321
235
  maxAge: THOUSAND_DAYS_MS,
322
236
  ...this.baseCookieOptions,
323
237
  ...cookieConfig
324
238
  });
325
239
  });
326
- __publicField$l(this, "getRefreshTokenFromCookie", (req) => {
240
+ __publicField$h(this, "getRefreshTokenFromCookie", (req) => {
327
241
  return req.cookies[`${this.options.providerId}-refresh-token`];
328
242
  });
329
- __publicField$l(this, "getGrantedScopeFromCookie", (req) => {
243
+ __publicField$h(this, "getGrantedScopeFromCookie", (req) => {
330
244
  return req.cookies[`${this.options.providerId}-granted-scope`];
331
245
  });
332
- __publicField$l(this, "setRefreshTokenCookie", (res, refreshToken, cookieConfig) => {
246
+ __publicField$h(this, "setRefreshTokenCookie", (res, refreshToken, cookieConfig) => {
333
247
  res.cookie(`${this.options.providerId}-refresh-token`, refreshToken, {
334
248
  maxAge: THOUSAND_DAYS_MS,
335
249
  ...this.baseCookieOptions,
336
250
  ...cookieConfig
337
251
  });
338
252
  });
339
- __publicField$l(this, "removeRefreshTokenCookie", (res, cookieConfig) => {
253
+ __publicField$h(this, "removeRefreshTokenCookie", (res, cookieConfig) => {
340
254
  res.cookie(`${this.options.providerId}-refresh-token`, "", {
341
255
  maxAge: 0,
342
256
  ...this.baseCookieOptions,
343
257
  ...cookieConfig
344
258
  });
345
259
  });
346
- __publicField$l(this, "getCookieConfig", (origin) => {
260
+ __publicField$h(this, "getCookieConfig", (origin) => {
347
261
  return this.options.cookieConfigurer({
348
262
  providerId: this.options.providerId,
349
263
  baseUrl: this.options.baseUrl,
@@ -649,10 +563,10 @@ function createAuthProviderIntegration(config) {
649
563
  });
650
564
  }
651
565
 
652
- var __defProp$k = Object.defineProperty;
653
- var __defNormalProp$k = (obj, key, value) => key in obj ? __defProp$k(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
654
- var __publicField$k = (obj, key, value) => {
655
- __defNormalProp$k(obj, typeof key !== "symbol" ? key + "" : key, value);
566
+ var __defProp$g = Object.defineProperty;
567
+ var __defNormalProp$g = (obj, key, value) => key in obj ? __defProp$g(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
568
+ var __publicField$g = (obj, key, value) => {
569
+ __defNormalProp$g(obj, typeof key !== "symbol" ? key + "" : key, value);
656
570
  return value;
657
571
  };
658
572
  const atlassianDefaultAuthHandler = async ({
@@ -663,10 +577,10 @@ const atlassianDefaultAuthHandler = async ({
663
577
  });
664
578
  class AtlassianAuthProvider {
665
579
  constructor(options) {
666
- __publicField$k(this, "_strategy");
667
- __publicField$k(this, "signInResolver");
668
- __publicField$k(this, "authHandler");
669
- __publicField$k(this, "resolverContext");
580
+ __publicField$g(this, "_strategy");
581
+ __publicField$g(this, "signInResolver");
582
+ __publicField$g(this, "authHandler");
583
+ __publicField$g(this, "resolverContext");
670
584
  this.resolverContext = options.resolverContext;
671
585
  this.authHandler = options.authHandler;
672
586
  this.signInResolver = options.signInResolver;
@@ -784,21 +698,21 @@ class Auth0Strategy extends Auth0InternalStrategy__default["default"] {
784
698
  }
785
699
  }
786
700
 
787
- var __defProp$j = Object.defineProperty;
788
- var __defNormalProp$j = (obj, key, value) => key in obj ? __defProp$j(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
789
- var __publicField$j = (obj, key, value) => {
790
- __defNormalProp$j(obj, typeof key !== "symbol" ? key + "" : key, value);
701
+ var __defProp$f = Object.defineProperty;
702
+ var __defNormalProp$f = (obj, key, value) => key in obj ? __defProp$f(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
703
+ var __publicField$f = (obj, key, value) => {
704
+ __defNormalProp$f(obj, typeof key !== "symbol" ? key + "" : key, value);
791
705
  return value;
792
706
  };
793
707
  class Auth0AuthProvider {
794
708
  constructor(options) {
795
- __publicField$j(this, "_strategy");
796
- __publicField$j(this, "signInResolver");
797
- __publicField$j(this, "authHandler");
798
- __publicField$j(this, "resolverContext");
799
- __publicField$j(this, "audience");
800
- __publicField$j(this, "connection");
801
- __publicField$j(this, "connectionScope");
709
+ __publicField$f(this, "_strategy");
710
+ __publicField$f(this, "signInResolver");
711
+ __publicField$f(this, "authHandler");
712
+ __publicField$f(this, "resolverContext");
713
+ __publicField$f(this, "audience");
714
+ __publicField$f(this, "connection");
715
+ __publicField$f(this, "connectionScope");
802
716
  /**
803
717
  * Due to passport-auth0 forcing options.state = true,
804
718
  * passport-oauth2 requires express-session to be installed
@@ -807,7 +721,7 @@ class Auth0AuthProvider {
807
721
  * passport-oauth2, which is the StateStore implementation used when options.state = false,
808
722
  * allowing us to avoid using express-session in order to integrate with auth0.
809
723
  */
810
- __publicField$j(this, "store", {
724
+ __publicField$f(this, "store", {
811
725
  store(_req, cb) {
812
726
  cb(null, null);
813
727
  },
@@ -948,23 +862,23 @@ const auth0 = createAuthProviderIntegration({
948
862
  }
949
863
  });
950
864
 
951
- var __defProp$i = Object.defineProperty;
952
- var __defNormalProp$i = (obj, key, value) => key in obj ? __defProp$i(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
953
- var __publicField$i = (obj, key, value) => {
954
- __defNormalProp$i(obj, typeof key !== "symbol" ? key + "" : key, value);
865
+ var __defProp$e = Object.defineProperty;
866
+ var __defNormalProp$e = (obj, key, value) => key in obj ? __defProp$e(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
867
+ var __publicField$e = (obj, key, value) => {
868
+ __defNormalProp$e(obj, typeof key !== "symbol" ? key + "" : key, value);
955
869
  return value;
956
870
  };
957
871
  const ALB_JWT_HEADER = "x-amzn-oidc-data";
958
872
  const ALB_ACCESS_TOKEN_HEADER = "x-amzn-oidc-accesstoken";
959
873
  class AwsAlbAuthProvider {
960
874
  constructor(options) {
961
- __publicField$i(this, "region");
962
- __publicField$i(this, "issuer");
963
- __publicField$i(this, "resolverContext");
964
- __publicField$i(this, "keyCache");
965
- __publicField$i(this, "authHandler");
966
- __publicField$i(this, "signInResolver");
967
- __publicField$i(this, "getKey", async (header) => {
875
+ __publicField$e(this, "region");
876
+ __publicField$e(this, "issuer");
877
+ __publicField$e(this, "resolverContext");
878
+ __publicField$e(this, "keyCache");
879
+ __publicField$e(this, "authHandler");
880
+ __publicField$e(this, "signInResolver");
881
+ __publicField$e(this, "getKey", async (header) => {
968
882
  if (!header.kid) {
969
883
  throw new errors.AuthenticationError("No key id was specified in header");
970
884
  }
@@ -1092,18 +1006,18 @@ const awsAlb = createAuthProviderIntegration({
1092
1006
  }
1093
1007
  });
1094
1008
 
1095
- var __defProp$h = Object.defineProperty;
1096
- var __defNormalProp$h = (obj, key, value) => key in obj ? __defProp$h(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1097
- var __publicField$h = (obj, key, value) => {
1098
- __defNormalProp$h(obj, typeof key !== "symbol" ? key + "" : key, value);
1009
+ var __defProp$d = Object.defineProperty;
1010
+ var __defNormalProp$d = (obj, key, value) => key in obj ? __defProp$d(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1011
+ var __publicField$d = (obj, key, value) => {
1012
+ __defNormalProp$d(obj, typeof key !== "symbol" ? key + "" : key, value);
1099
1013
  return value;
1100
1014
  };
1101
1015
  class BitbucketAuthProvider {
1102
1016
  constructor(options) {
1103
- __publicField$h(this, "_strategy");
1104
- __publicField$h(this, "signInResolver");
1105
- __publicField$h(this, "authHandler");
1106
- __publicField$h(this, "resolverContext");
1017
+ __publicField$d(this, "_strategy");
1018
+ __publicField$d(this, "signInResolver");
1019
+ __publicField$d(this, "authHandler");
1020
+ __publicField$d(this, "resolverContext");
1107
1021
  this.signInResolver = options.signInResolver;
1108
1022
  this.authHandler = options.authHandler;
1109
1023
  this.resolverContext = options.resolverContext;
@@ -1271,10 +1185,10 @@ const commonByEmailResolver = async (info, ctx) => {
1271
1185
  });
1272
1186
  };
1273
1187
 
1274
- var __defProp$g = Object.defineProperty;
1275
- var __defNormalProp$g = (obj, key, value) => key in obj ? __defProp$g(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1276
- var __publicField$g = (obj, key, value) => {
1277
- __defNormalProp$g(obj, typeof key !== "symbol" ? key + "" : key, value);
1188
+ var __defProp$c = Object.defineProperty;
1189
+ var __defNormalProp$c = (obj, key, value) => key in obj ? __defProp$c(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1190
+ var __publicField$c = (obj, key, value) => {
1191
+ __defNormalProp$c(obj, typeof key !== "symbol" ? key + "" : key, value);
1278
1192
  return value;
1279
1193
  };
1280
1194
  const CF_JWT_HEADER = "cf-access-jwt-assertion";
@@ -1282,12 +1196,12 @@ const COOKIE_AUTH_NAME = "CF_Authorization";
1282
1196
  const CACHE_PREFIX = "providers/cloudflare-access/profile-v1";
1283
1197
  class CloudflareAccessAuthProvider {
1284
1198
  constructor(options) {
1285
- __publicField$g(this, "teamName");
1286
- __publicField$g(this, "resolverContext");
1287
- __publicField$g(this, "authHandler");
1288
- __publicField$g(this, "signInResolver");
1289
- __publicField$g(this, "jwtKeySet");
1290
- __publicField$g(this, "cache");
1199
+ __publicField$c(this, "teamName");
1200
+ __publicField$c(this, "resolverContext");
1201
+ __publicField$c(this, "authHandler");
1202
+ __publicField$c(this, "signInResolver");
1203
+ __publicField$c(this, "jwtKeySet");
1204
+ __publicField$c(this, "cache");
1291
1205
  this.teamName = options.teamName;
1292
1206
  this.authHandler = options.authHandler;
1293
1207
  this.signInResolver = options.signInResolver;
@@ -1365,628 +1279,224 @@ class CloudflareAccessAuthProvider {
1365
1279
  token: jwt
1366
1280
  };
1367
1281
  } catch (err) {
1368
- throw new errors.ForwardedError(
1369
- "Failed to populate access identity information",
1370
- err
1371
- );
1372
- }
1373
- }
1374
- async handleResult(result) {
1375
- const { profile } = await this.authHandler(result, this.resolverContext);
1376
- const backstageIdentity = await this.signInResolver(
1377
- {
1378
- result,
1379
- profile
1380
- },
1381
- this.resolverContext
1382
- );
1383
- return {
1384
- providerInfo: {
1385
- expiresInSeconds: result.expiresInSeconds,
1386
- claims: result.claims,
1387
- cfAccessIdentityProfile: result.cfIdentity
1388
- },
1389
- backstageIdentity: prepareBackstageIdentityResponse(backstageIdentity),
1390
- profile
1391
- };
1392
- }
1393
- }
1394
- const cfAccess = createAuthProviderIntegration({
1395
- create(options) {
1396
- return ({ config, resolverContext }) => {
1397
- const teamName = config.getString("teamName");
1398
- if (!options.signIn.resolver) {
1399
- throw new Error(
1400
- "SignInResolver is required to use this authentication provider"
1401
- );
1402
- }
1403
- const authHandler = (options == null ? void 0 : options.authHandler) ? options.authHandler : async ({ claims, cfIdentity }) => {
1404
- return {
1405
- profile: {
1406
- email: claims.email,
1407
- displayName: cfIdentity.name
1408
- }
1409
- };
1410
- };
1411
- return new CloudflareAccessAuthProvider({
1412
- teamName,
1413
- signInResolver: options == null ? void 0 : options.signIn.resolver,
1414
- authHandler,
1415
- resolverContext,
1416
- ...options.cache && { cache: options.cache }
1417
- });
1418
- };
1419
- },
1420
- resolvers: {
1421
- /**
1422
- * Looks up the user by matching their email to the entity email.
1423
- */
1424
- emailMatchingUserEntityProfileEmail: () => commonByEmailResolver
1425
- }
1426
- });
1427
-
1428
- function createTokenValidator(audience, mockClient) {
1429
- const client = mockClient != null ? mockClient : new googleAuthLibrary.OAuth2Client();
1430
- return async function tokenValidator(token) {
1431
- const response = await client.getIapPublicKeys();
1432
- const ticket = await client.verifySignedJwtWithCertsAsync(
1433
- token,
1434
- response.pubkeys,
1435
- audience,
1436
- ["https://cloud.google.com/iap"]
1437
- );
1438
- const payload = ticket.getPayload();
1439
- if (!payload) {
1440
- throw new TypeError("Token had no payload");
1441
- }
1442
- return payload;
1443
- };
1444
- }
1445
- async function parseRequestToken(jwtToken, tokenValidator) {
1446
- if (typeof jwtToken !== "string" || !jwtToken) {
1447
- throw new errors.AuthenticationError("Missing Google IAP header");
1448
- }
1449
- let payload;
1450
- try {
1451
- payload = await tokenValidator(jwtToken);
1452
- } catch (e) {
1453
- throw new errors.AuthenticationError(`Google IAP token verification failed, ${e}`);
1454
- }
1455
- if (!payload.sub || !payload.email) {
1456
- throw new errors.AuthenticationError(
1457
- "Google IAP token payload is missing sub and/or email claim"
1458
- );
1459
- }
1460
- return {
1461
- iapToken: {
1462
- ...payload,
1463
- sub: payload.sub,
1464
- email: payload.email
1465
- }
1466
- };
1467
- }
1468
- const defaultAuthHandler$1 = async ({
1469
- iapToken
1470
- }) => ({ profile: { email: iapToken.email } });
1471
-
1472
- const DEFAULT_IAP_JWT_HEADER = "x-goog-iap-jwt-assertion";
1473
-
1474
- var __defProp$f = Object.defineProperty;
1475
- var __defNormalProp$f = (obj, key, value) => key in obj ? __defProp$f(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1476
- var __publicField$f = (obj, key, value) => {
1477
- __defNormalProp$f(obj, typeof key !== "symbol" ? key + "" : key, value);
1478
- return value;
1479
- };
1480
- class GcpIapProvider {
1481
- constructor(options) {
1482
- __publicField$f(this, "authHandler");
1483
- __publicField$f(this, "signInResolver");
1484
- __publicField$f(this, "tokenValidator");
1485
- __publicField$f(this, "resolverContext");
1486
- __publicField$f(this, "jwtHeader");
1487
- this.authHandler = options.authHandler;
1488
- this.signInResolver = options.signInResolver;
1489
- this.tokenValidator = options.tokenValidator;
1490
- this.resolverContext = options.resolverContext;
1491
- this.jwtHeader = (options == null ? void 0 : options.jwtHeader) || DEFAULT_IAP_JWT_HEADER;
1492
- }
1493
- async start() {
1494
- }
1495
- async frameHandler() {
1496
- }
1497
- async refresh(req, res) {
1498
- const result = await parseRequestToken(
1499
- req.header(this.jwtHeader),
1500
- this.tokenValidator
1501
- );
1502
- const { profile } = await this.authHandler(result, this.resolverContext);
1503
- const backstageIdentity = await this.signInResolver(
1504
- { profile, result },
1505
- this.resolverContext
1506
- );
1507
- const response = {
1508
- providerInfo: { iapToken: result.iapToken },
1509
- profile,
1510
- backstageIdentity: prepareBackstageIdentityResponse(backstageIdentity)
1511
- };
1512
- res.json(response);
1513
- }
1514
- }
1515
- const gcpIap = createAuthProviderIntegration({
1516
- create(options) {
1517
- return ({ config, resolverContext }) => {
1518
- var _a;
1519
- const audience = config.getString("audience");
1520
- const jwtHeader = config.getOptionalString("jwtHeader");
1521
- const authHandler = (_a = options.authHandler) != null ? _a : defaultAuthHandler$1;
1522
- const signInResolver = options.signIn.resolver;
1523
- const tokenValidator = createTokenValidator(audience);
1524
- return new GcpIapProvider({
1525
- authHandler,
1526
- signInResolver,
1527
- tokenValidator,
1528
- resolverContext,
1529
- jwtHeader
1530
- });
1531
- };
1532
- }
1533
- });
1534
-
1535
- const BACKSTAGE_SESSION_EXPIRATION = 3600;
1536
-
1537
- var __defProp$e = Object.defineProperty;
1538
- var __defNormalProp$e = (obj, key, value) => key in obj ? __defProp$e(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1539
- var __publicField$e = (obj, key, value) => {
1540
- __defNormalProp$e(obj, typeof key !== "symbol" ? key + "" : key, value);
1541
- return value;
1542
- };
1543
- const ACCESS_TOKEN_PREFIX = "access-token.";
1544
- class GithubAuthProvider {
1545
- constructor(options) {
1546
- __publicField$e(this, "_strategy");
1547
- __publicField$e(this, "signInResolver");
1548
- __publicField$e(this, "authHandler");
1549
- __publicField$e(this, "resolverContext");
1550
- __publicField$e(this, "stateEncoder");
1551
- this.signInResolver = options.signInResolver;
1552
- this.authHandler = options.authHandler;
1553
- this.stateEncoder = options.stateEncoder;
1554
- this.resolverContext = options.resolverContext;
1555
- this._strategy = new passportGithub2.Strategy(
1556
- {
1557
- clientID: options.clientId,
1558
- clientSecret: options.clientSecret,
1559
- callbackURL: options.callbackUrl,
1560
- tokenURL: options.tokenUrl,
1561
- userProfileURL: options.userProfileUrl,
1562
- authorizationURL: options.authorizationUrl
1563
- },
1564
- (accessToken, refreshToken, params, fullProfile, done) => {
1565
- done(void 0, { fullProfile, params, accessToken }, { refreshToken });
1566
- }
1567
- );
1568
- }
1569
- async start(req) {
1570
- return await executeRedirectStrategy(req, this._strategy, {
1571
- scope: req.scope,
1572
- state: (await this.stateEncoder(req)).encodedState
1573
- });
1574
- }
1575
- async handler(req) {
1576
- const { result, privateInfo } = await executeFrameHandlerStrategy(req, this._strategy);
1577
- let refreshToken = privateInfo.refreshToken;
1578
- if (!refreshToken && !result.params.expires_in) {
1579
- refreshToken = ACCESS_TOKEN_PREFIX + result.accessToken;
1580
- }
1581
- return {
1582
- response: await this.handleResult(result),
1583
- refreshToken
1584
- };
1585
- }
1586
- async refresh(req) {
1587
- const { scope, refreshToken } = req;
1588
- if (refreshToken == null ? void 0 : refreshToken.startsWith(ACCESS_TOKEN_PREFIX)) {
1589
- const accessToken = refreshToken.slice(ACCESS_TOKEN_PREFIX.length);
1590
- const fullProfile = await executeFetchUserProfileStrategy(
1591
- this._strategy,
1592
- accessToken
1593
- ).catch((error) => {
1594
- var _a;
1595
- if (((_a = error.oauthError) == null ? void 0 : _a.statusCode) === 401) {
1596
- throw new Error("Invalid access token");
1597
- }
1598
- throw error;
1599
- });
1600
- return {
1601
- response: await this.handleResult({
1602
- fullProfile,
1603
- params: { scope },
1604
- accessToken
1605
- }),
1606
- refreshToken
1607
- };
1608
- }
1609
- const result = await executeRefreshTokenStrategy(
1610
- this._strategy,
1611
- refreshToken,
1612
- scope
1613
- );
1614
- return {
1615
- response: await this.handleResult({
1616
- fullProfile: await executeFetchUserProfileStrategy(
1617
- this._strategy,
1618
- result.accessToken
1619
- ),
1620
- params: { ...result.params, scope },
1621
- accessToken: result.accessToken
1622
- }),
1623
- refreshToken: result.refreshToken
1624
- };
1625
- }
1626
- async handleResult(result) {
1627
- const { profile } = await this.authHandler(result, this.resolverContext);
1628
- const expiresInStr = result.params.expires_in;
1629
- let expiresInSeconds = expiresInStr === void 0 ? void 0 : Number(expiresInStr);
1630
- let backstageIdentity = void 0;
1631
- if (this.signInResolver) {
1632
- backstageIdentity = await this.signInResolver(
1633
- {
1634
- result,
1635
- profile
1636
- },
1637
- this.resolverContext
1638
- );
1639
- if (expiresInSeconds) {
1640
- expiresInSeconds = Math.min(
1641
- expiresInSeconds,
1642
- BACKSTAGE_SESSION_EXPIRATION
1643
- );
1644
- } else {
1645
- expiresInSeconds = BACKSTAGE_SESSION_EXPIRATION;
1646
- }
1647
- }
1648
- return {
1649
- backstageIdentity,
1650
- providerInfo: {
1651
- accessToken: result.accessToken,
1652
- scope: result.params.scope,
1653
- expiresInSeconds
1654
- },
1655
- profile
1656
- };
1657
- }
1658
- }
1659
- const github = createAuthProviderIntegration({
1660
- create(options) {
1661
- return ({ providerId, globalConfig, config, resolverContext }) => OAuthEnvironmentHandler.mapConfig(config, (envConfig) => {
1662
- var _a, _b, _c;
1663
- const clientId = envConfig.getString("clientId");
1664
- const clientSecret = envConfig.getString("clientSecret");
1665
- const enterpriseInstanceUrl = (_a = envConfig.getOptionalString("enterpriseInstanceUrl")) == null ? void 0 : _a.replace(/\/$/, "");
1666
- const customCallbackUrl = envConfig.getOptionalString("callbackUrl");
1667
- const authorizationUrl = enterpriseInstanceUrl ? `${enterpriseInstanceUrl}/login/oauth/authorize` : void 0;
1668
- const tokenUrl = enterpriseInstanceUrl ? `${enterpriseInstanceUrl}/login/oauth/access_token` : void 0;
1669
- const userProfileUrl = enterpriseInstanceUrl ? `${enterpriseInstanceUrl}/api/v3/user` : void 0;
1670
- const callbackUrl = customCallbackUrl || `${globalConfig.baseUrl}/${providerId}/handler/frame`;
1671
- const authHandler = (options == null ? void 0 : options.authHandler) ? options.authHandler : async ({ fullProfile }) => ({
1672
- profile: makeProfileInfo(fullProfile)
1673
- });
1674
- const stateEncoder = (_b = options == null ? void 0 : options.stateEncoder) != null ? _b : async (req) => {
1675
- return { encodedState: encodeState(req.state) };
1676
- };
1677
- const provider = new GithubAuthProvider({
1678
- clientId,
1679
- clientSecret,
1680
- callbackUrl,
1681
- tokenUrl,
1682
- userProfileUrl,
1683
- authorizationUrl,
1684
- signInResolver: (_c = options == null ? void 0 : options.signIn) == null ? void 0 : _c.resolver,
1685
- authHandler,
1686
- stateEncoder,
1687
- resolverContext
1688
- });
1689
- return OAuthAdapter.fromConfig(globalConfig, provider, {
1690
- persistScopes: true,
1691
- providerId,
1692
- callbackUrl
1693
- });
1694
- });
1695
- },
1696
- resolvers: {
1697
- /**
1698
- * Looks up the user by matching their GitHub username to the entity name.
1699
- */
1700
- usernameMatchingUserEntityName: () => {
1701
- return async (info, ctx) => {
1702
- const { fullProfile } = info.result;
1703
- const userId = fullProfile.username;
1704
- if (!userId) {
1705
- throw new Error(`GitHub user profile does not contain a username`);
1706
- }
1707
- return ctx.signInWithCatalogUser({ entityRef: { name: userId } });
1708
- };
1709
- }
1710
- }
1711
- });
1712
-
1713
- var __defProp$d = Object.defineProperty;
1714
- var __defNormalProp$d = (obj, key, value) => key in obj ? __defProp$d(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1715
- var __publicField$d = (obj, key, value) => {
1716
- __defNormalProp$d(obj, typeof key !== "symbol" ? key + "" : key, value);
1717
- return value;
1718
- };
1719
- const gitlabDefaultAuthHandler = async ({
1720
- fullProfile,
1721
- params
1722
- }) => ({
1723
- profile: makeProfileInfo(fullProfile, params.id_token)
1724
- });
1725
- class GitlabAuthProvider {
1726
- constructor(options) {
1727
- __publicField$d(this, "_strategy");
1728
- __publicField$d(this, "signInResolver");
1729
- __publicField$d(this, "authHandler");
1730
- __publicField$d(this, "resolverContext");
1731
- this.resolverContext = options.resolverContext;
1732
- this.authHandler = options.authHandler;
1733
- this.signInResolver = options.signInResolver;
1734
- this._strategy = new passportGitlab2.Strategy(
1735
- {
1736
- clientID: options.clientId,
1737
- clientSecret: options.clientSecret,
1738
- callbackURL: options.callbackUrl,
1739
- baseURL: options.baseUrl,
1740
- authorizationURL: `${options.baseUrl}/oauth/authorize`,
1741
- tokenURL: `${options.baseUrl}/oauth/token`,
1742
- profileURL: `${options.baseUrl}/api/v4/user`
1743
- },
1744
- (accessToken, refreshToken, params, fullProfile, done) => {
1745
- done(
1746
- void 0,
1747
- { fullProfile, params, accessToken },
1748
- {
1749
- refreshToken
1750
- }
1751
- );
1752
- }
1753
- );
1754
- }
1755
- async start(req) {
1756
- return await executeRedirectStrategy(req, this._strategy, {
1757
- scope: req.scope,
1758
- state: encodeState(req.state)
1759
- });
1760
- }
1761
- async handler(req) {
1762
- const { result, privateInfo } = await executeFrameHandlerStrategy(req, this._strategy);
1763
- return {
1764
- response: await this.handleResult(result),
1765
- refreshToken: privateInfo.refreshToken
1766
- };
1767
- }
1768
- async refresh(req) {
1769
- const { accessToken, refreshToken, params } = await executeRefreshTokenStrategy(
1770
- this._strategy,
1771
- req.refreshToken,
1772
- req.scope
1773
- );
1774
- const fullProfile = await executeFetchUserProfileStrategy(
1775
- this._strategy,
1776
- accessToken
1777
- );
1778
- return {
1779
- response: await this.handleResult({
1780
- fullProfile,
1781
- params,
1782
- accessToken
1783
- }),
1784
- refreshToken
1785
- };
1786
- }
1787
- async handleResult(result) {
1788
- const { profile } = await this.authHandler(result, this.resolverContext);
1789
- const response = {
1790
- providerInfo: {
1791
- idToken: result.params.id_token,
1792
- accessToken: result.accessToken,
1793
- scope: result.params.scope,
1794
- expiresInSeconds: result.params.expires_in
1795
- },
1796
- profile
1797
- };
1798
- if (this.signInResolver) {
1799
- response.backstageIdentity = await this.signInResolver(
1800
- {
1801
- result,
1802
- profile
1803
- },
1804
- this.resolverContext
1282
+ throw new errors.ForwardedError(
1283
+ "Failed to populate access identity information",
1284
+ err
1805
1285
  );
1806
1286
  }
1807
- return response;
1808
- }
1809
- }
1810
- const gitlab = createAuthProviderIntegration({
1811
- create(options) {
1812
- return ({ providerId, globalConfig, config, resolverContext }) => OAuthEnvironmentHandler.mapConfig(config, (envConfig) => {
1813
- var _a, _b;
1814
- const clientId = envConfig.getString("clientId");
1815
- const clientSecret = envConfig.getString("clientSecret");
1816
- const audience = envConfig.getOptionalString("audience");
1817
- const baseUrl = audience || "https://gitlab.com";
1818
- const customCallbackUrl = envConfig.getOptionalString("callbackUrl");
1819
- const callbackUrl = customCallbackUrl || `${globalConfig.baseUrl}/${providerId}/handler/frame`;
1820
- const authHandler = (_a = options == null ? void 0 : options.authHandler) != null ? _a : gitlabDefaultAuthHandler;
1821
- const provider = new GitlabAuthProvider({
1822
- clientId,
1823
- clientSecret,
1824
- callbackUrl,
1825
- baseUrl,
1826
- authHandler,
1827
- signInResolver: (_b = options == null ? void 0 : options.signIn) == null ? void 0 : _b.resolver,
1828
- resolverContext
1829
- });
1830
- return OAuthAdapter.fromConfig(globalConfig, provider, {
1831
- providerId,
1832
- callbackUrl
1833
- });
1834
- });
1835
1287
  }
1836
- });
1837
-
1838
- var __defProp$c = Object.defineProperty;
1839
- var __defNormalProp$c = (obj, key, value) => key in obj ? __defProp$c(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1840
- var __publicField$c = (obj, key, value) => {
1841
- __defNormalProp$c(obj, typeof key !== "symbol" ? key + "" : key, value);
1842
- return value;
1843
- };
1844
- class GoogleAuthProvider {
1845
- constructor(options) {
1846
- __publicField$c(this, "strategy");
1847
- __publicField$c(this, "signInResolver");
1848
- __publicField$c(this, "authHandler");
1849
- __publicField$c(this, "resolverContext");
1850
- this.authHandler = options.authHandler;
1851
- this.signInResolver = options.signInResolver;
1852
- this.resolverContext = options.resolverContext;
1853
- this.strategy = new passportGoogleOauth20.Strategy(
1288
+ async handleResult(result) {
1289
+ const { profile } = await this.authHandler(result, this.resolverContext);
1290
+ const backstageIdentity = await this.signInResolver(
1854
1291
  {
1855
- clientID: options.clientId,
1856
- clientSecret: options.clientSecret,
1857
- callbackURL: options.callbackUrl,
1858
- passReqToCallback: false
1292
+ result,
1293
+ profile
1859
1294
  },
1860
- (accessToken, refreshToken, params, fullProfile, done) => {
1861
- done(
1862
- void 0,
1863
- {
1864
- fullProfile,
1865
- params,
1866
- accessToken,
1867
- refreshToken
1868
- },
1869
- {
1870
- refreshToken
1871
- }
1872
- );
1873
- }
1874
- );
1875
- }
1876
- async start(req) {
1877
- return await executeRedirectStrategy(req, this.strategy, {
1878
- accessType: "offline",
1879
- prompt: "consent",
1880
- scope: req.scope,
1881
- state: encodeState(req.state)
1882
- });
1883
- }
1884
- async handler(req) {
1885
- const { result, privateInfo } = await executeFrameHandlerStrategy(req, this.strategy);
1886
- return {
1887
- response: await this.handleResult(result),
1888
- refreshToken: privateInfo.refreshToken
1889
- };
1890
- }
1891
- async logout(req) {
1892
- const oauthClient = new googleAuthLibrary.OAuth2Client();
1893
- await oauthClient.revokeToken(req.refreshToken);
1894
- }
1895
- async refresh(req) {
1896
- const { accessToken, refreshToken, params } = await executeRefreshTokenStrategy(
1897
- this.strategy,
1898
- req.refreshToken,
1899
- req.scope
1900
- );
1901
- const fullProfile = await executeFetchUserProfileStrategy(
1902
- this.strategy,
1903
- accessToken
1295
+ this.resolverContext
1904
1296
  );
1905
1297
  return {
1906
- response: await this.handleResult({
1907
- fullProfile,
1908
- params,
1909
- accessToken
1910
- }),
1911
- refreshToken
1912
- };
1913
- }
1914
- async handleResult(result) {
1915
- const { profile } = await this.authHandler(result, this.resolverContext);
1916
- const response = {
1917
1298
  providerInfo: {
1918
- idToken: result.params.id_token,
1919
- accessToken: result.accessToken,
1920
- scope: result.params.scope,
1921
- expiresInSeconds: result.params.expires_in
1299
+ expiresInSeconds: result.expiresInSeconds,
1300
+ claims: result.claims,
1301
+ cfAccessIdentityProfile: result.cfIdentity
1922
1302
  },
1303
+ backstageIdentity: prepareBackstageIdentityResponse(backstageIdentity),
1923
1304
  profile
1924
1305
  };
1925
- if (this.signInResolver) {
1926
- response.backstageIdentity = await this.signInResolver(
1927
- {
1928
- result,
1929
- profile
1930
- },
1931
- this.resolverContext
1932
- );
1933
- }
1934
- return response;
1935
1306
  }
1936
1307
  }
1937
- const google = createAuthProviderIntegration({
1308
+ const cfAccess = createAuthProviderIntegration({
1938
1309
  create(options) {
1939
- return ({ providerId, globalConfig, config, resolverContext }) => OAuthEnvironmentHandler.mapConfig(config, (envConfig) => {
1940
- var _a;
1941
- const clientId = envConfig.getString("clientId");
1942
- const clientSecret = envConfig.getString("clientSecret");
1943
- const customCallbackUrl = envConfig.getOptionalString("callbackUrl");
1944
- const callbackUrl = customCallbackUrl || `${globalConfig.baseUrl}/${providerId}/handler/frame`;
1945
- const authHandler = (options == null ? void 0 : options.authHandler) ? options.authHandler : async ({ fullProfile, params }) => ({
1946
- profile: makeProfileInfo(fullProfile, params.id_token)
1947
- });
1948
- const provider = new GoogleAuthProvider({
1949
- clientId,
1950
- clientSecret,
1951
- callbackUrl,
1952
- signInResolver: (_a = options == null ? void 0 : options.signIn) == null ? void 0 : _a.resolver,
1310
+ return ({ config, resolverContext }) => {
1311
+ const teamName = config.getString("teamName");
1312
+ if (!options.signIn.resolver) {
1313
+ throw new Error(
1314
+ "SignInResolver is required to use this authentication provider"
1315
+ );
1316
+ }
1317
+ const authHandler = (options == null ? void 0 : options.authHandler) ? options.authHandler : async ({ claims, cfIdentity }) => {
1318
+ return {
1319
+ profile: {
1320
+ email: claims.email,
1321
+ displayName: cfIdentity.name
1322
+ }
1323
+ };
1324
+ };
1325
+ return new CloudflareAccessAuthProvider({
1326
+ teamName,
1327
+ signInResolver: options == null ? void 0 : options.signIn.resolver,
1953
1328
  authHandler,
1954
- resolverContext
1955
- });
1956
- return OAuthAdapter.fromConfig(globalConfig, provider, {
1957
- providerId,
1958
- callbackUrl
1329
+ resolverContext,
1330
+ ...options.cache && { cache: options.cache }
1959
1331
  });
1960
- });
1332
+ };
1961
1333
  },
1962
1334
  resolvers: {
1963
- /**
1964
- * Looks up the user by matching their email local part to the entity name.
1965
- */
1966
- emailLocalPartMatchingUserEntityName: () => commonByEmailLocalPartResolver,
1967
1335
  /**
1968
1336
  * Looks up the user by matching their email to the entity email.
1969
1337
  */
1970
- emailMatchingUserEntityProfileEmail: () => commonByEmailResolver,
1338
+ emailMatchingUserEntityProfileEmail: () => commonByEmailResolver
1339
+ }
1340
+ });
1341
+
1342
+ const gcpIap = createAuthProviderIntegration({
1343
+ create(options) {
1344
+ var _a;
1345
+ return pluginAuthNode.createProxyAuthProviderFactory({
1346
+ authenticator: pluginAuthBackendModuleGcpIapProvider.gcpIapAuthenticator,
1347
+ profileTransform: options == null ? void 0 : options.authHandler,
1348
+ signInResolver: (_a = options == null ? void 0 : options.signIn) == null ? void 0 : _a.resolver
1349
+ });
1350
+ }
1351
+ });
1352
+
1353
+ const github = createAuthProviderIntegration({
1354
+ create(options) {
1355
+ var _a;
1356
+ const authHandler = options == null ? void 0 : options.authHandler;
1357
+ const signInResolver = (_a = options == null ? void 0 : options.signIn) == null ? void 0 : _a.resolver;
1358
+ return pluginAuthNode.createOAuthProviderFactory({
1359
+ authenticator: pluginAuthBackendModuleGithubProvider.githubAuthenticator,
1360
+ profileTransform: authHandler && (async (result, ctx) => authHandler(
1361
+ {
1362
+ fullProfile: result.fullProfile,
1363
+ accessToken: result.session.accessToken,
1364
+ params: {
1365
+ scope: result.session.scope,
1366
+ expires_in: result.session.expiresInSeconds ? String(result.session.expiresInSeconds) : "",
1367
+ refresh_token_expires_in: result.session.refreshTokenExpiresInSeconds ? String(result.session.refreshTokenExpiresInSeconds) : ""
1368
+ }
1369
+ },
1370
+ ctx
1371
+ )),
1372
+ signInResolver: signInResolver && (async ({ profile, result }, ctx) => signInResolver(
1373
+ {
1374
+ profile,
1375
+ result: {
1376
+ fullProfile: result.fullProfile,
1377
+ accessToken: result.session.accessToken,
1378
+ refreshToken: result.session.refreshToken,
1379
+ params: {
1380
+ scope: result.session.scope,
1381
+ expires_in: result.session.expiresInSeconds ? String(result.session.expiresInSeconds) : "",
1382
+ refresh_token_expires_in: result.session.refreshTokenExpiresInSeconds ? String(result.session.refreshTokenExpiresInSeconds) : ""
1383
+ }
1384
+ }
1385
+ },
1386
+ ctx
1387
+ ))
1388
+ });
1389
+ },
1390
+ resolvers: {
1971
1391
  /**
1972
- * Looks up the user by matching their email to the `google.com/email` annotation.
1392
+ * Looks up the user by matching their GitHub username to the entity name.
1973
1393
  */
1974
- emailMatchingUserEntityAnnotation() {
1394
+ usernameMatchingUserEntityName: () => {
1975
1395
  return async (info, ctx) => {
1976
- const { profile } = info;
1977
- if (!profile.email) {
1978
- throw new Error("Google profile contained no email");
1396
+ const { fullProfile } = info.result;
1397
+ const userId = fullProfile.username;
1398
+ if (!userId) {
1399
+ throw new Error(`GitHub user profile does not contain a username`);
1979
1400
  }
1980
- return ctx.signInWithCatalogUser({
1981
- annotations: {
1982
- "google.com/email": profile.email
1983
- }
1984
- });
1401
+ return ctx.signInWithCatalogUser({ entityRef: { name: userId } });
1985
1402
  };
1986
1403
  }
1987
1404
  }
1988
1405
  });
1989
1406
 
1407
+ function adaptLegacyOAuthHandler(authHandler) {
1408
+ return authHandler && (async (result, ctx) => authHandler(
1409
+ {
1410
+ fullProfile: result.fullProfile,
1411
+ accessToken: result.session.accessToken,
1412
+ params: {
1413
+ scope: result.session.scope,
1414
+ id_token: result.session.idToken,
1415
+ token_type: result.session.tokenType,
1416
+ expires_in: result.session.expiresInSeconds
1417
+ }
1418
+ },
1419
+ ctx
1420
+ ));
1421
+ }
1422
+
1423
+ function adaptLegacyOAuthSignInResolver(signInResolver) {
1424
+ return signInResolver && (async (input, ctx) => signInResolver(
1425
+ {
1426
+ profile: input.profile,
1427
+ result: {
1428
+ fullProfile: input.result.fullProfile,
1429
+ accessToken: input.result.session.accessToken,
1430
+ refreshToken: input.result.session.refreshToken,
1431
+ params: {
1432
+ scope: input.result.session.scope,
1433
+ id_token: input.result.session.idToken,
1434
+ token_type: input.result.session.tokenType,
1435
+ expires_in: input.result.session.expiresInSeconds
1436
+ }
1437
+ }
1438
+ },
1439
+ ctx
1440
+ ));
1441
+ }
1442
+
1443
+ function adaptOAuthSignInResolverToLegacy(resolvers) {
1444
+ const legacyResolvers = {};
1445
+ for (const name of Object.keys(resolvers)) {
1446
+ const resolver = resolvers[name];
1447
+ legacyResolvers[name] = () => async (input, ctx) => {
1448
+ var _a;
1449
+ return resolver(
1450
+ {
1451
+ profile: input.profile,
1452
+ result: {
1453
+ fullProfile: input.result.fullProfile,
1454
+ session: {
1455
+ accessToken: input.result.accessToken,
1456
+ expiresInSeconds: input.result.params.expires_in,
1457
+ scope: input.result.params.scope,
1458
+ idToken: input.result.params.id_token,
1459
+ tokenType: (_a = input.result.params.token_type) != null ? _a : "bearer",
1460
+ refreshToken: input.result.refreshToken
1461
+ }
1462
+ }
1463
+ },
1464
+ ctx
1465
+ );
1466
+ };
1467
+ }
1468
+ return legacyResolvers;
1469
+ }
1470
+
1471
+ const gitlab = createAuthProviderIntegration({
1472
+ create(options) {
1473
+ var _a;
1474
+ return pluginAuthNode.createOAuthProviderFactory({
1475
+ authenticator: pluginAuthBackendModuleGitlabProvider.gitlabAuthenticator,
1476
+ profileTransform: adaptLegacyOAuthHandler(options == null ? void 0 : options.authHandler),
1477
+ signInResolver: adaptLegacyOAuthSignInResolver((_a = options == null ? void 0 : options.signIn) == null ? void 0 : _a.resolver)
1478
+ });
1479
+ }
1480
+ });
1481
+
1482
+ const google = createAuthProviderIntegration({
1483
+ create(options) {
1484
+ var _a;
1485
+ return pluginAuthNode.createOAuthProviderFactory({
1486
+ authenticator: pluginAuthBackendModuleGoogleProvider.googleAuthenticator,
1487
+ profileTransform: adaptLegacyOAuthHandler(options == null ? void 0 : options.authHandler),
1488
+ signInResolver: adaptLegacyOAuthSignInResolver((_a = options == null ? void 0 : options.signIn) == null ? void 0 : _a.resolver)
1489
+ });
1490
+ },
1491
+ resolvers: adaptOAuthSignInResolverToLegacy({
1492
+ emailLocalPartMatchingUserEntityName: pluginAuthNode.commonSignInResolvers.emailLocalPartMatchingUserEntityName(),
1493
+ emailMatchingUserEntityProfileEmail: pluginAuthNode.commonSignInResolvers.emailMatchingUserEntityProfileEmail(),
1494
+ emailMatchingUserEntityAnnotation: pluginAuthBackendModuleGoogleProvider.googleSignInResolvers.emailMatchingUserEntityAnnotation()
1495
+ })
1496
+ });
1497
+
1498
+ const BACKSTAGE_SESSION_EXPIRATION = 3600;
1499
+
1990
1500
  var __defProp$b = Object.defineProperty;
1991
1501
  var __defNormalProp$b = (obj, key, value) => key in obj ? __defProp$b(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1992
1502
  var __publicField$b = (obj, key, value) => {
@@ -3873,7 +3383,7 @@ async function createRouter(options) {
3873
3383
  database,
3874
3384
  tokenManager,
3875
3385
  tokenFactoryAlgorithm,
3876
- providerFactories,
3386
+ providerFactories = {},
3877
3387
  catalogApi
3878
3388
  } = options;
3879
3389
  const router = Router__default["default"]();
@@ -3890,7 +3400,7 @@ async function createRouter(options) {
3890
3400
  keyStore,
3891
3401
  keyDurationSeconds,
3892
3402
  logger: logger.child({ component: "token-factory" }),
3893
- algorithm: tokenFactoryAlgorithm
3403
+ algorithm: tokenFactoryAlgorithm != null ? tokenFactoryAlgorithm : config.getOptionalString("auth.identityTokenAlgorithm")
3894
3404
  });
3895
3405
  const secret = config.getOptionalString("auth.session.secret");
3896
3406
  if (secret) {
@@ -3916,21 +3426,23 @@ async function createRouter(options) {
3916
3426
  }
3917
3427
  router.use(express__default["default"].urlencoded({ extended: false }));
3918
3428
  router.use(express__default["default"].json());
3919
- const allProviderFactories = {
3429
+ const allProviderFactories = options.disableDefaultProviderFactories ? providerFactories : {
3920
3430
  ...defaultAuthProviderFactories,
3921
3431
  ...providerFactories
3922
3432
  };
3923
- const providersConfig = config.getConfig("auth.providers");
3924
- const configuredProviders = providersConfig.keys();
3433
+ const providersConfig = config.getOptionalConfig("auth.providers");
3925
3434
  const isOriginAllowed = createOriginFilter(config);
3926
3435
  for (const [providerId, providerFactory] of Object.entries(
3927
3436
  allProviderFactories
3928
3437
  )) {
3929
- if (configuredProviders.includes(providerId)) {
3438
+ if (providersConfig == null ? void 0 : providersConfig.has(providerId)) {
3930
3439
  logger.info(`Configuring auth provider: ${providerId}`);
3931
3440
  try {
3932
3441
  const provider = providerFactory({
3933
3442
  providerId,
3443
+ appUrl,
3444
+ baseUrl: authUrl,
3445
+ isOriginAllowed,
3934
3446
  globalConfig: {
3935
3447
  baseUrl: authUrl,
3936
3448
  appUrl,
@@ -4009,9 +3521,59 @@ function createOriginFilter(config) {
4009
3521
  };
4010
3522
  }
4011
3523
 
3524
+ const authPlugin = backendPluginApi.createBackendPlugin({
3525
+ pluginId: "auth",
3526
+ register(reg) {
3527
+ const providers = /* @__PURE__ */ new Map();
3528
+ reg.registerExtensionPoint(pluginAuthNode.authProvidersExtensionPoint, {
3529
+ registerProvider({ providerId, factory }) {
3530
+ if (providers.has(providerId)) {
3531
+ throw new Error(
3532
+ `Auth provider '${providerId}' was already registered`
3533
+ );
3534
+ }
3535
+ providers.set(providerId, factory);
3536
+ }
3537
+ });
3538
+ reg.registerInit({
3539
+ deps: {
3540
+ httpRouter: backendPluginApi.coreServices.httpRouter,
3541
+ logger: backendPluginApi.coreServices.logger,
3542
+ config: backendPluginApi.coreServices.rootConfig,
3543
+ database: backendPluginApi.coreServices.database,
3544
+ discovery: backendPluginApi.coreServices.discovery,
3545
+ tokenManager: backendPluginApi.coreServices.tokenManager,
3546
+ catalogApi: alpha.catalogServiceRef
3547
+ },
3548
+ async init({
3549
+ httpRouter,
3550
+ logger,
3551
+ config,
3552
+ database,
3553
+ discovery,
3554
+ tokenManager,
3555
+ catalogApi
3556
+ }) {
3557
+ const router = await createRouter({
3558
+ logger,
3559
+ config,
3560
+ database,
3561
+ discovery,
3562
+ tokenManager,
3563
+ catalogApi,
3564
+ providerFactories: Object.fromEntries(providers),
3565
+ disableDefaultProviderFactories: true
3566
+ });
3567
+ httpRouter.use(router);
3568
+ }
3569
+ });
3570
+ }
3571
+ });
3572
+
4012
3573
  exports.CatalogIdentityClient = CatalogIdentityClient;
4013
3574
  exports.OAuthAdapter = OAuthAdapter;
4014
3575
  exports.OAuthEnvironmentHandler = OAuthEnvironmentHandler;
3576
+ exports.authPlugin = authPlugin;
4015
3577
  exports.createAuthProviderIntegration = createAuthProviderIntegration;
4016
3578
  exports.createOriginFilter = createOriginFilter;
4017
3579
  exports.createRouter = createRouter;