@backstage/plugin-permission-backend 0.5.11-next.0 → 0.5.11-next.1
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/CHANGELOG.md +13 -0
- package/dist/index.cjs.js +1 -5
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/package.json +8 -8
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# @backstage/plugin-permission-backend
|
|
2
2
|
|
|
3
|
+
## 0.5.11-next.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 667d917488: Updated dependency `msw` to `^0.47.0`.
|
|
8
|
+
- 87ec2ba4d6: Updated dependency `msw` to `^0.46.0`.
|
|
9
|
+
- 2cbd533426: Uptake the `IdentityApi` change to use `getIdentity` instead of `authenticate` for retrieving the logged in users identity.
|
|
10
|
+
- Updated dependencies
|
|
11
|
+
- @backstage/backend-common@0.15.1-next.2
|
|
12
|
+
- @backstage/plugin-auth-node@0.2.5-next.2
|
|
13
|
+
- @backstage/plugin-permission-common@0.6.4-next.1
|
|
14
|
+
- @backstage/plugin-permission-node@0.6.5-next.2
|
|
15
|
+
|
|
3
16
|
## 0.5.11-next.0
|
|
4
17
|
|
|
5
18
|
### Patch Changes
|
package/dist/index.cjs.js
CHANGED
|
@@ -7,7 +7,6 @@ var express = require('express');
|
|
|
7
7
|
var Router = require('express-promise-router');
|
|
8
8
|
var backendCommon = require('@backstage/backend-common');
|
|
9
9
|
var errors = require('@backstage/errors');
|
|
10
|
-
var pluginAuthNode = require('@backstage/plugin-auth-node');
|
|
11
10
|
var pluginPermissionCommon = require('@backstage/plugin-permission-common');
|
|
12
11
|
var fetch = require('node-fetch');
|
|
13
12
|
var lodash = require('lodash');
|
|
@@ -150,10 +149,7 @@ async function createRouter(options) {
|
|
|
150
149
|
router.post(
|
|
151
150
|
"/authorize",
|
|
152
151
|
async (req, res) => {
|
|
153
|
-
const
|
|
154
|
-
req.header("authorization")
|
|
155
|
-
);
|
|
156
|
-
const user = token ? await identity.authenticate(token) : void 0;
|
|
152
|
+
const user = await identity.getIdentity({ request: req });
|
|
157
153
|
const parseResult = evaluatePermissionRequestBatchSchema.safeParse(
|
|
158
154
|
req.body
|
|
159
155
|
);
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../src/service/PermissionIntegrationClient.ts","../src/service/router.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fetch from 'node-fetch';\nimport { z } from 'zod';\nimport { PluginEndpointDiscovery } from '@backstage/backend-common';\nimport {\n AuthorizeResult,\n ConditionalPolicyDecision,\n} from '@backstage/plugin-permission-common';\nimport {\n ApplyConditionsRequestEntry,\n ApplyConditionsResponseEntry,\n} from '@backstage/plugin-permission-node';\n\nconst responseSchema = z.object({\n items: z.array(\n z.object({\n id: z.string(),\n result: z\n .literal(AuthorizeResult.ALLOW)\n .or(z.literal(AuthorizeResult.DENY)),\n }),\n ),\n});\n\nexport type ResourcePolicyDecision = ConditionalPolicyDecision & {\n resourceRef: string;\n};\n\nexport class PermissionIntegrationClient {\n private readonly discovery: PluginEndpointDiscovery;\n\n constructor(options: { discovery: PluginEndpointDiscovery }) {\n this.discovery = options.discovery;\n }\n\n async applyConditions(\n pluginId: string,\n decisions: readonly ApplyConditionsRequestEntry[],\n authHeader?: string,\n ): Promise<ApplyConditionsResponseEntry[]> {\n const endpoint = `${await this.discovery.getBaseUrl(\n pluginId,\n )}/.well-known/backstage/permissions/apply-conditions`;\n\n const response = await fetch(endpoint, {\n method: 'POST',\n body: JSON.stringify({\n items: decisions.map(\n ({ id, resourceRef, resourceType, conditions }) => ({\n id,\n resourceRef,\n resourceType,\n conditions,\n }),\n ),\n }),\n headers: {\n ...(authHeader ? { authorization: authHeader } : {}),\n 'content-type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(\n `Unexpected response from plugin upstream when applying conditions. Expected 200 but got ${response.status} - ${response.statusText}`,\n );\n }\n\n const result = responseSchema.parse(await response.json());\n\n return result.items;\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { z } from 'zod';\nimport express, { Request, Response } from 'express';\nimport Router from 'express-promise-router';\nimport { Logger } from 'winston';\nimport {\n errorHandler,\n PluginEndpointDiscovery,\n} from '@backstage/backend-common';\nimport { InputError } from '@backstage/errors';\nimport {\n getBearerTokenFromAuthorizationHeader,\n BackstageIdentityResponse,\n IdentityClient,\n} from '@backstage/plugin-auth-node';\nimport {\n AuthorizeResult,\n EvaluatePermissionResponse,\n EvaluatePermissionRequest,\n IdentifiedPermissionMessage,\n EvaluatePermissionRequestBatch,\n EvaluatePermissionResponseBatch,\n isResourcePermission,\n PermissionAttributes,\n} from '@backstage/plugin-permission-common';\nimport {\n ApplyConditionsRequestEntry,\n ApplyConditionsResponseEntry,\n PermissionPolicy,\n} from '@backstage/plugin-permission-node';\nimport { PermissionIntegrationClient } from './PermissionIntegrationClient';\nimport { memoize } from 'lodash';\nimport DataLoader from 'dataloader';\nimport { Config } from '@backstage/config';\n\nconst attributesSchema: z.ZodSchema<PermissionAttributes> = z.object({\n action: z\n .union([\n z.literal('create'),\n z.literal('read'),\n z.literal('update'),\n z.literal('delete'),\n ])\n .optional(),\n});\n\nconst permissionSchema = z.union([\n z.object({\n type: z.literal('basic'),\n name: z.string(),\n attributes: attributesSchema,\n }),\n z.object({\n type: z.literal('resource'),\n name: z.string(),\n attributes: attributesSchema,\n resourceType: z.string(),\n }),\n]);\n\nconst evaluatePermissionRequestSchema: z.ZodSchema<\n IdentifiedPermissionMessage<EvaluatePermissionRequest>\n> = z.object({\n id: z.string(),\n resourceRef: z.string().optional(),\n permission: permissionSchema,\n});\n\nconst evaluatePermissionRequestBatchSchema: z.ZodSchema<EvaluatePermissionRequestBatch> =\n z.object({\n items: z.array(evaluatePermissionRequestSchema),\n });\n\n/**\n * Options required when constructing a new {@link express#Router} using\n * {@link createRouter}.\n *\n * @public\n */\nexport interface RouterOptions {\n logger: Logger;\n discovery: PluginEndpointDiscovery;\n policy: PermissionPolicy;\n identity: IdentityClient;\n config: Config;\n}\n\nconst handleRequest = async (\n requests: IdentifiedPermissionMessage<EvaluatePermissionRequest>[],\n user: BackstageIdentityResponse | undefined,\n policy: PermissionPolicy,\n permissionIntegrationClient: PermissionIntegrationClient,\n authHeader?: string,\n): Promise<IdentifiedPermissionMessage<EvaluatePermissionResponse>[]> => {\n const applyConditionsLoaderFor = memoize((pluginId: string) => {\n return new DataLoader<\n ApplyConditionsRequestEntry,\n ApplyConditionsResponseEntry\n >(batch =>\n permissionIntegrationClient.applyConditions(pluginId, batch, authHeader),\n );\n });\n\n return Promise.all(\n requests.map(({ id, resourceRef, ...request }) =>\n policy.handle(request, user).then(decision => {\n if (decision.result !== AuthorizeResult.CONDITIONAL) {\n return {\n id,\n ...decision,\n };\n }\n\n if (!isResourcePermission(request.permission)) {\n throw new Error(\n `Conditional decision returned from permission policy for non-resource permission ${request.permission.name}`,\n );\n }\n\n if (decision.resourceType !== request.permission.resourceType) {\n throw new Error(\n `Invalid resource conditions returned from permission policy for permission ${request.permission.name}`,\n );\n }\n\n if (!resourceRef) {\n return {\n id,\n ...decision,\n };\n }\n\n return applyConditionsLoaderFor(decision.pluginId).load({\n id,\n resourceRef,\n ...decision,\n });\n }),\n ),\n );\n};\n\n/**\n * Creates a new {@link express#Router} which provides the backend API\n * for the permission system.\n *\n * @public\n */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const { policy, discovery, identity, config, logger } = options;\n\n if (!config.getOptionalBoolean('permission.enabled')) {\n logger.warn(\n 'Permission backend started with permissions disabled. Enable permissions by setting permission.enabled=true.',\n );\n }\n\n const permissionIntegrationClient = new PermissionIntegrationClient({\n discovery,\n });\n\n const router = Router();\n router.use(express.json());\n\n router.get('/health', (_, response) => {\n response.send({ status: 'ok' });\n });\n\n router.post(\n '/authorize',\n async (\n req: Request<EvaluatePermissionRequestBatch>,\n res: Response<EvaluatePermissionResponseBatch>,\n ) => {\n const token = getBearerTokenFromAuthorizationHeader(\n req.header('authorization'),\n );\n const user = token ? await identity.authenticate(token) : undefined;\n\n const parseResult = evaluatePermissionRequestBatchSchema.safeParse(\n req.body,\n );\n\n if (!parseResult.success) {\n throw new InputError(parseResult.error.toString());\n }\n\n const body = parseResult.data;\n\n res.json({\n items: await handleRequest(\n body.items,\n user,\n policy,\n permissionIntegrationClient,\n req.header('authorization'),\n ),\n });\n },\n );\n\n router.use(errorHandler());\n\n return router;\n}\n"],"names":["z","AuthorizeResult","fetch","memoize","DataLoader","isResourcePermission","Router","express","getBearerTokenFromAuthorizationHeader","InputError","errorHandler"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAKA,MAAM,cAAc,GAAGA,KAAC,CAAC,MAAM,CAAC;AAChC,EAAE,KAAK,EAAEA,KAAC,CAAC,KAAK;AAChB,IAAIA,KAAC,CAAC,MAAM,CAAC;AACb,MAAM,EAAE,EAAEA,KAAC,CAAC,MAAM,EAAE;AACpB,MAAM,MAAM,EAAEA,KAAC,CA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KAAK;AACxB,MAAM,MAAM,KAAK,GAAGC,oDAAqC;AACzD,QAAQ,GAAG,CAAC,MAAM,CAAC,eAAe,CAAC;AACnC,OAAO,CAAC;AACR,MAAM,MAAM,IAAI,GAAG,KAAK,GAAG,MAAM,QAAQ,CAAC,YAAY,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,CAAC;AACvE,MAAM,MAAM,WAAW,GAAG,oCAAoC,CAAC,SAAS;AACxE,QAAQ,GAAG,CAAC,IAAI;AAChB,OAAO,CAAC;AACR,MAAM,IAAI,CAAC,WAAW,CAAC,OAAO,EAAE;AAChC,QAAQ,MAAM,IAAIC,iBAAU,CAAC,WAAW,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC;AAC3D,OAAO;AACP,MAAM,MAAM,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC;AACpC,MAAM,GAAG,CAAC,IAAI,CAAC;AACf,QAAQ,KAAK,EAAE,MAAM,aAAa;AAClC,UAAU,IAAI,CAAC,KAAK;AACpB,UAAU,IAAI;AACd,UAAU,MAAM;AAChB,UAAU,2BAA2B;AACrC,UAAU,GAAG,CAAC,MAAM,CAAC,eAAe,CAAC;AACrC,SAAS;AACT,OAAO,CAAC,CAAC;AACT,KAAK;AACL,GAAG,CAAC;AACJ,EAAE,MAAM,CAAC,GAAG,CAACC,0BAAY,EAAE,CAAC,CAAC;AAC7B,EAAE,OAAO,MAAM,CAAC;AAChB;;;;"}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/service/PermissionIntegrationClient.ts","../src/service/router.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fetch from 'node-fetch';\nimport { z } from 'zod';\nimport { PluginEndpointDiscovery } from '@backstage/backend-common';\nimport {\n AuthorizeResult,\n ConditionalPolicyDecision,\n} from '@backstage/plugin-permission-common';\nimport {\n ApplyConditionsRequestEntry,\n ApplyConditionsResponseEntry,\n} from '@backstage/plugin-permission-node';\n\nconst responseSchema = z.object({\n items: z.array(\n z.object({\n id: z.string(),\n result: z\n .literal(AuthorizeResult.ALLOW)\n .or(z.literal(AuthorizeResult.DENY)),\n }),\n ),\n});\n\nexport type ResourcePolicyDecision = ConditionalPolicyDecision & {\n resourceRef: string;\n};\n\nexport class PermissionIntegrationClient {\n private readonly discovery: PluginEndpointDiscovery;\n\n constructor(options: { discovery: PluginEndpointDiscovery }) {\n this.discovery = options.discovery;\n }\n\n async applyConditions(\n pluginId: string,\n decisions: readonly ApplyConditionsRequestEntry[],\n authHeader?: string,\n ): Promise<ApplyConditionsResponseEntry[]> {\n const endpoint = `${await this.discovery.getBaseUrl(\n pluginId,\n )}/.well-known/backstage/permissions/apply-conditions`;\n\n const response = await fetch(endpoint, {\n method: 'POST',\n body: JSON.stringify({\n items: decisions.map(\n ({ id, resourceRef, resourceType, conditions }) => ({\n id,\n resourceRef,\n resourceType,\n conditions,\n }),\n ),\n }),\n headers: {\n ...(authHeader ? { authorization: authHeader } : {}),\n 'content-type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(\n `Unexpected response from plugin upstream when applying conditions. Expected 200 but got ${response.status} - ${response.statusText}`,\n );\n }\n\n const result = responseSchema.parse(await response.json());\n\n return result.items;\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { z } from 'zod';\nimport express, { Request, Response } from 'express';\nimport Router from 'express-promise-router';\nimport { Logger } from 'winston';\nimport {\n errorHandler,\n PluginEndpointDiscovery,\n} from '@backstage/backend-common';\nimport { InputError } from '@backstage/errors';\nimport {\n BackstageIdentityResponse,\n IdentityApi,\n} from '@backstage/plugin-auth-node';\nimport {\n AuthorizeResult,\n EvaluatePermissionResponse,\n EvaluatePermissionRequest,\n IdentifiedPermissionMessage,\n EvaluatePermissionRequestBatch,\n EvaluatePermissionResponseBatch,\n isResourcePermission,\n PermissionAttributes,\n} from '@backstage/plugin-permission-common';\nimport {\n ApplyConditionsRequestEntry,\n ApplyConditionsResponseEntry,\n PermissionPolicy,\n} from '@backstage/plugin-permission-node';\nimport { PermissionIntegrationClient } from './PermissionIntegrationClient';\nimport { memoize } from 'lodash';\nimport DataLoader from 'dataloader';\nimport { Config } from '@backstage/config';\n\nconst attributesSchema: z.ZodSchema<PermissionAttributes> = z.object({\n action: z\n .union([\n z.literal('create'),\n z.literal('read'),\n z.literal('update'),\n z.literal('delete'),\n ])\n .optional(),\n});\n\nconst permissionSchema = z.union([\n z.object({\n type: z.literal('basic'),\n name: z.string(),\n attributes: attributesSchema,\n }),\n z.object({\n type: z.literal('resource'),\n name: z.string(),\n attributes: attributesSchema,\n resourceType: z.string(),\n }),\n]);\n\nconst evaluatePermissionRequestSchema: z.ZodSchema<\n IdentifiedPermissionMessage<EvaluatePermissionRequest>\n> = z.object({\n id: z.string(),\n resourceRef: z.string().optional(),\n permission: permissionSchema,\n});\n\nconst evaluatePermissionRequestBatchSchema: z.ZodSchema<EvaluatePermissionRequestBatch> =\n z.object({\n items: z.array(evaluatePermissionRequestSchema),\n });\n\n/**\n * Options required when constructing a new {@link express#Router} using\n * {@link createRouter}.\n *\n * @public\n */\nexport interface RouterOptions {\n logger: Logger;\n discovery: PluginEndpointDiscovery;\n policy: PermissionPolicy;\n identity: IdentityApi;\n config: Config;\n}\n\nconst handleRequest = async (\n requests: IdentifiedPermissionMessage<EvaluatePermissionRequest>[],\n user: BackstageIdentityResponse | undefined,\n policy: PermissionPolicy,\n permissionIntegrationClient: PermissionIntegrationClient,\n authHeader?: string,\n): Promise<IdentifiedPermissionMessage<EvaluatePermissionResponse>[]> => {\n const applyConditionsLoaderFor = memoize((pluginId: string) => {\n return new DataLoader<\n ApplyConditionsRequestEntry,\n ApplyConditionsResponseEntry\n >(batch =>\n permissionIntegrationClient.applyConditions(pluginId, batch, authHeader),\n );\n });\n\n return Promise.all(\n requests.map(({ id, resourceRef, ...request }) =>\n policy.handle(request, user).then(decision => {\n if (decision.result !== AuthorizeResult.CONDITIONAL) {\n return {\n id,\n ...decision,\n };\n }\n\n if (!isResourcePermission(request.permission)) {\n throw new Error(\n `Conditional decision returned from permission policy for non-resource permission ${request.permission.name}`,\n );\n }\n\n if (decision.resourceType !== request.permission.resourceType) {\n throw new Error(\n `Invalid resource conditions returned from permission policy for permission ${request.permission.name}`,\n );\n }\n\n if (!resourceRef) {\n return {\n id,\n ...decision,\n };\n }\n\n return applyConditionsLoaderFor(decision.pluginId).load({\n id,\n resourceRef,\n ...decision,\n });\n }),\n ),\n );\n};\n\n/**\n * Creates a new {@link express#Router} which provides the backend API\n * for the permission system.\n *\n * @public\n */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const { policy, discovery, identity, config, logger } = options;\n\n if (!config.getOptionalBoolean('permission.enabled')) {\n logger.warn(\n 'Permission backend started with permissions disabled. Enable permissions by setting permission.enabled=true.',\n );\n }\n\n const permissionIntegrationClient = new PermissionIntegrationClient({\n discovery,\n });\n\n const router = Router();\n router.use(express.json());\n\n router.get('/health', (_, response) => {\n response.send({ status: 'ok' });\n });\n\n router.post(\n '/authorize',\n async (\n req: Request<EvaluatePermissionRequestBatch>,\n res: Response<EvaluatePermissionResponseBatch>,\n ) => {\n const user = await identity.getIdentity({ request: req });\n\n const parseResult = evaluatePermissionRequestBatchSchema.safeParse(\n req.body,\n );\n\n if (!parseResult.success) {\n throw new InputError(parseResult.error.toString());\n }\n\n const body = parseResult.data;\n\n res.json({\n items: await handleRequest(\n body.items,\n user,\n policy,\n permissionIntegrationClient,\n req.header('authorization'),\n ),\n });\n },\n );\n\n router.use(errorHandler());\n\n return router;\n}\n"],"names":["z","AuthorizeResult","fetch","memoize","DataLoader","isResourcePermission","Router","express","InputError","errorHandler"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA4BA,MAAM,cAAA,GAAiBA,MAAE,MAAO,CAAA;AAAA,EAC9B,OAAOA,KAAE,CAAA,KAAA;AAAA,IACPA,MAAE,MAAO,CAAA;AAAA,MACP,EAAA,EAAIA,MAAE,MAAO,EAAA;AAAA,MACb,MAAA,EAAQA,KACL,CAAA,OAAA,CAAQC,sCAAgB,CAAA,KAAK,CAC7B,CAAA,EAAA,CAAGD,KAAE,CAAA,OAAA,CAAQC,sCAAgB,CAAA,IAAI,CAAC,CAAA;AAAA,KACtC,CAAA;AAAA,GACH;AACF,CAAC,CAAA,CAAA;AAMM,MAAM,2BAA4B,CAAA;AAAA,EAGvC,YAAY,OAAiD,EAAA;AAC3D,IAAA,IAAA,CAAK,YAAY,OAAQ,CAAA,SAAA,CAAA;AAAA,GAC3B;AAAA,EAEA,MAAM,eAAA,CACJ,QACA,EAAA,SAAA,EACA,UACyC,EAAA;AACzC,IAAA,MAAM,QAAW,GAAA,CAAA,EAAG,MAAM,IAAA,CAAK,SAAU,CAAA,UAAA;AAAA,MACvC,QAAA;AAAA,KACF,CAAA,mDAAA,CAAA,CAAA;AAEA,IAAM,MAAA,QAAA,GAAW,MAAMC,yBAAA,CAAM,QAAU,EAAA;AAAA,MACrC,MAAQ,EAAA,MAAA;AAAA,MACR,IAAA,EAAM,KAAK,SAAU,CAAA;AAAA,QACnB,OAAO,SAAU,CAAA,GAAA;AAAA,UACf,CAAC,EAAE,EAAA,EAAI,WAAa,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CAAA;AAEzB,EAAA,MAAA,CAAO,GAAI,CAAA,SAAA,EAAW,CAAC,CAAA,EAAG,QAAa,KAAA;AACrC,IAAA,QAAA,CAAS,IAAK,CAAA,EAAE,MAAQ,EAAA,IAAA,EAAM,CAAA,CAAA;AAAA,GAC/B,CAAA,CAAA;AAED,EAAO,MAAA,CAAA,IAAA;AAAA,IACL,YAAA;AAAA,IACA,OACE,KACA,GACG,KAAA;AACH,MAAA,MAAM,OAAO,MAAM,QAAA,CAAS,YAAY,EAAE,OAAA,EAAS,KAAK,CAAA,CAAA;AAExD,MAAA,MAAM,cAAc,oCAAqC,CAAA,SAAA;AAAA,QACvD,GAAI,CAAA,IAAA;AAAA,OACN,CAAA;AAEA,MAAI,IAAA,CAAC,YAAY,OAAS,EAAA;AACxB,QAAA,MAAM,IAAIC,iBAAA,CAAW,WAAY,CAAA,KAAA,CAAM,UAAU,CAAA,CAAA;AAAA,OACnD;AAEA,MAAA,MAAM,OAAO,WAAY,CAAA,IAAA,CAAA;AAEzB,MAAA,GAAA,CAAI,IAAK,CAAA;AAAA,QACP,OAAO,MAAM,aAAA;AAAA,UACX,IAAK,CAAA,KAAA;AAAA,UACL,IAAA;AAAA,UACA,MAAA;AAAA,UACA,2BAAA;AAAA,UACA,GAAA,CAAI,OAAO,eAAe,CAAA;AAAA,SAC5B;AAAA,OACD,CAAA,CAAA;AAAA,KACH;AAAA,GACF,CAAA;AAEA,EAAO,MAAA,CAAA,GAAA,CAAIC,4BAAc,CAAA,CAAA;AAEzB,EAAO,OAAA,MAAA,CAAA;AACT;;;;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import express from 'express';
|
|
2
2
|
import { Logger } from 'winston';
|
|
3
3
|
import { PluginEndpointDiscovery } from '@backstage/backend-common';
|
|
4
|
-
import {
|
|
4
|
+
import { IdentityApi } from '@backstage/plugin-auth-node';
|
|
5
5
|
import { PermissionPolicy } from '@backstage/plugin-permission-node';
|
|
6
6
|
import { Config } from '@backstage/config';
|
|
7
7
|
|
|
@@ -15,7 +15,7 @@ interface RouterOptions {
|
|
|
15
15
|
logger: Logger;
|
|
16
16
|
discovery: PluginEndpointDiscovery;
|
|
17
17
|
policy: PermissionPolicy;
|
|
18
|
-
identity:
|
|
18
|
+
identity: IdentityApi;
|
|
19
19
|
config: Config;
|
|
20
20
|
}
|
|
21
21
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@backstage/plugin-permission-backend",
|
|
3
|
-
"version": "0.5.11-next.
|
|
3
|
+
"version": "0.5.11-next.1",
|
|
4
4
|
"main": "dist/index.cjs.js",
|
|
5
5
|
"types": "dist/index.d.ts",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -22,12 +22,12 @@
|
|
|
22
22
|
"clean": "backstage-cli package clean"
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@backstage/backend-common": "^0.15.1-next.
|
|
25
|
+
"@backstage/backend-common": "^0.15.1-next.2",
|
|
26
26
|
"@backstage/config": "^1.0.1",
|
|
27
27
|
"@backstage/errors": "^1.1.0",
|
|
28
|
-
"@backstage/plugin-auth-node": "^0.2.5-next.
|
|
29
|
-
"@backstage/plugin-permission-common": "^0.6.4-next.
|
|
30
|
-
"@backstage/plugin-permission-node": "^0.6.5-next.
|
|
28
|
+
"@backstage/plugin-auth-node": "^0.2.5-next.2",
|
|
29
|
+
"@backstage/plugin-permission-common": "^0.6.4-next.1",
|
|
30
|
+
"@backstage/plugin-permission-node": "^0.6.5-next.2",
|
|
31
31
|
"@types/express": "*",
|
|
32
32
|
"dataloader": "^2.0.0",
|
|
33
33
|
"express": "^4.17.1",
|
|
@@ -39,14 +39,14 @@
|
|
|
39
39
|
"zod": "^3.11.6"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
|
-
"@backstage/cli": "^0.
|
|
42
|
+
"@backstage/cli": "^0.19.0-next.2",
|
|
43
43
|
"@types/lodash": "^4.14.151",
|
|
44
44
|
"@types/supertest": "^2.0.8",
|
|
45
|
-
"msw": "^0.
|
|
45
|
+
"msw": "^0.47.0",
|
|
46
46
|
"supertest": "^6.1.6"
|
|
47
47
|
},
|
|
48
48
|
"files": [
|
|
49
49
|
"dist"
|
|
50
50
|
],
|
|
51
|
-
"gitHead": "
|
|
51
|
+
"gitHead": "24f889f173370f060725fcf9404081e40769beb4"
|
|
52
52
|
}
|