@backstage/plugin-permission-backend 0.5.6-next.0 → 0.5.7-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/CHANGELOG.md +34 -0
- package/dist/index.cjs.js +29 -16
- package/dist/index.cjs.js.map +1 -1
- package/package.json +7 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,39 @@
|
|
|
1
1
|
# @backstage/plugin-permission-backend
|
|
2
2
|
|
|
3
|
+
## 0.5.7-next.0
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies
|
|
8
|
+
- @backstage/backend-common@0.13.3-next.0
|
|
9
|
+
- @backstage/plugin-auth-node@0.2.1-next.0
|
|
10
|
+
- @backstage/plugin-permission-node@0.6.1-next.0
|
|
11
|
+
|
|
12
|
+
## 0.5.6
|
|
13
|
+
|
|
14
|
+
### Patch Changes
|
|
15
|
+
|
|
16
|
+
- c98d271466: Use updated types from `@backstage/plugin-permission-common`
|
|
17
|
+
- 95284162d6: - Add more specific check for policies which return conditional decisions for non-resource permissions.
|
|
18
|
+
- Refine permission validation in authorize endpoint to differentiate between `BasicPermission` and `ResourcePermission` instances.
|
|
19
|
+
- Updated dependencies
|
|
20
|
+
- @backstage/plugin-permission-common@0.6.0
|
|
21
|
+
- @backstage/plugin-permission-node@0.6.0
|
|
22
|
+
- @backstage/plugin-auth-node@0.2.0
|
|
23
|
+
- @backstage/backend-common@0.13.2
|
|
24
|
+
|
|
25
|
+
## 0.5.6-next.1
|
|
26
|
+
|
|
27
|
+
### Patch Changes
|
|
28
|
+
|
|
29
|
+
- c98d271466: Use updated types from `@backstage/plugin-permission-common`
|
|
30
|
+
- 95284162d6: - Add more specific check for policies which return conditional decisions for non-resource permissions.
|
|
31
|
+
- Refine permission validation in authorize endpoint to differentiate between `BasicPermission` and `ResourcePermission` instances.
|
|
32
|
+
- Updated dependencies
|
|
33
|
+
- @backstage/plugin-permission-common@0.6.0-next.0
|
|
34
|
+
- @backstage/plugin-permission-node@0.6.0-next.1
|
|
35
|
+
- @backstage/backend-common@0.13.2-next.1
|
|
36
|
+
|
|
3
37
|
## 0.5.6-next.0
|
|
4
38
|
|
|
5
39
|
### Patch Changes
|
package/dist/index.cjs.js
CHANGED
|
@@ -55,24 +55,34 @@ class PermissionIntegrationClient {
|
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
-
const
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
58
|
+
const attributesSchema = zod.z.object({
|
|
59
|
+
action: zod.z.union([
|
|
60
|
+
zod.z.literal("create"),
|
|
61
|
+
zod.z.literal("read"),
|
|
62
|
+
zod.z.literal("update"),
|
|
63
|
+
zod.z.literal("delete")
|
|
64
|
+
]).optional()
|
|
65
|
+
});
|
|
66
|
+
const permissionSchema = zod.z.union([
|
|
67
|
+
zod.z.object({
|
|
68
|
+
type: zod.z.literal("basic"),
|
|
69
|
+
name: zod.z.string(),
|
|
70
|
+
attributes: attributesSchema
|
|
71
|
+
}),
|
|
72
|
+
zod.z.object({
|
|
73
|
+
type: zod.z.literal("resource"),
|
|
62
74
|
name: zod.z.string(),
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
action: zod.z.union([
|
|
66
|
-
zod.z.literal("create"),
|
|
67
|
-
zod.z.literal("read"),
|
|
68
|
-
zod.z.literal("update"),
|
|
69
|
-
zod.z.literal("delete")
|
|
70
|
-
]).optional()
|
|
71
|
-
})
|
|
75
|
+
attributes: attributesSchema,
|
|
76
|
+
resourceType: zod.z.string()
|
|
72
77
|
})
|
|
78
|
+
]);
|
|
79
|
+
const evaluatePermissionRequestSchema = zod.z.object({
|
|
80
|
+
id: zod.z.string(),
|
|
81
|
+
resourceRef: zod.z.string().optional(),
|
|
82
|
+
permission: permissionSchema
|
|
73
83
|
});
|
|
74
|
-
const
|
|
75
|
-
items: zod.z.array(
|
|
84
|
+
const evaluatePermissionRequestBatchSchema = zod.z.object({
|
|
85
|
+
items: zod.z.array(evaluatePermissionRequestSchema)
|
|
76
86
|
});
|
|
77
87
|
const handleRequest = async (requests, user, policy, permissionIntegrationClient, authHeader) => {
|
|
78
88
|
const applyConditionsLoaderFor = lodash.memoize((pluginId) => {
|
|
@@ -85,6 +95,9 @@ const handleRequest = async (requests, user, policy, permissionIntegrationClient
|
|
|
85
95
|
...decision
|
|
86
96
|
};
|
|
87
97
|
}
|
|
98
|
+
if (!pluginPermissionCommon.isResourcePermission(request.permission)) {
|
|
99
|
+
throw new Error(`Conditional decision returned from permission policy for non-resource permission ${request.permission.name}`);
|
|
100
|
+
}
|
|
88
101
|
if (decision.resourceType !== request.permission.resourceType) {
|
|
89
102
|
throw new Error(`Invalid resource conditions returned from permission policy for permission ${request.permission.name}`);
|
|
90
103
|
}
|
|
@@ -117,7 +130,7 @@ async function createRouter(options) {
|
|
|
117
130
|
router.post("/authorize", async (req, res) => {
|
|
118
131
|
const token = pluginAuthNode.getBearerTokenFromAuthorizationHeader(req.header("authorization"));
|
|
119
132
|
const user = token ? await identity.authenticate(token) : void 0;
|
|
120
|
-
const parseResult =
|
|
133
|
+
const parseResult = evaluatePermissionRequestBatchSchema.safeParse(req.body);
|
|
121
134
|
if (!parseResult.success) {
|
|
122
135
|
throw new errors.InputError(parseResult.error.toString());
|
|
123
136
|
}
|
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 { AuthorizeResult } from '@backstage/plugin-permission-common';\nimport {\n ApplyConditionsRequestEntry,\n ApplyConditionsResponseEntry,\n ConditionalPolicyDecision,\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 AuthorizeDecision,\n AuthorizeQuery,\n Identified,\n AuthorizeRequest,\n AuthorizeResponse,\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 querySchema: z.ZodSchema<Identified<AuthorizeQuery>> = z.object({\n id: z.string(),\n resourceRef: z.string().optional(),\n permission: z.object({\n name: z.string(),\n resourceType: z.string().optional(),\n attributes: 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 }),\n});\n\nconst requestSchema: z.ZodSchema<AuthorizeRequest> = z.object({\n items: z.array(querySchema),\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: Identified<AuthorizeQuery>[],\n user: BackstageIdentityResponse | undefined,\n policy: PermissionPolicy,\n permissionIntegrationClient: PermissionIntegrationClient,\n authHeader?: string,\n): Promise<Identified<AuthorizeDecision>[]> => {\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 (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<AuthorizeRequest>,\n res: Response<AuthorizeResponse>,\n ) => {\n const token = getBearerTokenFromAuthorizationHeader(\n req.header('authorization'),\n );\n const user = token ? await identity.authenticate(token) : undefined;\n\n const parseResult = requestSchema.safeParse(req.body);\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","Router","express","getBearerTokenFromAuthorizationHeader","InputError","errorHandler"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAM,cAAA,GAAiB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CAAA;AACT;;;;"}
|
|
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,CAACA,KAAC,CAAC,MAAM,CAAC;AAC1B,IAAI,EAAE,EAAEA,KAAC,CAAC,MAAM,EAAE;AAClB,IAAI,MAAM,EAAEA,KAAC,CAAC,OAAO,CAACC,sCAAe,CAAC,KAAK,CAAC,CAAC,EAAE,CAACD,KAAC,CAAC,OAAO,CAACC,sCAAe,CAAC,IAAI,CAAC,CAAC;AAChF,GAAG,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AACI,MAAM,2BAA2B,CAAC;AACzC,EAAE,WAAW,CAAC,OAAO,EAAE;AACvB,IAAI,IAA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AIC,iBAAU,CAAC,WAAW,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC;AACzD,KAAK;AACL,IAAI,MAAM,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC;AAClC,IAAI,GAAG,CAAC,IAAI,CAAC;AACb,MAAM,KAAK,EAAE,MAAM,aAAa,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,2BAA2B,EAAE,GAAG,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC;AACpH,KAAK,CAAC,CAAC;AACP,GAAG,CAAC,CAAC;AACL,EAAE,MAAM,CAAC,GAAG,CAACC,0BAAY,EAAE,CAAC,CAAC;AAC7B,EAAE,OAAO,MAAM,CAAC;AAChB;;;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@backstage/plugin-permission-backend",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.7-next.0",
|
|
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.13.
|
|
25
|
+
"@backstage/backend-common": "^0.13.3-next.0",
|
|
26
26
|
"@backstage/config": "^1.0.0",
|
|
27
27
|
"@backstage/errors": "^1.0.0",
|
|
28
|
-
"@backstage/plugin-auth-node": "^0.2.
|
|
29
|
-
"@backstage/plugin-permission-common": "^0.
|
|
30
|
-
"@backstage/plugin-permission-node": "^0.
|
|
28
|
+
"@backstage/plugin-auth-node": "^0.2.1-next.0",
|
|
29
|
+
"@backstage/plugin-permission-common": "^0.6.0",
|
|
30
|
+
"@backstage/plugin-permission-node": "^0.6.1-next.0",
|
|
31
31
|
"@types/express": "*",
|
|
32
32
|
"dataloader": "^2.0.0",
|
|
33
33
|
"express": "^4.17.1",
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"zod": "^3.11.6"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
|
-
"@backstage/cli": "^0.
|
|
42
|
+
"@backstage/cli": "^0.17.1-next.0",
|
|
43
43
|
"@types/lodash": "^4.14.151",
|
|
44
44
|
"@types/supertest": "^2.0.8",
|
|
45
45
|
"msw": "^0.35.0",
|
|
@@ -48,5 +48,5 @@
|
|
|
48
48
|
"files": [
|
|
49
49
|
"dist"
|
|
50
50
|
],
|
|
51
|
-
"gitHead": "
|
|
51
|
+
"gitHead": "88ee375f5ee44b7a7917297785ddf88691fe3381"
|
|
52
52
|
}
|