@backstage/backend-app-api 0.5.12 → 0.6.0-next.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/dist/index.cjs.js CHANGED
@@ -23,10 +23,13 @@ var crypto = require('crypto');
23
23
  var winston = require('winston');
24
24
  var backendPluginApi = require('@backstage/backend-plugin-api');
25
25
  var alpha = require('@backstage/backend-plugin-api/alpha');
26
+ var jose = require('jose');
26
27
  var backendCommon = require('@backstage/backend-common');
27
28
  var backendAppApi = require('@backstage/backend-app-api');
29
+ var cookie = require('cookie');
28
30
  var PromiseRouter = require('express-promise-router');
29
31
  var types = require('@backstage/types');
32
+ var pathToRegexp = require('path-to-regexp');
30
33
  var pluginAuthNode = require('@backstage/plugin-auth-node');
31
34
  var pluginPermissionNode = require('@backstage/plugin-permission-node');
32
35
  var express = require('express');
@@ -609,31 +612,31 @@ function applyInternalErrorFilter(error, logger) {
609
612
  return error;
610
613
  }
611
614
 
612
- var __accessCheck$8 = (obj, member, msg) => {
615
+ var __accessCheck$a = (obj, member, msg) => {
613
616
  if (!member.has(obj))
614
617
  throw TypeError("Cannot " + msg);
615
618
  };
616
- var __privateGet$8 = (obj, member, getter) => {
617
- __accessCheck$8(obj, member, "read from private field");
619
+ var __privateGet$9 = (obj, member, getter) => {
620
+ __accessCheck$a(obj, member, "read from private field");
618
621
  return getter ? getter.call(obj) : member.get(obj);
619
622
  };
620
- var __privateAdd$8 = (obj, member, value) => {
623
+ var __privateAdd$a = (obj, member, value) => {
621
624
  if (member.has(obj))
622
625
  throw TypeError("Cannot add the same private member more than once");
623
626
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
624
627
  };
625
- var __privateSet$8 = (obj, member, value, setter) => {
626
- __accessCheck$8(obj, member, "write to private field");
628
+ var __privateSet$9 = (obj, member, value, setter) => {
629
+ __accessCheck$a(obj, member, "write to private field");
627
630
  setter ? setter.call(obj, value) : member.set(obj, value);
628
631
  return value;
629
632
  };
630
633
  var _config, _logger;
631
634
  const _MiddlewareFactory = class _MiddlewareFactory {
632
635
  constructor(options) {
633
- __privateAdd$8(this, _config, void 0);
634
- __privateAdd$8(this, _logger, void 0);
635
- __privateSet$8(this, _config, options.config);
636
- __privateSet$8(this, _logger, options.logger);
636
+ __privateAdd$a(this, _config, void 0);
637
+ __privateAdd$a(this, _logger, void 0);
638
+ __privateSet$9(this, _config, options.config);
639
+ __privateSet$9(this, _logger, options.logger);
637
640
  }
638
641
  /**
639
642
  * Creates a new {@link MiddlewareFactory}.
@@ -679,7 +682,7 @@ const _MiddlewareFactory = class _MiddlewareFactory {
679
682
  * @returns An Express request handler
680
683
  */
681
684
  logging() {
682
- const logger = __privateGet$8(this, _logger).child({
685
+ const logger = __privateGet$9(this, _logger).child({
683
686
  type: "incomingRequest"
684
687
  });
685
688
  return morgan__default["default"]("combined", {
@@ -703,7 +706,7 @@ const _MiddlewareFactory = class _MiddlewareFactory {
703
706
  * @returns An Express request handler
704
707
  */
705
708
  helmet() {
706
- return helmet__default["default"](readHelmetOptions(__privateGet$8(this, _config).getOptionalConfig("backend")));
709
+ return helmet__default["default"](readHelmetOptions(__privateGet$9(this, _config).getOptionalConfig("backend")));
707
710
  }
708
711
  /**
709
712
  * Returns a middleware that implements the cors library.
@@ -718,7 +721,7 @@ const _MiddlewareFactory = class _MiddlewareFactory {
718
721
  * @returns An Express request handler
719
722
  */
720
723
  cors() {
721
- return cors__default["default"](readCorsOptions(__privateGet$8(this, _config).getOptionalConfig("backend")));
724
+ return cors__default["default"](readCorsOptions(__privateGet$9(this, _config).getOptionalConfig("backend")));
722
725
  }
723
726
  /**
724
727
  * Express middleware to handle errors during request processing.
@@ -743,7 +746,7 @@ const _MiddlewareFactory = class _MiddlewareFactory {
743
746
  error(options = {}) {
744
747
  var _a;
745
748
  const showStackTraces = (_a = options.showStackTraces) != null ? _a : process.env.NODE_ENV === "development";
746
- const logger = __privateGet$8(this, _logger).child({
749
+ const logger = __privateGet$9(this, _logger).child({
747
750
  type: "errorHandler"
748
751
  });
749
752
  return (rawError, req, res, next) => {
@@ -802,31 +805,31 @@ const escapeRegExp = (text) => {
802
805
  return text.replace(/[.*+?^${}(\)|[\]\\]/g, "\\$&");
803
806
  };
804
807
 
805
- var __accessCheck$7 = (obj, member, msg) => {
808
+ var __accessCheck$9 = (obj, member, msg) => {
806
809
  if (!member.has(obj))
807
810
  throw TypeError("Cannot " + msg);
808
811
  };
809
- var __privateGet$7 = (obj, member, getter) => {
810
- __accessCheck$7(obj, member, "read from private field");
812
+ var __privateGet$8 = (obj, member, getter) => {
813
+ __accessCheck$9(obj, member, "read from private field");
811
814
  return getter ? getter.call(obj) : member.get(obj);
812
815
  };
813
- var __privateAdd$7 = (obj, member, value) => {
816
+ var __privateAdd$9 = (obj, member, value) => {
814
817
  if (member.has(obj))
815
818
  throw TypeError("Cannot add the same private member more than once");
816
819
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
817
820
  };
818
- var __privateSet$7 = (obj, member, value, setter) => {
819
- __accessCheck$7(obj, member, "write to private field");
821
+ var __privateSet$8 = (obj, member, value, setter) => {
822
+ __accessCheck$9(obj, member, "write to private field");
820
823
  setter ? setter.call(obj, value) : member.set(obj, value);
821
824
  return value;
822
825
  };
823
826
  var _winston, _addRedactions;
824
827
  const _WinstonLogger = class _WinstonLogger {
825
828
  constructor(winston, addRedactions) {
826
- __privateAdd$7(this, _winston, void 0);
827
- __privateAdd$7(this, _addRedactions, void 0);
828
- __privateSet$7(this, _winston, winston);
829
- __privateSet$7(this, _addRedactions, addRedactions);
829
+ __privateAdd$9(this, _winston, void 0);
830
+ __privateAdd$9(this, _addRedactions, void 0);
831
+ __privateSet$8(this, _winston, winston);
832
+ __privateSet$8(this, _addRedactions, addRedactions);
830
833
  }
831
834
  /**
832
835
  * Creates a {@link WinstonLogger} instance.
@@ -907,44 +910,44 @@ const _WinstonLogger = class _WinstonLogger {
907
910
  );
908
911
  }
909
912
  error(message, meta) {
910
- __privateGet$7(this, _winston).error(message, meta);
913
+ __privateGet$8(this, _winston).error(message, meta);
911
914
  }
912
915
  warn(message, meta) {
913
- __privateGet$7(this, _winston).warn(message, meta);
916
+ __privateGet$8(this, _winston).warn(message, meta);
914
917
  }
915
918
  info(message, meta) {
916
- __privateGet$7(this, _winston).info(message, meta);
919
+ __privateGet$8(this, _winston).info(message, meta);
917
920
  }
918
921
  debug(message, meta) {
919
- __privateGet$7(this, _winston).debug(message, meta);
922
+ __privateGet$8(this, _winston).debug(message, meta);
920
923
  }
921
924
  child(meta) {
922
- return new _WinstonLogger(__privateGet$7(this, _winston).child(meta));
925
+ return new _WinstonLogger(__privateGet$8(this, _winston).child(meta));
923
926
  }
924
927
  addRedactions(redactions) {
925
928
  var _a;
926
- (_a = __privateGet$7(this, _addRedactions)) == null ? void 0 : _a.call(this, redactions);
929
+ (_a = __privateGet$8(this, _addRedactions)) == null ? void 0 : _a.call(this, redactions);
927
930
  }
928
931
  };
929
932
  _winston = new WeakMap();
930
933
  _addRedactions = new WeakMap();
931
934
  let WinstonLogger = _WinstonLogger;
932
935
 
933
- var __accessCheck$6 = (obj, member, msg) => {
936
+ var __accessCheck$8 = (obj, member, msg) => {
934
937
  if (!member.has(obj))
935
938
  throw TypeError("Cannot " + msg);
936
939
  };
937
- var __privateGet$6 = (obj, member, getter) => {
938
- __accessCheck$6(obj, member, "read from private field");
940
+ var __privateGet$7 = (obj, member, getter) => {
941
+ __accessCheck$8(obj, member, "read from private field");
939
942
  return getter ? getter.call(obj) : member.get(obj);
940
943
  };
941
- var __privateAdd$6 = (obj, member, value) => {
944
+ var __privateAdd$8 = (obj, member, value) => {
942
945
  if (member.has(obj))
943
946
  throw TypeError("Cannot add the same private member more than once");
944
947
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
945
948
  };
946
- var __privateSet$6 = (obj, member, value, setter) => {
947
- __accessCheck$6(obj, member, "write to private field");
949
+ var __privateSet$7 = (obj, member, value, setter) => {
950
+ __accessCheck$8(obj, member, "write to private field");
948
951
  setter ? setter.call(obj, value) : member.set(obj, value);
949
952
  return value;
950
953
  };
@@ -952,25 +955,25 @@ var _hasStarted$1, _startupTasks$1, _hasShutdown, _shutdownTasks;
952
955
  class BackendLifecycleImpl {
953
956
  constructor(logger) {
954
957
  this.logger = logger;
955
- __privateAdd$6(this, _hasStarted$1, false);
956
- __privateAdd$6(this, _startupTasks$1, []);
957
- __privateAdd$6(this, _hasShutdown, false);
958
- __privateAdd$6(this, _shutdownTasks, []);
958
+ __privateAdd$8(this, _hasStarted$1, false);
959
+ __privateAdd$8(this, _startupTasks$1, []);
960
+ __privateAdd$8(this, _hasShutdown, false);
961
+ __privateAdd$8(this, _shutdownTasks, []);
959
962
  }
960
963
  addStartupHook(hook, options) {
961
- if (__privateGet$6(this, _hasStarted$1)) {
964
+ if (__privateGet$7(this, _hasStarted$1)) {
962
965
  throw new Error("Attempted to add startup hook after startup");
963
966
  }
964
- __privateGet$6(this, _startupTasks$1).push({ hook, options });
967
+ __privateGet$7(this, _startupTasks$1).push({ hook, options });
965
968
  }
966
969
  async startup() {
967
- if (__privateGet$6(this, _hasStarted$1)) {
970
+ if (__privateGet$7(this, _hasStarted$1)) {
968
971
  return;
969
972
  }
970
- __privateSet$6(this, _hasStarted$1, true);
971
- this.logger.debug(`Running ${__privateGet$6(this, _startupTasks$1).length} startup tasks...`);
973
+ __privateSet$7(this, _hasStarted$1, true);
974
+ this.logger.debug(`Running ${__privateGet$7(this, _startupTasks$1).length} startup tasks...`);
972
975
  await Promise.all(
973
- __privateGet$6(this, _startupTasks$1).map(async ({ hook, options }) => {
976
+ __privateGet$7(this, _startupTasks$1).map(async ({ hook, options }) => {
974
977
  var _a;
975
978
  const logger = (_a = options == null ? void 0 : options.logger) != null ? _a : this.logger;
976
979
  try {
@@ -983,21 +986,21 @@ class BackendLifecycleImpl {
983
986
  );
984
987
  }
985
988
  addShutdownHook(hook, options) {
986
- if (__privateGet$6(this, _hasShutdown)) {
989
+ if (__privateGet$7(this, _hasShutdown)) {
987
990
  throw new Error("Attempted to add shutdown hook after shutdown");
988
991
  }
989
- __privateGet$6(this, _shutdownTasks).push({ hook, options });
992
+ __privateGet$7(this, _shutdownTasks).push({ hook, options });
990
993
  }
991
994
  async shutdown() {
992
- if (__privateGet$6(this, _hasShutdown)) {
995
+ if (__privateGet$7(this, _hasShutdown)) {
993
996
  return;
994
997
  }
995
- __privateSet$6(this, _hasShutdown, true);
998
+ __privateSet$7(this, _hasShutdown, true);
996
999
  this.logger.debug(
997
- `Running ${__privateGet$6(this, _shutdownTasks).length} shutdown tasks...`
1000
+ `Running ${__privateGet$7(this, _shutdownTasks).length} shutdown tasks...`
998
1001
  );
999
1002
  await Promise.all(
1000
- __privateGet$6(this, _shutdownTasks).map(async ({ hook, options }) => {
1003
+ __privateGet$7(this, _shutdownTasks).map(async ({ hook, options }) => {
1001
1004
  var _a;
1002
1005
  const logger = (_a = options == null ? void 0 : options.logger) != null ? _a : this.logger;
1003
1006
  try {
@@ -1024,21 +1027,21 @@ const rootLifecycleServiceFactory = backendPluginApi.createServiceFactory({
1024
1027
  }
1025
1028
  });
1026
1029
 
1027
- var __accessCheck$5 = (obj, member, msg) => {
1030
+ var __accessCheck$7 = (obj, member, msg) => {
1028
1031
  if (!member.has(obj))
1029
1032
  throw TypeError("Cannot " + msg);
1030
1033
  };
1031
- var __privateGet$5 = (obj, member, getter) => {
1032
- __accessCheck$5(obj, member, "read from private field");
1034
+ var __privateGet$6 = (obj, member, getter) => {
1035
+ __accessCheck$7(obj, member, "read from private field");
1033
1036
  return getter ? getter.call(obj) : member.get(obj);
1034
1037
  };
1035
- var __privateAdd$5 = (obj, member, value) => {
1038
+ var __privateAdd$7 = (obj, member, value) => {
1036
1039
  if (member.has(obj))
1037
1040
  throw TypeError("Cannot add the same private member more than once");
1038
1041
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1039
1042
  };
1040
- var __privateSet$5 = (obj, member, value, setter) => {
1041
- __accessCheck$5(obj, member, "write to private field");
1043
+ var __privateSet$6 = (obj, member, value, setter) => {
1044
+ __accessCheck$7(obj, member, "write to private field");
1042
1045
  setter ? setter.call(obj, value) : member.set(obj, value);
1043
1046
  return value;
1044
1047
  };
@@ -1048,25 +1051,25 @@ class BackendPluginLifecycleImpl {
1048
1051
  this.logger = logger;
1049
1052
  this.rootLifecycle = rootLifecycle;
1050
1053
  this.pluginMetadata = pluginMetadata;
1051
- __privateAdd$5(this, _hasStarted, false);
1052
- __privateAdd$5(this, _startupTasks, []);
1054
+ __privateAdd$7(this, _hasStarted, false);
1055
+ __privateAdd$7(this, _startupTasks, []);
1053
1056
  }
1054
1057
  addStartupHook(hook, options) {
1055
- if (__privateGet$5(this, _hasStarted)) {
1058
+ if (__privateGet$6(this, _hasStarted)) {
1056
1059
  throw new Error("Attempted to add startup hook after startup");
1057
1060
  }
1058
- __privateGet$5(this, _startupTasks).push({ hook, options });
1061
+ __privateGet$6(this, _startupTasks).push({ hook, options });
1059
1062
  }
1060
1063
  async startup() {
1061
- if (__privateGet$5(this, _hasStarted)) {
1064
+ if (__privateGet$6(this, _hasStarted)) {
1062
1065
  return;
1063
1066
  }
1064
- __privateSet$5(this, _hasStarted, true);
1067
+ __privateSet$6(this, _hasStarted, true);
1065
1068
  this.logger.debug(
1066
- `Running ${__privateGet$5(this, _startupTasks).length} plugin startup tasks...`
1069
+ `Running ${__privateGet$6(this, _startupTasks).length} plugin startup tasks...`
1067
1070
  );
1068
1071
  await Promise.all(
1069
- __privateGet$5(this, _startupTasks).map(async ({ hook, options }) => {
1072
+ __privateGet$6(this, _startupTasks).map(async ({ hook, options }) => {
1070
1073
  var _a;
1071
1074
  const logger = (_a = options == null ? void 0 : options.logger) != null ? _a : this.logger;
1072
1075
  try {
@@ -1104,26 +1107,26 @@ const lifecycleServiceFactory = backendPluginApi.createServiceFactory({
1104
1107
  }
1105
1108
  });
1106
1109
 
1107
- var __accessCheck$4 = (obj, member, msg) => {
1110
+ var __accessCheck$6 = (obj, member, msg) => {
1108
1111
  if (!member.has(obj))
1109
1112
  throw TypeError("Cannot " + msg);
1110
1113
  };
1111
- var __privateGet$4 = (obj, member, getter) => {
1112
- __accessCheck$4(obj, member, "read from private field");
1114
+ var __privateGet$5 = (obj, member, getter) => {
1115
+ __accessCheck$6(obj, member, "read from private field");
1113
1116
  return getter ? getter.call(obj) : member.get(obj);
1114
1117
  };
1115
- var __privateAdd$4 = (obj, member, value) => {
1118
+ var __privateAdd$6 = (obj, member, value) => {
1116
1119
  if (member.has(obj))
1117
1120
  throw TypeError("Cannot add the same private member more than once");
1118
1121
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1119
1122
  };
1120
- var __privateSet$4 = (obj, member, value, setter) => {
1121
- __accessCheck$4(obj, member, "write to private field");
1123
+ var __privateSet$5 = (obj, member, value, setter) => {
1124
+ __accessCheck$6(obj, member, "write to private field");
1122
1125
  setter ? setter.call(obj, value) : member.set(obj, value);
1123
1126
  return value;
1124
1127
  };
1125
- var __privateMethod$3 = (obj, member, method) => {
1126
- __accessCheck$4(obj, member, "access private method");
1128
+ var __privateMethod$5 = (obj, member, method) => {
1129
+ __accessCheck$6(obj, member, "access private method");
1127
1130
  return method;
1128
1131
  };
1129
1132
  var _nodeIds, _cycleKeys, _getCycleKey, getCycleKey_fn, _nodes, _allProvided;
@@ -1143,21 +1146,21 @@ class Node {
1143
1146
  }
1144
1147
  const _CycleKeySet = class _CycleKeySet {
1145
1148
  constructor(nodes) {
1146
- __privateAdd$4(this, _getCycleKey);
1147
- __privateAdd$4(this, _nodeIds, void 0);
1148
- __privateAdd$4(this, _cycleKeys, void 0);
1149
- __privateSet$4(this, _nodeIds, new Map(nodes.map((n, i) => [n.value, i])));
1150
- __privateSet$4(this, _cycleKeys, /* @__PURE__ */ new Set());
1149
+ __privateAdd$6(this, _getCycleKey);
1150
+ __privateAdd$6(this, _nodeIds, void 0);
1151
+ __privateAdd$6(this, _cycleKeys, void 0);
1152
+ __privateSet$5(this, _nodeIds, new Map(nodes.map((n, i) => [n.value, i])));
1153
+ __privateSet$5(this, _cycleKeys, /* @__PURE__ */ new Set());
1151
1154
  }
1152
1155
  static from(nodes) {
1153
1156
  return new _CycleKeySet(nodes);
1154
1157
  }
1155
1158
  tryAdd(path) {
1156
- const cycleKey = __privateMethod$3(this, _getCycleKey, getCycleKey_fn).call(this, path);
1157
- if (__privateGet$4(this, _cycleKeys).has(cycleKey)) {
1159
+ const cycleKey = __privateMethod$5(this, _getCycleKey, getCycleKey_fn).call(this, path);
1160
+ if (__privateGet$5(this, _cycleKeys).has(cycleKey)) {
1158
1161
  return false;
1159
1162
  }
1160
- __privateGet$4(this, _cycleKeys).add(cycleKey);
1163
+ __privateGet$5(this, _cycleKeys).add(cycleKey);
1161
1164
  return true;
1162
1165
  }
1163
1166
  };
@@ -1165,18 +1168,18 @@ _nodeIds = new WeakMap();
1165
1168
  _cycleKeys = new WeakMap();
1166
1169
  _getCycleKey = new WeakSet();
1167
1170
  getCycleKey_fn = function(path) {
1168
- return path.map((n) => __privateGet$4(this, _nodeIds).get(n)).sort().join(",");
1171
+ return path.map((n) => __privateGet$5(this, _nodeIds).get(n)).sort().join(",");
1169
1172
  };
1170
1173
  let CycleKeySet = _CycleKeySet;
1171
1174
  const _DependencyGraph = class _DependencyGraph {
1172
1175
  constructor(nodes) {
1173
- __privateAdd$4(this, _nodes, void 0);
1174
- __privateAdd$4(this, _allProvided, void 0);
1175
- __privateSet$4(this, _nodes, nodes);
1176
- __privateSet$4(this, _allProvided, /* @__PURE__ */ new Set());
1177
- for (const node of __privateGet$4(this, _nodes).values()) {
1176
+ __privateAdd$6(this, _nodes, void 0);
1177
+ __privateAdd$6(this, _allProvided, void 0);
1178
+ __privateSet$5(this, _nodes, nodes);
1179
+ __privateSet$5(this, _allProvided, /* @__PURE__ */ new Set());
1180
+ for (const node of __privateGet$5(this, _nodes).values()) {
1178
1181
  for (const produced of node.provides) {
1179
- __privateGet$4(this, _allProvided).add(produced);
1182
+ __privateGet$5(this, _allProvided).add(produced);
1180
1183
  }
1181
1184
  }
1182
1185
  }
@@ -1200,9 +1203,9 @@ const _DependencyGraph = class _DependencyGraph {
1200
1203
  */
1201
1204
  findUnsatisfiedDeps() {
1202
1205
  const unsatisfiedDependencies = [];
1203
- for (const node of __privateGet$4(this, _nodes).values()) {
1206
+ for (const node of __privateGet$5(this, _nodes).values()) {
1204
1207
  const unsatisfied = Array.from(node.consumes).filter(
1205
- (id) => !__privateGet$4(this, _allProvided).has(id)
1208
+ (id) => !__privateGet$5(this, _allProvided).has(id)
1206
1209
  );
1207
1210
  if (unsatisfied.length > 0) {
1208
1211
  unsatisfiedDependencies.push({ value: node.value, unsatisfied });
@@ -1222,8 +1225,8 @@ const _DependencyGraph = class _DependencyGraph {
1222
1225
  * form a cycle, with the same node as the first and last element of the array.
1223
1226
  */
1224
1227
  *detectCircularDependencies() {
1225
- const cycleKeys = CycleKeySet.from(__privateGet$4(this, _nodes));
1226
- for (const startNode of __privateGet$4(this, _nodes)) {
1228
+ const cycleKeys = CycleKeySet.from(__privateGet$5(this, _nodes));
1229
+ for (const startNode of __privateGet$5(this, _nodes)) {
1227
1230
  const visited = /* @__PURE__ */ new Set();
1228
1231
  const stack = new Array([
1229
1232
  startNode,
@@ -1236,7 +1239,7 @@ const _DependencyGraph = class _DependencyGraph {
1236
1239
  }
1237
1240
  visited.add(node);
1238
1241
  for (const consumed of node.consumes) {
1239
- const providerNodes = __privateGet$4(this, _nodes).filter(
1242
+ const providerNodes = __privateGet$5(this, _nodes).filter(
1240
1243
  (other) => other.provides.has(consumed)
1241
1244
  );
1242
1245
  for (const provider of providerNodes) {
@@ -1265,9 +1268,9 @@ const _DependencyGraph = class _DependencyGraph {
1265
1268
  * Dependencies of nodes that are not produced by any other nodes will be ignored.
1266
1269
  */
1267
1270
  async parallelTopologicalTraversal(fn) {
1268
- const allProvided = __privateGet$4(this, _allProvided);
1271
+ const allProvided = __privateGet$5(this, _allProvided);
1269
1272
  const producedSoFar = /* @__PURE__ */ new Set();
1270
- const waiting = new Set(__privateGet$4(this, _nodes).values());
1273
+ const waiting = new Set(__privateGet$5(this, _nodes).values());
1271
1274
  const visited = /* @__PURE__ */ new Set();
1272
1275
  const results = new Array();
1273
1276
  let inFlight = 0;
@@ -1313,26 +1316,26 @@ _nodes = new WeakMap();
1313
1316
  _allProvided = new WeakMap();
1314
1317
  let DependencyGraph = _DependencyGraph;
1315
1318
 
1316
- var __accessCheck$3 = (obj, member, msg) => {
1319
+ var __accessCheck$5 = (obj, member, msg) => {
1317
1320
  if (!member.has(obj))
1318
1321
  throw TypeError("Cannot " + msg);
1319
1322
  };
1320
- var __privateGet$3 = (obj, member, getter) => {
1321
- __accessCheck$3(obj, member, "read from private field");
1323
+ var __privateGet$4 = (obj, member, getter) => {
1324
+ __accessCheck$5(obj, member, "read from private field");
1322
1325
  return getter ? getter.call(obj) : member.get(obj);
1323
1326
  };
1324
- var __privateAdd$3 = (obj, member, value) => {
1327
+ var __privateAdd$5 = (obj, member, value) => {
1325
1328
  if (member.has(obj))
1326
1329
  throw TypeError("Cannot add the same private member more than once");
1327
1330
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1328
1331
  };
1329
- var __privateSet$3 = (obj, member, value, setter) => {
1330
- __accessCheck$3(obj, member, "write to private field");
1332
+ var __privateSet$4 = (obj, member, value, setter) => {
1333
+ __accessCheck$5(obj, member, "write to private field");
1331
1334
  setter ? setter.call(obj, value) : member.set(obj, value);
1332
1335
  return value;
1333
1336
  };
1334
- var __privateMethod$2 = (obj, member, method) => {
1335
- __accessCheck$3(obj, member, "access private method");
1337
+ var __privateMethod$4 = (obj, member, method) => {
1338
+ __accessCheck$5(obj, member, "access private method");
1336
1339
  return method;
1337
1340
  };
1338
1341
  var _providedFactories, _loadedDefaultFactories, _implementations, _rootServiceImplementations, _addedFactoryIds, _instantiatedFactories, _resolveFactory, resolveFactory_fn, _checkForMissingDeps, checkForMissingDeps_fn;
@@ -1355,19 +1358,19 @@ const pluginMetadataServiceFactory = backendPluginApi.createServiceFactory(
1355
1358
  );
1356
1359
  const _ServiceRegistry = class _ServiceRegistry {
1357
1360
  constructor(factories) {
1358
- __privateAdd$3(this, _resolveFactory);
1359
- __privateAdd$3(this, _checkForMissingDeps);
1360
- __privateAdd$3(this, _providedFactories, void 0);
1361
- __privateAdd$3(this, _loadedDefaultFactories, void 0);
1362
- __privateAdd$3(this, _implementations, void 0);
1363
- __privateAdd$3(this, _rootServiceImplementations, /* @__PURE__ */ new Map());
1364
- __privateAdd$3(this, _addedFactoryIds, /* @__PURE__ */ new Set());
1365
- __privateAdd$3(this, _instantiatedFactories, /* @__PURE__ */ new Set());
1366
- __privateSet$3(this, _providedFactories, new Map(
1361
+ __privateAdd$5(this, _resolveFactory);
1362
+ __privateAdd$5(this, _checkForMissingDeps);
1363
+ __privateAdd$5(this, _providedFactories, void 0);
1364
+ __privateAdd$5(this, _loadedDefaultFactories, void 0);
1365
+ __privateAdd$5(this, _implementations, void 0);
1366
+ __privateAdd$5(this, _rootServiceImplementations, /* @__PURE__ */ new Map());
1367
+ __privateAdd$5(this, _addedFactoryIds, /* @__PURE__ */ new Set());
1368
+ __privateAdd$5(this, _instantiatedFactories, /* @__PURE__ */ new Set());
1369
+ __privateSet$4(this, _providedFactories, new Map(
1367
1370
  factories.map((sf) => [sf.service.id, toInternalServiceFactory(sf)])
1368
1371
  ));
1369
- __privateSet$3(this, _loadedDefaultFactories, /* @__PURE__ */ new Map());
1370
- __privateSet$3(this, _implementations, /* @__PURE__ */ new Map());
1372
+ __privateSet$4(this, _loadedDefaultFactories, /* @__PURE__ */ new Map());
1373
+ __privateSet$4(this, _implementations, /* @__PURE__ */ new Map());
1371
1374
  }
1372
1375
  static create(factories) {
1373
1376
  const registry = new _ServiceRegistry(factories);
@@ -1376,7 +1379,7 @@ const _ServiceRegistry = class _ServiceRegistry {
1376
1379
  }
1377
1380
  checkForCircularDeps() {
1378
1381
  const graph = DependencyGraph.fromIterable(
1379
- Array.from(__privateGet$3(this, _providedFactories)).map(
1382
+ Array.from(__privateGet$4(this, _providedFactories)).map(
1380
1383
  ([serviceId, serviceFactory]) => ({
1381
1384
  value: serviceId,
1382
1385
  provides: [serviceId],
@@ -1398,30 +1401,30 @@ const _ServiceRegistry = class _ServiceRegistry {
1398
1401
  `The ${backendPluginApi.coreServices.pluginMetadata.id} service cannot be overridden`
1399
1402
  );
1400
1403
  }
1401
- if (__privateGet$3(this, _addedFactoryIds).has(factoryId)) {
1404
+ if (__privateGet$4(this, _addedFactoryIds).has(factoryId)) {
1402
1405
  throw new Error(
1403
1406
  `Duplicate service implementations provided for ${factoryId}`
1404
1407
  );
1405
1408
  }
1406
- if (__privateGet$3(this, _instantiatedFactories).has(factoryId)) {
1409
+ if (__privateGet$4(this, _instantiatedFactories).has(factoryId)) {
1407
1410
  throw new Error(
1408
1411
  `Unable to set service factory with id ${factoryId}, service has already been instantiated`
1409
1412
  );
1410
1413
  }
1411
- __privateGet$3(this, _addedFactoryIds).add(factoryId);
1412
- __privateGet$3(this, _providedFactories).set(factoryId, toInternalServiceFactory(factory));
1414
+ __privateGet$4(this, _addedFactoryIds).add(factoryId);
1415
+ __privateGet$4(this, _providedFactories).set(factoryId, toInternalServiceFactory(factory));
1413
1416
  }
1414
1417
  getServiceRefs() {
1415
- return Array.from(__privateGet$3(this, _providedFactories).values()).map((f) => f.service);
1418
+ return Array.from(__privateGet$4(this, _providedFactories).values()).map((f) => f.service);
1416
1419
  }
1417
1420
  get(ref, pluginId) {
1418
1421
  var _a;
1419
- __privateGet$3(this, _instantiatedFactories).add(ref.id);
1420
- return (_a = __privateMethod$2(this, _resolveFactory, resolveFactory_fn).call(this, ref, pluginId)) == null ? void 0 : _a.then((factory) => {
1422
+ __privateGet$4(this, _instantiatedFactories).add(ref.id);
1423
+ return (_a = __privateMethod$4(this, _resolveFactory, resolveFactory_fn).call(this, ref, pluginId)) == null ? void 0 : _a.then((factory) => {
1421
1424
  if (factory.service.scope === "root") {
1422
- let existing = __privateGet$3(this, _rootServiceImplementations).get(factory);
1425
+ let existing = __privateGet$4(this, _rootServiceImplementations).get(factory);
1423
1426
  if (!existing) {
1424
- __privateMethod$2(this, _checkForMissingDeps, checkForMissingDeps_fn).call(this, factory, pluginId);
1427
+ __privateMethod$4(this, _checkForMissingDeps, checkForMissingDeps_fn).call(this, factory, pluginId);
1425
1428
  const rootDeps = new Array();
1426
1429
  for (const [name, serviceRef] of Object.entries(factory.deps)) {
1427
1430
  if (serviceRef.scope !== "root") {
@@ -1435,13 +1438,13 @@ const _ServiceRegistry = class _ServiceRegistry {
1435
1438
  existing = Promise.all(rootDeps).then(
1436
1439
  (entries) => factory.factory(Object.fromEntries(entries), void 0)
1437
1440
  );
1438
- __privateGet$3(this, _rootServiceImplementations).set(factory, existing);
1441
+ __privateGet$4(this, _rootServiceImplementations).set(factory, existing);
1439
1442
  }
1440
1443
  return existing;
1441
1444
  }
1442
- let implementation = __privateGet$3(this, _implementations).get(factory);
1445
+ let implementation = __privateGet$4(this, _implementations).get(factory);
1443
1446
  if (!implementation) {
1444
- __privateMethod$2(this, _checkForMissingDeps, checkForMissingDeps_fn).call(this, factory, pluginId);
1447
+ __privateMethod$4(this, _checkForMissingDeps, checkForMissingDeps_fn).call(this, factory, pluginId);
1445
1448
  const rootDeps = new Array();
1446
1449
  for (const [name, serviceRef] of Object.entries(factory.deps)) {
1447
1450
  if (serviceRef.scope === "root") {
@@ -1463,7 +1466,7 @@ const _ServiceRegistry = class _ServiceRegistry {
1463
1466
  }),
1464
1467
  byPlugin: /* @__PURE__ */ new Map()
1465
1468
  };
1466
- __privateGet$3(this, _implementations).set(factory, implementation);
1469
+ __privateGet$4(this, _implementations).set(factory, implementation);
1467
1470
  }
1468
1471
  let result = implementation.byPlugin.get(pluginId);
1469
1472
  if (!result) {
@@ -1501,18 +1504,18 @@ resolveFactory_fn = function(ref, pluginId) {
1501
1504
  toInternalServiceFactory(pluginMetadataServiceFactory({ pluginId }))
1502
1505
  );
1503
1506
  }
1504
- let resolvedFactory = __privateGet$3(this, _providedFactories).get(ref.id);
1507
+ let resolvedFactory = __privateGet$4(this, _providedFactories).get(ref.id);
1505
1508
  const { __defaultFactory: defaultFactory } = ref;
1506
1509
  if (!resolvedFactory && !defaultFactory) {
1507
1510
  return void 0;
1508
1511
  }
1509
1512
  if (!resolvedFactory) {
1510
- let loadedFactory = __privateGet$3(this, _loadedDefaultFactories).get(defaultFactory);
1513
+ let loadedFactory = __privateGet$4(this, _loadedDefaultFactories).get(defaultFactory);
1511
1514
  if (!loadedFactory) {
1512
1515
  loadedFactory = Promise.resolve().then(() => defaultFactory(ref)).then(
1513
1516
  (f) => toInternalServiceFactory(typeof f === "function" ? f() : f)
1514
1517
  );
1515
- __privateGet$3(this, _loadedDefaultFactories).set(defaultFactory, loadedFactory);
1518
+ __privateGet$4(this, _loadedDefaultFactories).set(defaultFactory, loadedFactory);
1516
1519
  }
1517
1520
  resolvedFactory = loadedFactory.catch((error) => {
1518
1521
  throw new Error(
@@ -1530,7 +1533,7 @@ checkForMissingDeps_fn = function(factory, pluginId) {
1530
1533
  if (ref.id === backendPluginApi.coreServices.pluginMetadata.id) {
1531
1534
  return false;
1532
1535
  }
1533
- if (__privateGet$3(this, _providedFactories).get(ref.id)) {
1536
+ if (__privateGet$4(this, _providedFactories).get(ref.id)) {
1534
1537
  return false;
1535
1538
  }
1536
1539
  return !ref.__defaultFactory;
@@ -1544,52 +1547,52 @@ checkForMissingDeps_fn = function(factory, pluginId) {
1544
1547
  };
1545
1548
  let ServiceRegistry = _ServiceRegistry;
1546
1549
 
1547
- var __accessCheck$2 = (obj, member, msg) => {
1550
+ var __accessCheck$4 = (obj, member, msg) => {
1548
1551
  if (!member.has(obj))
1549
1552
  throw TypeError("Cannot " + msg);
1550
1553
  };
1551
- var __privateGet$2 = (obj, member, getter) => {
1552
- __accessCheck$2(obj, member, "read from private field");
1554
+ var __privateGet$3 = (obj, member, getter) => {
1555
+ __accessCheck$4(obj, member, "read from private field");
1553
1556
  return getter ? getter.call(obj) : member.get(obj);
1554
1557
  };
1555
- var __privateAdd$2 = (obj, member, value) => {
1558
+ var __privateAdd$4 = (obj, member, value) => {
1556
1559
  if (member.has(obj))
1557
1560
  throw TypeError("Cannot add the same private member more than once");
1558
1561
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1559
1562
  };
1560
- var __privateSet$2 = (obj, member, value, setter) => {
1561
- __accessCheck$2(obj, member, "write to private field");
1563
+ var __privateSet$3 = (obj, member, value, setter) => {
1564
+ __accessCheck$4(obj, member, "write to private field");
1562
1565
  setter ? setter.call(obj, value) : member.set(obj, value);
1563
1566
  return value;
1564
1567
  };
1565
- var __privateMethod$1 = (obj, member, method) => {
1566
- __accessCheck$2(obj, member, "access private method");
1568
+ var __privateMethod$3 = (obj, member, method) => {
1569
+ __accessCheck$4(obj, member, "access private method");
1567
1570
  return method;
1568
1571
  };
1569
1572
  var _startPromise, _features, _extensionPoints, _serviceRegistry, _registeredFeatures, _getInitDeps, getInitDeps_fn, _addFeature, addFeature_fn, _doStart, doStart_fn, _getRootLifecycleImpl, getRootLifecycleImpl_fn, _getPluginLifecycleImpl, getPluginLifecycleImpl_fn;
1570
1573
  class BackendInitializer {
1571
1574
  constructor(defaultApiFactories) {
1572
- __privateAdd$2(this, _getInitDeps);
1573
- __privateAdd$2(this, _addFeature);
1574
- __privateAdd$2(this, _doStart);
1575
+ __privateAdd$4(this, _getInitDeps);
1576
+ __privateAdd$4(this, _addFeature);
1577
+ __privateAdd$4(this, _doStart);
1575
1578
  // Bit of a hacky way to grab the lifecycle services, potentially find a nicer way to do this
1576
- __privateAdd$2(this, _getRootLifecycleImpl);
1577
- __privateAdd$2(this, _getPluginLifecycleImpl);
1578
- __privateAdd$2(this, _startPromise, void 0);
1579
- __privateAdd$2(this, _features, new Array());
1580
- __privateAdd$2(this, _extensionPoints, /* @__PURE__ */ new Map());
1581
- __privateAdd$2(this, _serviceRegistry, void 0);
1582
- __privateAdd$2(this, _registeredFeatures, new Array());
1583
- __privateSet$2(this, _serviceRegistry, ServiceRegistry.create([...defaultApiFactories]));
1579
+ __privateAdd$4(this, _getRootLifecycleImpl);
1580
+ __privateAdd$4(this, _getPluginLifecycleImpl);
1581
+ __privateAdd$4(this, _startPromise, void 0);
1582
+ __privateAdd$4(this, _features, new Array());
1583
+ __privateAdd$4(this, _extensionPoints, /* @__PURE__ */ new Map());
1584
+ __privateAdd$4(this, _serviceRegistry, void 0);
1585
+ __privateAdd$4(this, _registeredFeatures, new Array());
1586
+ __privateSet$3(this, _serviceRegistry, ServiceRegistry.create([...defaultApiFactories]));
1584
1587
  }
1585
1588
  add(feature) {
1586
- if (__privateGet$2(this, _startPromise)) {
1589
+ if (__privateGet$3(this, _startPromise)) {
1587
1590
  throw new Error("feature can not be added after the backend has started");
1588
1591
  }
1589
- __privateGet$2(this, _registeredFeatures).push(Promise.resolve(feature));
1592
+ __privateGet$3(this, _registeredFeatures).push(Promise.resolve(feature));
1590
1593
  }
1591
1594
  async start() {
1592
- if (__privateGet$2(this, _startPromise)) {
1595
+ if (__privateGet$3(this, _startPromise)) {
1593
1596
  throw new Error("Backend has already started");
1594
1597
  }
1595
1598
  const exitHandler = async () => {
@@ -1607,18 +1610,18 @@ class BackendInitializer {
1607
1610
  process.addListener("SIGTERM", exitHandler);
1608
1611
  process.addListener("SIGINT", exitHandler);
1609
1612
  process.addListener("beforeExit", exitHandler);
1610
- __privateSet$2(this, _startPromise, __privateMethod$1(this, _doStart, doStart_fn).call(this));
1611
- await __privateGet$2(this, _startPromise);
1613
+ __privateSet$3(this, _startPromise, __privateMethod$3(this, _doStart, doStart_fn).call(this));
1614
+ await __privateGet$3(this, _startPromise);
1612
1615
  }
1613
1616
  async stop() {
1614
- if (!__privateGet$2(this, _startPromise)) {
1617
+ if (!__privateGet$3(this, _startPromise)) {
1615
1618
  return;
1616
1619
  }
1617
1620
  try {
1618
- await __privateGet$2(this, _startPromise);
1621
+ await __privateGet$3(this, _startPromise);
1619
1622
  } catch (error) {
1620
1623
  }
1621
- const lifecycleService = await __privateMethod$1(this, _getRootLifecycleImpl, getRootLifecycleImpl_fn).call(this);
1624
+ const lifecycleService = await __privateMethod$3(this, _getRootLifecycleImpl, getRootLifecycleImpl_fn).call(this);
1622
1625
  await lifecycleService.shutdown();
1623
1626
  }
1624
1627
  }
@@ -1632,7 +1635,7 @@ getInitDeps_fn = async function(deps, pluginId, moduleId) {
1632
1635
  const result = /* @__PURE__ */ new Map();
1633
1636
  const missingRefs = /* @__PURE__ */ new Set();
1634
1637
  for (const [name, ref] of Object.entries(deps)) {
1635
- const ep = __privateGet$2(this, _extensionPoints).get(ref.id);
1638
+ const ep = __privateGet$3(this, _extensionPoints).get(ref.id);
1636
1639
  if (ep) {
1637
1640
  if (ep.pluginId !== pluginId) {
1638
1641
  throw new Error(
@@ -1641,7 +1644,7 @@ getInitDeps_fn = async function(deps, pluginId, moduleId) {
1641
1644
  }
1642
1645
  result.set(name, ep.impl);
1643
1646
  } else {
1644
- const impl = await __privateGet$2(this, _serviceRegistry).get(
1647
+ const impl = await __privateGet$3(this, _serviceRegistry).get(
1645
1648
  ref,
1646
1649
  pluginId
1647
1650
  );
@@ -1668,14 +1671,14 @@ addFeature_fn = function(feature) {
1668
1671
  );
1669
1672
  }
1670
1673
  if (isServiceFactory(feature)) {
1671
- __privateGet$2(this, _serviceRegistry).add(feature);
1674
+ __privateGet$3(this, _serviceRegistry).add(feature);
1672
1675
  } else if (isInternalBackendFeature(feature)) {
1673
1676
  if (feature.version !== "v1") {
1674
1677
  throw new Error(
1675
1678
  `Failed to add feature, invalid version '${feature.version}'`
1676
1679
  );
1677
1680
  }
1678
- __privateGet$2(this, _features).push(feature);
1681
+ __privateGet$3(this, _features).push(feature);
1679
1682
  } else {
1680
1683
  throw new Error(
1681
1684
  `Failed to add feature, invalid feature ${JSON.stringify(feature)}`
@@ -1684,39 +1687,39 @@ addFeature_fn = function(feature) {
1684
1687
  };
1685
1688
  _doStart = new WeakSet();
1686
1689
  doStart_fn = async function() {
1687
- __privateGet$2(this, _serviceRegistry).checkForCircularDeps();
1688
- for (const feature of __privateGet$2(this, _registeredFeatures)) {
1689
- __privateMethod$1(this, _addFeature, addFeature_fn).call(this, await feature);
1690
+ __privateGet$3(this, _serviceRegistry).checkForCircularDeps();
1691
+ for (const feature of __privateGet$3(this, _registeredFeatures)) {
1692
+ __privateMethod$3(this, _addFeature, addFeature_fn).call(this, await feature);
1690
1693
  }
1691
- const featureDiscovery = await __privateGet$2(this, _serviceRegistry).get(
1694
+ const featureDiscovery = await __privateGet$3(this, _serviceRegistry).get(
1692
1695
  alpha.featureDiscoveryServiceRef,
1693
1696
  "root"
1694
1697
  );
1695
1698
  if (featureDiscovery) {
1696
1699
  const { features } = await featureDiscovery.getBackendFeatures();
1697
1700
  for (const feature of features) {
1698
- __privateMethod$1(this, _addFeature, addFeature_fn).call(this, feature);
1701
+ __privateMethod$3(this, _addFeature, addFeature_fn).call(this, feature);
1699
1702
  }
1700
- __privateGet$2(this, _serviceRegistry).checkForCircularDeps();
1703
+ __privateGet$3(this, _serviceRegistry).checkForCircularDeps();
1701
1704
  }
1702
- for (const ref of __privateGet$2(this, _serviceRegistry).getServiceRefs()) {
1705
+ for (const ref of __privateGet$3(this, _serviceRegistry).getServiceRefs()) {
1703
1706
  if (ref.scope === "root") {
1704
- await __privateGet$2(this, _serviceRegistry).get(ref, "root");
1707
+ await __privateGet$3(this, _serviceRegistry).get(ref, "root");
1705
1708
  }
1706
1709
  }
1707
1710
  const pluginInits = /* @__PURE__ */ new Map();
1708
1711
  const moduleInits = /* @__PURE__ */ new Map();
1709
- for (const feature of __privateGet$2(this, _features)) {
1712
+ for (const feature of __privateGet$3(this, _features)) {
1710
1713
  for (const r of feature.getRegistrations()) {
1711
1714
  const provides = /* @__PURE__ */ new Set();
1712
1715
  if (r.type === "plugin" || r.type === "module") {
1713
1716
  for (const [extRef, extImpl] of r.extensionPoints) {
1714
- if (__privateGet$2(this, _extensionPoints).has(extRef.id)) {
1717
+ if (__privateGet$3(this, _extensionPoints).has(extRef.id)) {
1715
1718
  throw new Error(
1716
1719
  `ExtensionPoint with ID '${extRef.id}' is already registered`
1717
1720
  );
1718
1721
  }
1719
- __privateGet$2(this, _extensionPoints).set(extRef.id, {
1722
+ __privateGet$3(this, _extensionPoints).set(extRef.id, {
1720
1723
  impl: extImpl,
1721
1724
  pluginId: r.pluginId
1722
1725
  });
@@ -1776,7 +1779,7 @@ doStart_fn = async function() {
1776
1779
  }
1777
1780
  await tree.parallelTopologicalTraversal(
1778
1781
  async ({ moduleId, moduleInit }) => {
1779
- const moduleDeps = await __privateMethod$1(this, _getInitDeps, getInitDeps_fn).call(this, moduleInit.init.deps, pluginId, moduleId);
1782
+ const moduleDeps = await __privateMethod$3(this, _getInitDeps, getInitDeps_fn).call(this, moduleInit.init.deps, pluginId, moduleId);
1780
1783
  await moduleInit.init.func(moduleDeps).catch((error) => {
1781
1784
  throw new errors.ForwardedError(
1782
1785
  `Module '${moduleId}' for plugin '${pluginId}' startup failed`,
@@ -1788,7 +1791,7 @@ doStart_fn = async function() {
1788
1791
  }
1789
1792
  const pluginInit = pluginInits.get(pluginId);
1790
1793
  if (pluginInit) {
1791
- const pluginDeps = await __privateMethod$1(this, _getInitDeps, getInitDeps_fn).call(this, pluginInit.init.deps, pluginId);
1794
+ const pluginDeps = await __privateMethod$3(this, _getInitDeps, getInitDeps_fn).call(this, pluginInit.init.deps, pluginId);
1792
1795
  await pluginInit.init.func(pluginDeps).catch((error) => {
1793
1796
  throw new errors.ForwardedError(
1794
1797
  `Plugin '${pluginId}' startup failed`,
@@ -1796,14 +1799,14 @@ doStart_fn = async function() {
1796
1799
  );
1797
1800
  });
1798
1801
  }
1799
- const lifecycleService2 = await __privateMethod$1(this, _getPluginLifecycleImpl, getPluginLifecycleImpl_fn).call(this, pluginId);
1802
+ const lifecycleService2 = await __privateMethod$3(this, _getPluginLifecycleImpl, getPluginLifecycleImpl_fn).call(this, pluginId);
1800
1803
  await lifecycleService2.startup();
1801
1804
  })
1802
1805
  );
1803
- const lifecycleService = await __privateMethod$1(this, _getRootLifecycleImpl, getRootLifecycleImpl_fn).call(this);
1806
+ const lifecycleService = await __privateMethod$3(this, _getRootLifecycleImpl, getRootLifecycleImpl_fn).call(this);
1804
1807
  await lifecycleService.startup();
1805
1808
  if (process.env.NODE_ENV !== "test") {
1806
- const rootLogger = await __privateGet$2(this, _serviceRegistry).get(
1809
+ const rootLogger = await __privateGet$3(this, _serviceRegistry).get(
1807
1810
  backendPluginApi.coreServices.rootLogger,
1808
1811
  "root"
1809
1812
  );
@@ -1819,7 +1822,7 @@ doStart_fn = async function() {
1819
1822
  };
1820
1823
  _getRootLifecycleImpl = new WeakSet();
1821
1824
  getRootLifecycleImpl_fn = async function() {
1822
- const lifecycleService = await __privateGet$2(this, _serviceRegistry).get(
1825
+ const lifecycleService = await __privateGet$3(this, _serviceRegistry).get(
1823
1826
  backendPluginApi.coreServices.rootLifecycle,
1824
1827
  "root"
1825
1828
  );
@@ -1830,7 +1833,7 @@ getRootLifecycleImpl_fn = async function() {
1830
1833
  };
1831
1834
  _getPluginLifecycleImpl = new WeakSet();
1832
1835
  getPluginLifecycleImpl_fn = async function(pluginId) {
1833
- const lifecycleService = await __privateGet$2(this, _serviceRegistry).get(
1836
+ const lifecycleService = await __privateGet$3(this, _serviceRegistry).get(
1834
1837
  backendPluginApi.coreServices.lifecycle,
1835
1838
  pluginId
1836
1839
  );
@@ -1846,42 +1849,42 @@ function isInternalBackendFeature(feature) {
1846
1849
  return typeof feature.getRegistrations === "function";
1847
1850
  }
1848
1851
 
1849
- var __accessCheck$1 = (obj, member, msg) => {
1852
+ var __accessCheck$3 = (obj, member, msg) => {
1850
1853
  if (!member.has(obj))
1851
1854
  throw TypeError("Cannot " + msg);
1852
1855
  };
1853
- var __privateGet$1 = (obj, member, getter) => {
1854
- __accessCheck$1(obj, member, "read from private field");
1856
+ var __privateGet$2 = (obj, member, getter) => {
1857
+ __accessCheck$3(obj, member, "read from private field");
1855
1858
  return getter ? getter.call(obj) : member.get(obj);
1856
1859
  };
1857
- var __privateAdd$1 = (obj, member, value) => {
1860
+ var __privateAdd$3 = (obj, member, value) => {
1858
1861
  if (member.has(obj))
1859
1862
  throw TypeError("Cannot add the same private member more than once");
1860
1863
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1861
1864
  };
1862
- var __privateSet$1 = (obj, member, value, setter) => {
1863
- __accessCheck$1(obj, member, "write to private field");
1865
+ var __privateSet$2 = (obj, member, value, setter) => {
1866
+ __accessCheck$3(obj, member, "write to private field");
1864
1867
  setter ? setter.call(obj, value) : member.set(obj, value);
1865
1868
  return value;
1866
1869
  };
1867
1870
  var _initializer;
1868
1871
  class BackstageBackend {
1869
1872
  constructor(defaultServiceFactories) {
1870
- __privateAdd$1(this, _initializer, void 0);
1871
- __privateSet$1(this, _initializer, new BackendInitializer(defaultServiceFactories));
1873
+ __privateAdd$3(this, _initializer, void 0);
1874
+ __privateSet$2(this, _initializer, new BackendInitializer(defaultServiceFactories));
1872
1875
  }
1873
1876
  add(feature) {
1874
1877
  if (isPromise(feature)) {
1875
- __privateGet$1(this, _initializer).add(feature.then((f) => unwrapFeature(f.default)));
1878
+ __privateGet$2(this, _initializer).add(feature.then((f) => unwrapFeature(f.default)));
1876
1879
  } else {
1877
- __privateGet$1(this, _initializer).add(unwrapFeature(feature));
1880
+ __privateGet$2(this, _initializer).add(unwrapFeature(feature));
1878
1881
  }
1879
1882
  }
1880
1883
  async start() {
1881
- await __privateGet$1(this, _initializer).start();
1884
+ await __privateGet$2(this, _initializer).start();
1882
1885
  }
1883
1886
  async stop() {
1884
- await __privateGet$1(this, _initializer).stop();
1887
+ await __privateGet$2(this, _initializer).stop();
1885
1888
  }
1886
1889
  }
1887
1890
  _initializer = new WeakMap();
@@ -1927,6 +1930,176 @@ function createSpecializedBackend(options) {
1927
1930
  return new BackstageBackend(services);
1928
1931
  }
1929
1932
 
1933
+ var __accessCheck$2 = (obj, member, msg) => {
1934
+ if (!member.has(obj))
1935
+ throw TypeError("Cannot " + msg);
1936
+ };
1937
+ var __privateAdd$2 = (obj, member, value) => {
1938
+ if (member.has(obj))
1939
+ throw TypeError("Cannot add the same private member more than once");
1940
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1941
+ };
1942
+ var __privateMethod$2 = (obj, member, method) => {
1943
+ __accessCheck$2(obj, member, "access private method");
1944
+ return method;
1945
+ };
1946
+ var _getJwtExpiration, getJwtExpiration_fn;
1947
+ function createCredentialsWithServicePrincipal(sub, token) {
1948
+ return {
1949
+ $$type: "@backstage/BackstageCredentials",
1950
+ version: "v1",
1951
+ token,
1952
+ principal: {
1953
+ type: "service",
1954
+ subject: sub
1955
+ }
1956
+ };
1957
+ }
1958
+ function createCredentialsWithUserPrincipal(sub, token, expiresAt) {
1959
+ return {
1960
+ $$type: "@backstage/BackstageCredentials",
1961
+ version: "v1",
1962
+ token,
1963
+ expiresAt,
1964
+ principal: {
1965
+ type: "user",
1966
+ userEntityRef: sub
1967
+ }
1968
+ };
1969
+ }
1970
+ function createCredentialsWithNonePrincipal() {
1971
+ return {
1972
+ $$type: "@backstage/BackstageCredentials",
1973
+ version: "v1",
1974
+ principal: {
1975
+ type: "none"
1976
+ }
1977
+ };
1978
+ }
1979
+ function toInternalBackstageCredentials(credentials) {
1980
+ if (credentials.$$type !== "@backstage/BackstageCredentials") {
1981
+ throw new Error("Invalid credential type");
1982
+ }
1983
+ const internalCredentials = credentials;
1984
+ if (internalCredentials.version !== "v1") {
1985
+ throw new Error(
1986
+ `Invalid credential version ${internalCredentials.version}`
1987
+ );
1988
+ }
1989
+ return internalCredentials;
1990
+ }
1991
+ class DefaultAuthService {
1992
+ constructor(tokenManager, identity, pluginId, disableDefaultAuthPolicy) {
1993
+ this.tokenManager = tokenManager;
1994
+ this.identity = identity;
1995
+ this.pluginId = pluginId;
1996
+ this.disableDefaultAuthPolicy = disableDefaultAuthPolicy;
1997
+ __privateAdd$2(this, _getJwtExpiration);
1998
+ }
1999
+ // allowLimitedAccess is currently ignored, since we currently always use the full user tokens
2000
+ async authenticate(token) {
2001
+ const { sub, aud } = jose.decodeJwt(token);
2002
+ if (sub === "backstage-server" && !aud) {
2003
+ await this.tokenManager.authenticate(token);
2004
+ return createCredentialsWithServicePrincipal("external:backstage-plugin");
2005
+ }
2006
+ const identity = await this.identity.getIdentity({
2007
+ request: {
2008
+ headers: { authorization: `Bearer ${token}` }
2009
+ }
2010
+ });
2011
+ if (!identity) {
2012
+ throw new errors.AuthenticationError("Invalid user token");
2013
+ }
2014
+ return createCredentialsWithUserPrincipal(
2015
+ identity.identity.userEntityRef,
2016
+ token,
2017
+ __privateMethod$2(this, _getJwtExpiration, getJwtExpiration_fn).call(this, token)
2018
+ );
2019
+ }
2020
+ isPrincipal(credentials, type) {
2021
+ const principal = credentials.principal;
2022
+ if (type === "unknown") {
2023
+ return true;
2024
+ }
2025
+ if (principal.type !== type) {
2026
+ return false;
2027
+ }
2028
+ return true;
2029
+ }
2030
+ async getNoneCredentials() {
2031
+ return createCredentialsWithNonePrincipal();
2032
+ }
2033
+ async getOwnServiceCredentials() {
2034
+ return createCredentialsWithServicePrincipal(`plugin:${this.pluginId}`);
2035
+ }
2036
+ async getPluginRequestToken(options) {
2037
+ const internalForward = toInternalBackstageCredentials(options.onBehalfOf);
2038
+ const { type } = internalForward.principal;
2039
+ if (type === "none" && this.disableDefaultAuthPolicy) {
2040
+ return { token: "" };
2041
+ }
2042
+ switch (type) {
2043
+ case "service":
2044
+ return this.tokenManager.getToken();
2045
+ case "user":
2046
+ if (!internalForward.token) {
2047
+ throw new Error("User credentials is unexpectedly missing token");
2048
+ }
2049
+ return { token: internalForward.token };
2050
+ default:
2051
+ throw new errors.AuthenticationError(
2052
+ `Refused to issue service token for credential type '${type}'`
2053
+ );
2054
+ }
2055
+ }
2056
+ async getLimitedUserToken(credentials) {
2057
+ const internalCredentials = toInternalBackstageCredentials(credentials);
2058
+ const { token } = internalCredentials;
2059
+ if (!token) {
2060
+ throw new errors.AuthenticationError(
2061
+ "User credentials is unexpectedly missing token"
2062
+ );
2063
+ }
2064
+ return { token, expiresAt: __privateMethod$2(this, _getJwtExpiration, getJwtExpiration_fn).call(this, token) };
2065
+ }
2066
+ }
2067
+ _getJwtExpiration = new WeakSet();
2068
+ getJwtExpiration_fn = function(token) {
2069
+ const { exp } = jose.decodeJwt(token);
2070
+ if (!exp) {
2071
+ throw new errors.AuthenticationError("User token is missing expiration");
2072
+ }
2073
+ return new Date(exp * 1e3);
2074
+ };
2075
+ const authServiceFactory = backendPluginApi.createServiceFactory({
2076
+ service: backendPluginApi.coreServices.auth,
2077
+ deps: {
2078
+ config: backendPluginApi.coreServices.rootConfig,
2079
+ logger: backendPluginApi.coreServices.rootLogger,
2080
+ plugin: backendPluginApi.coreServices.pluginMetadata,
2081
+ identity: backendPluginApi.coreServices.identity,
2082
+ // Re-using the token manager makes sure that we use the same generated keys for
2083
+ // development as plugins that have not yet been migrated. It's important that this
2084
+ // keeps working as long as there are plugins that have not been migrated to the
2085
+ // new auth services in the new backend system.
2086
+ tokenManager: backendPluginApi.coreServices.tokenManager
2087
+ },
2088
+ async factory({ config, plugin, identity, tokenManager }) {
2089
+ const disableDefaultAuthPolicy = Boolean(
2090
+ config.getOptionalBoolean(
2091
+ "backend.auth.dangerouslyDisableDefaultAuthPolicy"
2092
+ )
2093
+ );
2094
+ return new DefaultAuthService(
2095
+ tokenManager,
2096
+ identity,
2097
+ plugin.getId(),
2098
+ disableDefaultAuthPolicy
2099
+ );
2100
+ }
2101
+ });
2102
+
1930
2103
  const cacheServiceFactory = backendPluginApi.createServiceFactory({
1931
2104
  service: backendPluginApi.coreServices.cache,
1932
2105
  deps: {
@@ -2071,6 +2244,208 @@ const discoveryServiceFactory = backendPluginApi.createServiceFactory({
2071
2244
  }
2072
2245
  });
2073
2246
 
2247
+ var __accessCheck$1 = (obj, member, msg) => {
2248
+ if (!member.has(obj))
2249
+ throw TypeError("Cannot " + msg);
2250
+ };
2251
+ var __privateGet$1 = (obj, member, getter) => {
2252
+ __accessCheck$1(obj, member, "read from private field");
2253
+ return getter ? getter.call(obj) : member.get(obj);
2254
+ };
2255
+ var __privateAdd$1 = (obj, member, value) => {
2256
+ if (member.has(obj))
2257
+ throw TypeError("Cannot add the same private member more than once");
2258
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2259
+ };
2260
+ var __privateSet$1 = (obj, member, value, setter) => {
2261
+ __accessCheck$1(obj, member, "write to private field");
2262
+ setter ? setter.call(obj, value) : member.set(obj, value);
2263
+ return value;
2264
+ };
2265
+ var __privateMethod$1 = (obj, member, method) => {
2266
+ __accessCheck$1(obj, member, "access private method");
2267
+ return method;
2268
+ };
2269
+ var _auth, _discovery, _pluginId, _extractCredentialsFromRequest, extractCredentialsFromRequest_fn, _extractLimitedCredentialsFromRequest, extractLimitedCredentialsFromRequest_fn, _getCredentials, getCredentials_fn, _getLimitedCredentials, getLimitedCredentials_fn, _existingCookieExpiration, existingCookieExpiration_fn;
2270
+ const FIVE_MINUTES_MS = 5 * 60 * 1e3;
2271
+ const BACKSTAGE_AUTH_COOKIE = "backstage-auth";
2272
+ function getTokenFromRequest(req) {
2273
+ const authHeader = req.headers.authorization;
2274
+ if (typeof authHeader === "string") {
2275
+ const matches = authHeader.match(/^Bearer[ ]+(\S+)$/i);
2276
+ const token = matches == null ? void 0 : matches[1];
2277
+ if (token) {
2278
+ return token;
2279
+ }
2280
+ }
2281
+ return void 0;
2282
+ }
2283
+ function getCookieFromRequest(req) {
2284
+ const cookieHeader = req.headers.cookie;
2285
+ if (cookieHeader) {
2286
+ const cookies = cookie.parse(cookieHeader);
2287
+ const token = cookies[BACKSTAGE_AUTH_COOKIE];
2288
+ if (token) {
2289
+ return token;
2290
+ }
2291
+ }
2292
+ return void 0;
2293
+ }
2294
+ function willExpireSoon(expiresAt) {
2295
+ return Date.now() + FIVE_MINUTES_MS > expiresAt.getTime();
2296
+ }
2297
+ const credentialsSymbol = Symbol("backstage-credentials");
2298
+ const limitedCredentialsSymbol = Symbol("backstage-limited-credentials");
2299
+ class DefaultHttpAuthService {
2300
+ constructor(auth, discovery, pluginId) {
2301
+ __privateAdd$1(this, _extractCredentialsFromRequest);
2302
+ __privateAdd$1(this, _extractLimitedCredentialsFromRequest);
2303
+ __privateAdd$1(this, _getCredentials);
2304
+ __privateAdd$1(this, _getLimitedCredentials);
2305
+ __privateAdd$1(this, _existingCookieExpiration);
2306
+ __privateAdd$1(this, _auth, void 0);
2307
+ __privateAdd$1(this, _discovery, void 0);
2308
+ __privateAdd$1(this, _pluginId, void 0);
2309
+ __privateSet$1(this, _auth, auth);
2310
+ __privateSet$1(this, _discovery, discovery);
2311
+ __privateSet$1(this, _pluginId, pluginId);
2312
+ }
2313
+ async credentials(req, options) {
2314
+ const credentials = (options == null ? void 0 : options.allowLimitedAccess) ? await __privateMethod$1(this, _getLimitedCredentials, getLimitedCredentials_fn).call(this, req) : await __privateMethod$1(this, _getCredentials, getCredentials_fn).call(this, req);
2315
+ const allowed = options == null ? void 0 : options.allow;
2316
+ if (!allowed) {
2317
+ return credentials;
2318
+ }
2319
+ if (__privateGet$1(this, _auth).isPrincipal(credentials, "none")) {
2320
+ if (allowed.includes("none")) {
2321
+ return credentials;
2322
+ }
2323
+ throw new errors.AuthenticationError("Missing credentials");
2324
+ } else if (__privateGet$1(this, _auth).isPrincipal(credentials, "user")) {
2325
+ if (allowed.includes("user")) {
2326
+ return credentials;
2327
+ }
2328
+ throw new errors.NotAllowedError(
2329
+ `This endpoint does not allow 'user' credentials`
2330
+ );
2331
+ } else if (__privateGet$1(this, _auth).isPrincipal(credentials, "service")) {
2332
+ if (allowed.includes("service")) {
2333
+ return credentials;
2334
+ }
2335
+ throw new errors.NotAllowedError(
2336
+ `This endpoint does not allow 'service' credentials`
2337
+ );
2338
+ }
2339
+ throw new errors.NotAllowedError(
2340
+ "Unknown principal type, this should never happen"
2341
+ );
2342
+ }
2343
+ async issueUserCookie(res, options) {
2344
+ if (res.headersSent) {
2345
+ throw new Error("Failed to issue user cookie, headers were already sent");
2346
+ }
2347
+ let credentials;
2348
+ if (options == null ? void 0 : options.credentials) {
2349
+ if (!__privateGet$1(this, _auth).isPrincipal(options.credentials, "user")) {
2350
+ throw new errors.AuthenticationError(
2351
+ "Refused to issue cookie for non-user principal"
2352
+ );
2353
+ }
2354
+ credentials = options.credentials;
2355
+ } else {
2356
+ credentials = await this.credentials(res.req, { allow: ["user"] });
2357
+ }
2358
+ const existingExpiresAt = await __privateMethod$1(this, _existingCookieExpiration, existingCookieExpiration_fn).call(this, res.req);
2359
+ if (existingExpiresAt && !willExpireSoon(existingExpiresAt)) {
2360
+ return { expiresAt: existingExpiresAt };
2361
+ }
2362
+ const originHeader = res.req.headers.origin;
2363
+ const origin = !originHeader || originHeader === "null" ? void 0 : originHeader;
2364
+ const externalBaseUrlStr = await __privateGet$1(this, _discovery).getExternalBaseUrl(
2365
+ __privateGet$1(this, _pluginId)
2366
+ );
2367
+ const externalBaseUrl = new URL(origin != null ? origin : externalBaseUrlStr);
2368
+ const { token, expiresAt } = await __privateGet$1(this, _auth).getLimitedUserToken(
2369
+ credentials
2370
+ );
2371
+ if (!token) {
2372
+ throw new Error("User credentials is unexpectedly missing token");
2373
+ }
2374
+ const secure = externalBaseUrl.protocol === "https:" || externalBaseUrl.hostname === "localhost";
2375
+ res.cookie(BACKSTAGE_AUTH_COOKIE, token, {
2376
+ domain: externalBaseUrl.hostname,
2377
+ httpOnly: true,
2378
+ expires: expiresAt,
2379
+ secure,
2380
+ priority: "high",
2381
+ sameSite: secure ? "none" : "lax"
2382
+ });
2383
+ return { expiresAt };
2384
+ }
2385
+ }
2386
+ _auth = new WeakMap();
2387
+ _discovery = new WeakMap();
2388
+ _pluginId = new WeakMap();
2389
+ _extractCredentialsFromRequest = new WeakSet();
2390
+ extractCredentialsFromRequest_fn = async function(req) {
2391
+ const token = getTokenFromRequest(req);
2392
+ if (!token) {
2393
+ return await __privateGet$1(this, _auth).getNoneCredentials();
2394
+ }
2395
+ return await __privateGet$1(this, _auth).authenticate(token);
2396
+ };
2397
+ _extractLimitedCredentialsFromRequest = new WeakSet();
2398
+ extractLimitedCredentialsFromRequest_fn = async function(req) {
2399
+ const token = getTokenFromRequest(req);
2400
+ if (token) {
2401
+ return await __privateGet$1(this, _auth).authenticate(token, {
2402
+ allowLimitedAccess: true
2403
+ });
2404
+ }
2405
+ const cookie = getCookieFromRequest(req);
2406
+ if (cookie) {
2407
+ return await __privateGet$1(this, _auth).authenticate(cookie, {
2408
+ allowLimitedAccess: true
2409
+ });
2410
+ }
2411
+ return await __privateGet$1(this, _auth).getNoneCredentials();
2412
+ };
2413
+ _getCredentials = new WeakSet();
2414
+ getCredentials_fn = async function(req) {
2415
+ var _a;
2416
+ return (_a = req[credentialsSymbol]) != null ? _a : req[credentialsSymbol] = __privateMethod$1(this, _extractCredentialsFromRequest, extractCredentialsFromRequest_fn).call(this, req);
2417
+ };
2418
+ _getLimitedCredentials = new WeakSet();
2419
+ getLimitedCredentials_fn = async function(req) {
2420
+ var _a;
2421
+ return (_a = req[limitedCredentialsSymbol]) != null ? _a : req[limitedCredentialsSymbol] = __privateMethod$1(this, _extractLimitedCredentialsFromRequest, extractLimitedCredentialsFromRequest_fn).call(this, req);
2422
+ };
2423
+ _existingCookieExpiration = new WeakSet();
2424
+ existingCookieExpiration_fn = async function(req) {
2425
+ const existingCookie = getCookieFromRequest(req);
2426
+ if (!existingCookie) {
2427
+ return void 0;
2428
+ }
2429
+ const existingCredentials = await __privateGet$1(this, _auth).authenticate(existingCookie, {
2430
+ allowLimitedAccess: true
2431
+ });
2432
+ if (!__privateGet$1(this, _auth).isPrincipal(existingCredentials, "user")) {
2433
+ return void 0;
2434
+ }
2435
+ return existingCredentials.expiresAt;
2436
+ };
2437
+ const httpAuthServiceFactory = backendPluginApi.createServiceFactory({
2438
+ service: backendPluginApi.coreServices.httpAuth,
2439
+ deps: {
2440
+ auth: backendPluginApi.coreServices.auth,
2441
+ discovery: backendPluginApi.coreServices.discovery,
2442
+ plugin: backendPluginApi.coreServices.pluginMetadata
2443
+ },
2444
+ async factory({ auth, discovery, plugin }) {
2445
+ return new DefaultHttpAuthService(auth, discovery, plugin.getId());
2446
+ }
2447
+ });
2448
+
2074
2449
  const DEFAULT_TIMEOUT = { seconds: 5 };
2075
2450
  function createLifecycleMiddleware(options) {
2076
2451
  const { lifecycle, startupRequestPauseTimeout = DEFAULT_TIMEOUT } = options;
@@ -2115,24 +2490,87 @@ function createLifecycleMiddleware(options) {
2115
2490
  };
2116
2491
  }
2117
2492
 
2493
+ function createPathPolicyPredicate(policyPath) {
2494
+ if (policyPath === "/" || policyPath === "*") {
2495
+ return () => true;
2496
+ }
2497
+ const pathRegex = pathToRegexp.pathToRegexp(policyPath, void 0, {
2498
+ end: false
2499
+ });
2500
+ return (path) => {
2501
+ return pathRegex.test(path);
2502
+ };
2503
+ }
2504
+ function createCredentialsBarrier(options) {
2505
+ const { httpAuth, config } = options;
2506
+ const disableDefaultAuthPolicy = config.getOptionalBoolean(
2507
+ "backend.auth.dangerouslyDisableDefaultAuthPolicy"
2508
+ );
2509
+ if (disableDefaultAuthPolicy) {
2510
+ return {
2511
+ middleware: (_req, _res, next) => next(),
2512
+ addAuthPolicy: () => {
2513
+ }
2514
+ };
2515
+ }
2516
+ const unauthenticatedPredicates = new Array();
2517
+ const cookiePredicates = new Array();
2518
+ const middleware = (req, _, next) => {
2519
+ const allowsUnauthenticated = unauthenticatedPredicates.some(
2520
+ (predicate) => predicate(req.path)
2521
+ );
2522
+ if (allowsUnauthenticated) {
2523
+ next();
2524
+ return;
2525
+ }
2526
+ const allowsCookie = cookiePredicates.some(
2527
+ (predicate) => predicate(req.path)
2528
+ );
2529
+ httpAuth.credentials(req, {
2530
+ allow: ["user", "service"],
2531
+ allowLimitedAccess: allowsCookie
2532
+ }).then(
2533
+ () => next(),
2534
+ (err) => next(err)
2535
+ );
2536
+ };
2537
+ const addAuthPolicy = (policy) => {
2538
+ if (policy.allow === "unauthenticated") {
2539
+ unauthenticatedPredicates.push(createPathPolicyPredicate(policy.path));
2540
+ } else if (policy.allow === "user-cookie") {
2541
+ cookiePredicates.push(createPathPolicyPredicate(policy.path));
2542
+ } else {
2543
+ throw new Error("Invalid auth policy");
2544
+ }
2545
+ };
2546
+ return { middleware, addAuthPolicy };
2547
+ }
2548
+
2118
2549
  const httpRouterServiceFactory = backendPluginApi.createServiceFactory(
2119
2550
  (options) => ({
2120
2551
  service: backendPluginApi.coreServices.httpRouter,
2121
2552
  deps: {
2122
2553
  plugin: backendPluginApi.coreServices.pluginMetadata,
2554
+ config: backendPluginApi.coreServices.rootConfig,
2123
2555
  lifecycle: backendPluginApi.coreServices.lifecycle,
2124
- rootHttpRouter: backendPluginApi.coreServices.rootHttpRouter
2556
+ rootHttpRouter: backendPluginApi.coreServices.rootHttpRouter,
2557
+ httpAuth: backendPluginApi.coreServices.httpAuth
2125
2558
  },
2126
- async factory({ plugin, rootHttpRouter, lifecycle }) {
2559
+ async factory({ httpAuth, config, plugin, rootHttpRouter, lifecycle }) {
2127
2560
  var _a;
2128
2561
  const getPath = (_a = options == null ? void 0 : options.getPath) != null ? _a : (id) => `/api/${id}`;
2129
2562
  const path = getPath(plugin.getId());
2130
2563
  const router = PromiseRouter__default["default"]();
2131
2564
  rootHttpRouter.use(path, router);
2565
+ const credentialsBarrier = createCredentialsBarrier({ httpAuth, config });
2132
2566
  router.use(createLifecycleMiddleware({ lifecycle }));
2567
+ router.use(credentialsBarrier.middleware);
2133
2568
  return {
2134
2569
  use(handler) {
2135
2570
  router.use(handler);
2571
+ },
2572
+ addAuthPolicy(policy) {
2573
+ credentialsBarrier.addAuthPolicy(policy);
2136
2574
  }
2137
2575
  };
2138
2576
  }
@@ -2165,12 +2603,14 @@ const loggerServiceFactory = backendPluginApi.createServiceFactory({
2165
2603
  const permissionsServiceFactory = backendPluginApi.createServiceFactory({
2166
2604
  service: backendPluginApi.coreServices.permissions,
2167
2605
  deps: {
2606
+ auth: backendPluginApi.coreServices.auth,
2168
2607
  config: backendPluginApi.coreServices.rootConfig,
2169
2608
  discovery: backendPluginApi.coreServices.discovery,
2170
2609
  tokenManager: backendPluginApi.coreServices.tokenManager
2171
2610
  },
2172
- async factory({ config, discovery, tokenManager }) {
2611
+ async factory({ auth, config, discovery, tokenManager }) {
2173
2612
  return pluginPermissionNode.ServerPermissionClient.fromConfig(config, {
2613
+ auth,
2174
2614
  discovery,
2175
2615
  tokenManager
2176
2616
  });
@@ -2383,10 +2823,40 @@ const urlReaderServiceFactory = backendPluginApi.createServiceFactory({
2383
2823
  }
2384
2824
  });
2385
2825
 
2826
+ class DefaultUserInfoService {
2827
+ async getUserInfo(credentials) {
2828
+ const internalCredentials = toInternalBackstageCredentials(credentials);
2829
+ if (internalCredentials.principal.type !== "user") {
2830
+ throw new Error("Only user credentials are supported");
2831
+ }
2832
+ if (!internalCredentials.token) {
2833
+ throw new Error("User credentials is unexpectedly missing token");
2834
+ }
2835
+ const { sub: userEntityRef, ent: ownershipEntityRefs = [] } = jose.decodeJwt(
2836
+ internalCredentials.token
2837
+ );
2838
+ if (typeof userEntityRef !== "string") {
2839
+ throw new Error("User entity ref must be a string");
2840
+ }
2841
+ if (!Array.isArray(ownershipEntityRefs) || ownershipEntityRefs.some((ref) => typeof ref !== "string")) {
2842
+ throw new Error("Ownership entity refs must be an array of strings");
2843
+ }
2844
+ return { userEntityRef, ownershipEntityRefs };
2845
+ }
2846
+ }
2847
+ const userInfoServiceFactory = backendPluginApi.createServiceFactory({
2848
+ service: backendPluginApi.coreServices.userInfo,
2849
+ deps: {},
2850
+ async factory() {
2851
+ return new DefaultUserInfoService();
2852
+ }
2853
+ });
2854
+
2386
2855
  exports.DefaultRootHttpRouter = DefaultRootHttpRouter;
2387
2856
  exports.HostDiscovery = HostDiscovery;
2388
2857
  exports.MiddlewareFactory = MiddlewareFactory;
2389
2858
  exports.WinstonLogger = WinstonLogger;
2859
+ exports.authServiceFactory = authServiceFactory;
2390
2860
  exports.cacheServiceFactory = cacheServiceFactory;
2391
2861
  exports.createConfigSecretEnumerator = createConfigSecretEnumerator;
2392
2862
  exports.createHttpServer = createHttpServer;
@@ -2394,6 +2864,7 @@ exports.createLifecycleMiddleware = createLifecycleMiddleware;
2394
2864
  exports.createSpecializedBackend = createSpecializedBackend;
2395
2865
  exports.databaseServiceFactory = databaseServiceFactory;
2396
2866
  exports.discoveryServiceFactory = discoveryServiceFactory;
2867
+ exports.httpAuthServiceFactory = httpAuthServiceFactory;
2397
2868
  exports.httpRouterServiceFactory = httpRouterServiceFactory;
2398
2869
  exports.identityServiceFactory = identityServiceFactory;
2399
2870
  exports.lifecycleServiceFactory = lifecycleServiceFactory;
@@ -2410,4 +2881,5 @@ exports.rootLoggerServiceFactory = rootLoggerServiceFactory;
2410
2881
  exports.schedulerServiceFactory = schedulerServiceFactory;
2411
2882
  exports.tokenManagerServiceFactory = tokenManagerServiceFactory;
2412
2883
  exports.urlReaderServiceFactory = urlReaderServiceFactory;
2884
+ exports.userInfoServiceFactory = userInfoServiceFactory;
2413
2885
  //# sourceMappingURL=index.cjs.js.map