c8y-nitro 0.1.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/LICENSE +21 -0
- package/README.md +292 -0
- package/dist/cli/commands/bootstrap.mjs +64 -0
- package/dist/cli/commands/roles.mjs +41 -0
- package/dist/cli/index.d.mts +1 -0
- package/dist/cli/index.mjs +18 -0
- package/dist/cli/utils/c8y-api.mjs +172 -0
- package/dist/cli/utils/config.mjs +57 -0
- package/dist/cli/utils/env-file.mjs +61 -0
- package/dist/index.d.mts +12 -0
- package/dist/index.mjs +51 -0
- package/dist/module/apiClient.mjs +207 -0
- package/dist/module/autoBootstrap.mjs +54 -0
- package/dist/module/c8yzip.mjs +66 -0
- package/dist/module/constants.mjs +6 -0
- package/dist/module/docker.mjs +101 -0
- package/dist/module/manifest.mjs +72 -0
- package/dist/module/probeCheck.mjs +30 -0
- package/dist/module/register.mjs +58 -0
- package/dist/module/runtime/handlers/liveness-readiness.ts +7 -0
- package/dist/module/runtime/middlewares/dev-user.ts +25 -0
- package/dist/module/runtime/plugins/c8y-variables.ts +24 -0
- package/dist/module/runtime.mjs +31 -0
- package/dist/package.mjs +7 -0
- package/dist/types/apiClient.d.mts +16 -0
- package/dist/types/manifest.d.mts +323 -0
- package/dist/types/roles.d.mts +4 -0
- package/dist/types/zip.d.mts +22 -0
- package/dist/types.d.mts +13 -0
- package/dist/types.mjs +1 -0
- package/dist/utils/client.d.mts +50 -0
- package/dist/utils/client.mjs +91 -0
- package/dist/utils/credentials.d.mts +66 -0
- package/dist/utils/credentials.mjs +117 -0
- package/dist/utils/internal/common.mjs +26 -0
- package/dist/utils/middleware.d.mts +89 -0
- package/dist/utils/middleware.mjs +62 -0
- package/dist/utils/resources.d.mts +28 -0
- package/dist/utils/resources.mjs +50 -0
- package/dist/utils.d.mts +5 -0
- package/dist/utils.mjs +6 -0
- package/package.json +87 -0
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { ICredentials } from "@c8y/client";
|
|
2
|
+
|
|
3
|
+
//#region src/utils/credentials.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Fetches credentials for all tenants subscribed to this microservice.\
|
|
6
|
+
* Uses bootstrap credentials from runtime config to query the microservice subscriptions API.\
|
|
7
|
+
* Results are cached for 10 minutes.\
|
|
8
|
+
* @returns Object mapping tenant IDs to their respective credentials
|
|
9
|
+
* @example
|
|
10
|
+
* // Get all subscribed tenant credentials:
|
|
11
|
+
* const credentials = await useSubscribedTenantCredentials()
|
|
12
|
+
* console.log(Object.keys(credentials)) // ['t12345', 't67890']
|
|
13
|
+
*
|
|
14
|
+
* // Access specific tenant:
|
|
15
|
+
* const tenant1Creds = credentials['t12345']
|
|
16
|
+
*
|
|
17
|
+
* // Invalidate cache:
|
|
18
|
+
* await useSubscribedTenantCredentials.invalidate()
|
|
19
|
+
*
|
|
20
|
+
* // Force refresh:
|
|
21
|
+
* const freshCreds = await useSubscribedTenantCredentials.refresh()
|
|
22
|
+
*/
|
|
23
|
+
declare const useSubscribedTenantCredentials: (() => Promise<Record<string, ICredentials>>) & {
|
|
24
|
+
invalidate: () => Promise<void>;
|
|
25
|
+
refresh: () => Promise<Record<string, ICredentials>>;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Fetches credentials for the tenant where this microservice is deployed.\
|
|
29
|
+
* Uses the C8Y_BOOTSTRAP_TENANT environment variable to identify the deployed tenant.\
|
|
30
|
+
* Returns credentials from the subscribed tenant credentials cache (cached for 10 minutes).
|
|
31
|
+
* @returns Credentials for the deployed tenant
|
|
32
|
+
* @throws {HTTPError} If no credentials found for the deployed tenant
|
|
33
|
+
* @example
|
|
34
|
+
* // Get deployed tenant credentials:
|
|
35
|
+
* const creds = await useDeployedTenantCredentials()
|
|
36
|
+
* console.log(creds.tenant, creds.user)
|
|
37
|
+
*
|
|
38
|
+
* // Invalidate cache:
|
|
39
|
+
* await useDeployedTenantCredentials.invalidate()
|
|
40
|
+
*
|
|
41
|
+
* // Force refresh:
|
|
42
|
+
* const freshCreds = await useDeployedTenantCredentials.refresh()
|
|
43
|
+
* @note This function is not cached separately. It uses the cache of `useSubscribedTenantCredentials()`. Invalidating or refreshing one will refresh `useDeployedTenantCredentials()`s cache.
|
|
44
|
+
*/
|
|
45
|
+
declare const useDeployedTenantCredentials: (() => Promise<ICredentials>) & {
|
|
46
|
+
invalidate: () => Promise<void>;
|
|
47
|
+
refresh: () => Promise<ICredentials>;
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Fetches credentials for the tenant of the current user making the request.\
|
|
51
|
+
* Extracts the user's tenant ID from the request headers and returns corresponding credentials.\
|
|
52
|
+
* Results are cached in the request context for subsequent calls within the same request.\
|
|
53
|
+
* Must be called within a request handler context.
|
|
54
|
+
* @returns Credentials for the user's tenant
|
|
55
|
+
* @throws {HTTPError} If no subscribed tenant credentials found for the user's tenant
|
|
56
|
+
* @example
|
|
57
|
+
* // In a request handler:
|
|
58
|
+
* const userCreds = await useUserTenantCredentials()
|
|
59
|
+
* console.log(userCreds.tenant, userCreds.user)
|
|
60
|
+
*
|
|
61
|
+
* // Credentials are automatically cached for the request duration
|
|
62
|
+
* const sameCreds = await useUserTenantCredentials() // Uses cached value
|
|
63
|
+
*/
|
|
64
|
+
declare function useUserTenantCredentials(): Promise<ICredentials>;
|
|
65
|
+
//#endregion
|
|
66
|
+
export { useDeployedTenantCredentials, useSubscribedTenantCredentials, useUserTenantCredentials };
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { useUserClient } from "./client.mjs";
|
|
2
|
+
import process from "node:process";
|
|
3
|
+
import { Client } from "@c8y/client";
|
|
4
|
+
import { useRequest } from "nitro/context";
|
|
5
|
+
import { defineCachedFunction } from "nitro/cache";
|
|
6
|
+
import { HTTPError } from "nitro/h3";
|
|
7
|
+
import { useStorage } from "nitro/storage";
|
|
8
|
+
|
|
9
|
+
//#region src/utils/credentials.ts
|
|
10
|
+
/**
|
|
11
|
+
* Fetches credentials for all tenants subscribed to this microservice.\
|
|
12
|
+
* Uses bootstrap credentials from runtime config to query the microservice subscriptions API.\
|
|
13
|
+
* Results are cached for 10 minutes.\
|
|
14
|
+
* @returns Object mapping tenant IDs to their respective credentials
|
|
15
|
+
* @example
|
|
16
|
+
* // Get all subscribed tenant credentials:
|
|
17
|
+
* const credentials = await useSubscribedTenantCredentials()
|
|
18
|
+
* console.log(Object.keys(credentials)) // ['t12345', 't67890']
|
|
19
|
+
*
|
|
20
|
+
* // Access specific tenant:
|
|
21
|
+
* const tenant1Creds = credentials['t12345']
|
|
22
|
+
*
|
|
23
|
+
* // Invalidate cache:
|
|
24
|
+
* await useSubscribedTenantCredentials.invalidate()
|
|
25
|
+
*
|
|
26
|
+
* // Force refresh:
|
|
27
|
+
* const freshCreds = await useSubscribedTenantCredentials.refresh()
|
|
28
|
+
*/
|
|
29
|
+
const useSubscribedTenantCredentials = Object.assign(defineCachedFunction(async () => {
|
|
30
|
+
return (await Client.getMicroserviceSubscriptions({
|
|
31
|
+
tenant: process.env.C8Y_BOOTSTRAP_TENANT,
|
|
32
|
+
user: process.env.C8Y_BOOTSTRAP_USER,
|
|
33
|
+
password: process.env.C8Y_BOOTSTRAP_PASSWORD
|
|
34
|
+
}, process.env.C8Y_BASEURL)).reduce((acc, cred) => {
|
|
35
|
+
if (cred.tenant) acc[cred.tenant] = cred;
|
|
36
|
+
return acc;
|
|
37
|
+
}, {});
|
|
38
|
+
}, {
|
|
39
|
+
maxAge: 600,
|
|
40
|
+
name: "_c8y_nitro_get_subscribed_tenant_credentials",
|
|
41
|
+
group: "c8y_nitro",
|
|
42
|
+
swr: false
|
|
43
|
+
}), {
|
|
44
|
+
invalidate: async () => {
|
|
45
|
+
await useStorage("cache").removeItem(`c8y_nitro:functions:_c8y_nitro_get_subscribed_tenant_credentials.json`);
|
|
46
|
+
},
|
|
47
|
+
refresh: async () => {
|
|
48
|
+
await useSubscribedTenantCredentials.invalidate();
|
|
49
|
+
return await useSubscribedTenantCredentials();
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
/**
|
|
53
|
+
* Fetches credentials for the tenant where this microservice is deployed.\
|
|
54
|
+
* Uses the C8Y_BOOTSTRAP_TENANT environment variable to identify the deployed tenant.\
|
|
55
|
+
* Returns credentials from the subscribed tenant credentials cache (cached for 10 minutes).
|
|
56
|
+
* @returns Credentials for the deployed tenant
|
|
57
|
+
* @throws {HTTPError} If no credentials found for the deployed tenant
|
|
58
|
+
* @example
|
|
59
|
+
* // Get deployed tenant credentials:
|
|
60
|
+
* const creds = await useDeployedTenantCredentials()
|
|
61
|
+
* console.log(creds.tenant, creds.user)
|
|
62
|
+
*
|
|
63
|
+
* // Invalidate cache:
|
|
64
|
+
* await useDeployedTenantCredentials.invalidate()
|
|
65
|
+
*
|
|
66
|
+
* // Force refresh:
|
|
67
|
+
* const freshCreds = await useDeployedTenantCredentials.refresh()
|
|
68
|
+
* @note This function is not cached separately. It uses the cache of `useSubscribedTenantCredentials()`. Invalidating or refreshing one will refresh `useDeployedTenantCredentials()`s cache.
|
|
69
|
+
*/
|
|
70
|
+
const useDeployedTenantCredentials = Object.assign(async () => {
|
|
71
|
+
const tenant = process.env.C8Y_BOOTSTRAP_TENANT;
|
|
72
|
+
const allCredsPromise = await useSubscribedTenantCredentials();
|
|
73
|
+
if (!allCredsPromise[tenant]) throw new HTTPError({
|
|
74
|
+
message: `No credentials found for tenant deployed tenant '${tenant}'`,
|
|
75
|
+
status: 500,
|
|
76
|
+
statusText: "Internal Server Error"
|
|
77
|
+
});
|
|
78
|
+
return allCredsPromise[tenant];
|
|
79
|
+
}, {
|
|
80
|
+
invalidate: useSubscribedTenantCredentials.invalidate,
|
|
81
|
+
refresh: async () => {
|
|
82
|
+
await useDeployedTenantCredentials.invalidate();
|
|
83
|
+
return await useDeployedTenantCredentials();
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
/**
|
|
87
|
+
* Fetches credentials for the tenant of the current user making the request.\
|
|
88
|
+
* Extracts the user's tenant ID from the request headers and returns corresponding credentials.\
|
|
89
|
+
* Results are cached in the request context for subsequent calls within the same request.\
|
|
90
|
+
* Must be called within a request handler context.
|
|
91
|
+
* @returns Credentials for the user's tenant
|
|
92
|
+
* @throws {HTTPError} If no subscribed tenant credentials found for the user's tenant
|
|
93
|
+
* @example
|
|
94
|
+
* // In a request handler:
|
|
95
|
+
* const userCreds = await useUserTenantCredentials()
|
|
96
|
+
* console.log(userCreds.tenant, userCreds.user)
|
|
97
|
+
*
|
|
98
|
+
* // Credentials are automatically cached for the request duration
|
|
99
|
+
* const sameCreds = await useUserTenantCredentials() // Uses cached value
|
|
100
|
+
*/
|
|
101
|
+
async function useUserTenantCredentials() {
|
|
102
|
+
const request = useRequest();
|
|
103
|
+
if (request.context?.["c8y_user_tenant_credentials"]) return request.context["c8y_user_tenant_credentials"];
|
|
104
|
+
const tenantId = useUserClient().core.tenant;
|
|
105
|
+
const userTenantCreds = (await useSubscribedTenantCredentials())[tenantId];
|
|
106
|
+
if (!userTenantCreds) throw new HTTPError({
|
|
107
|
+
message: `No subscribed tenant credentials found for user tenant '${tenantId}'`,
|
|
108
|
+
status: 500,
|
|
109
|
+
statusText: "Internal Server Error"
|
|
110
|
+
});
|
|
111
|
+
request.context ??= {};
|
|
112
|
+
request.context["c8y_user_tenant_credentials"] = userTenantCreds;
|
|
113
|
+
return userTenantCreds;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
//#endregion
|
|
117
|
+
export { useDeployedTenantCredentials, useSubscribedTenantCredentials, useUserTenantCredentials };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
//#region src/utils/internal/common.ts
|
|
2
|
+
/**
|
|
3
|
+
* Converts undici Request headers to the format expected by MicroserviceClientRequestAuth.\
|
|
4
|
+
* Extracts the following headers from the request:
|
|
5
|
+
* - `authorization`: Used for Basic Auth or Bearer token authentication
|
|
6
|
+
* - `cookie`: Used to extract XSRF-TOKEN and authorization token from cookies
|
|
7
|
+
*
|
|
8
|
+
* The MicroserviceClientRequestAuth class will automatically:
|
|
9
|
+
* - Extract XSRF-TOKEN from cookies for CSRF protection
|
|
10
|
+
* - Extract authorization token from cookies (prioritized over header auth)
|
|
11
|
+
* - Fall back to Authorization header if no cookie-based auth is present
|
|
12
|
+
*
|
|
13
|
+
* @param request - The HTTP request containing headers
|
|
14
|
+
* @returns Headers object compatible with \@c8y/client's MicroserviceClientRequestAuth
|
|
15
|
+
*/
|
|
16
|
+
function convertRequestHeadersToC8yFormat(request) {
|
|
17
|
+
const headers = {};
|
|
18
|
+
const authorization = request.headers.get("authorization");
|
|
19
|
+
if (authorization) headers.authorization = authorization;
|
|
20
|
+
const cookie = request.headers.get("cookie");
|
|
21
|
+
if (cookie) headers.cookie = cookie;
|
|
22
|
+
return headers;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
//#endregion
|
|
26
|
+
export { convertRequestHeadersToC8yFormat };
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { EventHandler } from "nitro/h3";
|
|
2
|
+
import { C8YRoles } from "c8y-nitro/types";
|
|
3
|
+
|
|
4
|
+
//#region src/utils/middleware.d.ts
|
|
5
|
+
type UserRole = keyof C8YRoles | (string & {});
|
|
6
|
+
/**
|
|
7
|
+
* Middleware to check if the current user has the required role.\
|
|
8
|
+
* If the user doesn't have the required role, throws a 403 Forbidden error.\
|
|
9
|
+
* Must be used within a request handler context.\
|
|
10
|
+
* @param role - Single role ID to check for
|
|
11
|
+
* @returns Event handler that validates user roles
|
|
12
|
+
* @example
|
|
13
|
+
* // Single role:
|
|
14
|
+
* export default defineHandler({
|
|
15
|
+
* middleware: [hasUserRequiredRole('ROLE_INVENTORY_ADMIN')],
|
|
16
|
+
* handler: async () => {
|
|
17
|
+
* return { message: 'You have access' }
|
|
18
|
+
* }
|
|
19
|
+
* })
|
|
20
|
+
*
|
|
21
|
+
*/
|
|
22
|
+
declare function hasUserRequiredRole(role: UserRole): EventHandler;
|
|
23
|
+
/**
|
|
24
|
+
* Middleware to check if the current user has at least one of the required roles.\
|
|
25
|
+
* If the user doesn't have any of the required roles, throws a 403 Forbidden error.\
|
|
26
|
+
* Must be used within a request handler context.\
|
|
27
|
+
* @param roles - Array of role IDs to check for
|
|
28
|
+
* @returns Event handler that validates user roles
|
|
29
|
+
* @example
|
|
30
|
+
* // Multiple roles:
|
|
31
|
+
* export default defineHandler({
|
|
32
|
+
* middleware: [hasUserRequiredRole(['ROLE_INVENTORY_ADMIN', 'ROLE_DEVICE_CONTROL'])],
|
|
33
|
+
* handler: async () => {
|
|
34
|
+
* return { message: 'You have access' }
|
|
35
|
+
* }
|
|
36
|
+
* })
|
|
37
|
+
*/
|
|
38
|
+
declare function hasUserRequiredRole(roles: UserRole[]): EventHandler;
|
|
39
|
+
/**
|
|
40
|
+
* Middleware to check if the current user belongs to a specific allowed tenant.\
|
|
41
|
+
* If the user's tenant doesn't match, throws a 403 Forbidden error.\
|
|
42
|
+
* Must be used within a request handler context.\
|
|
43
|
+
* @param tenantId - Single tenant ID to allow
|
|
44
|
+
* @returns Event handler that validates user tenant
|
|
45
|
+
* @example
|
|
46
|
+
* // Single tenant:
|
|
47
|
+
* export default defineHandler({
|
|
48
|
+
* middleware: [isUserFromAllowedTenant('t123456')],
|
|
49
|
+
* handler: async () => {
|
|
50
|
+
* return { message: 'You have access' }
|
|
51
|
+
* }
|
|
52
|
+
* })
|
|
53
|
+
*
|
|
54
|
+
*/
|
|
55
|
+
declare function isUserFromAllowedTenant(tenantId: string): EventHandler;
|
|
56
|
+
/**
|
|
57
|
+
* Middleware to check if the current user belongs to one of the allowed tenants.\
|
|
58
|
+
* If the user's tenant doesn't match any of the allowed tenants, throws a 403 Forbidden error.\
|
|
59
|
+
* Must be used within a request handler context.\
|
|
60
|
+
* @param tenantIds - Array of tenant IDs to allow
|
|
61
|
+
* @returns Event handler that validates user tenant
|
|
62
|
+
* @example
|
|
63
|
+
* // Multiple tenants:
|
|
64
|
+
* export default defineHandler({
|
|
65
|
+
* middleware: [isUserFromAllowedTenant(['t123456', 't789012'])],
|
|
66
|
+
* handler: async () => {
|
|
67
|
+
* return { message: 'You have access' }
|
|
68
|
+
* }
|
|
69
|
+
* })
|
|
70
|
+
*/
|
|
71
|
+
declare function isUserFromAllowedTenant(tenantIds: string[]): EventHandler;
|
|
72
|
+
/**
|
|
73
|
+
* Middleware to check if the current user belongs to the deployed tenant.\
|
|
74
|
+
* The deployed tenant is where this microservice is hosted (C8Y_BOOTSTRAP_TENANT).\
|
|
75
|
+
* If the user's tenant doesn't match the deployed tenant, throws a 403 Forbidden error.\
|
|
76
|
+
* Must be used within a request handler context.\
|
|
77
|
+
* @returns Event handler that validates user is from deployed tenant
|
|
78
|
+
* @example
|
|
79
|
+
* // Only allow users from the deployed tenant:
|
|
80
|
+
* export default defineHandler({
|
|
81
|
+
* middleware: [isUserFromDeployedTenant()],
|
|
82
|
+
* handler: async () => {
|
|
83
|
+
* return { message: 'You have access' }
|
|
84
|
+
* }
|
|
85
|
+
* })
|
|
86
|
+
*/
|
|
87
|
+
declare function isUserFromDeployedTenant(): EventHandler;
|
|
88
|
+
//#endregion
|
|
89
|
+
export { hasUserRequiredRole, isUserFromAllowedTenant, isUserFromDeployedTenant };
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { useUserClient } from "./client.mjs";
|
|
2
|
+
import { useUserRoles } from "./resources.mjs";
|
|
3
|
+
import process from "node:process";
|
|
4
|
+
import { HTTPError, defineHandler } from "nitro/h3";
|
|
5
|
+
|
|
6
|
+
//#region src/utils/middleware.ts
|
|
7
|
+
function hasUserRequiredRole(roleOrRoles) {
|
|
8
|
+
return defineHandler(async () => {
|
|
9
|
+
const requiredRoles = Array.isArray(roleOrRoles) ? roleOrRoles : [roleOrRoles];
|
|
10
|
+
const userRoles = await useUserRoles();
|
|
11
|
+
if (!requiredRoles.some((role) => userRoles.includes(role))) throw new HTTPError({
|
|
12
|
+
status: 403,
|
|
13
|
+
statusText: "Forbidden",
|
|
14
|
+
message: `User does not have required role(s) to access this resource: ${requiredRoles.join(", ")}`
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
function isUserFromAllowedTenant(tenantIdOrIds) {
|
|
19
|
+
return defineHandler(async () => {
|
|
20
|
+
const allowedTenants = Array.isArray(tenantIdOrIds) ? tenantIdOrIds : [tenantIdOrIds];
|
|
21
|
+
const userTenantId = useUserClient().core.tenant;
|
|
22
|
+
if (!allowedTenants.includes(userTenantId)) throw new HTTPError({
|
|
23
|
+
status: 403,
|
|
24
|
+
statusText: "Forbidden",
|
|
25
|
+
message: `User's tenant '${userTenantId}' is not allowed to access this resource. Allowed tenants: ${allowedTenants.join(", ")}`
|
|
26
|
+
});
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Middleware to check if the current user belongs to the deployed tenant.\
|
|
31
|
+
* The deployed tenant is where this microservice is hosted (C8Y_BOOTSTRAP_TENANT).\
|
|
32
|
+
* If the user's tenant doesn't match the deployed tenant, throws a 403 Forbidden error.\
|
|
33
|
+
* Must be used within a request handler context.\
|
|
34
|
+
* @returns Event handler that validates user is from deployed tenant
|
|
35
|
+
* @example
|
|
36
|
+
* // Only allow users from the deployed tenant:
|
|
37
|
+
* export default defineHandler({
|
|
38
|
+
* middleware: [isUserFromDeployedTenant()],
|
|
39
|
+
* handler: async () => {
|
|
40
|
+
* return { message: 'You have access' }
|
|
41
|
+
* }
|
|
42
|
+
* })
|
|
43
|
+
*/
|
|
44
|
+
function isUserFromDeployedTenant() {
|
|
45
|
+
return defineHandler(async () => {
|
|
46
|
+
const userTenantId = useUserClient().core.tenant;
|
|
47
|
+
const deployedTenantId = process.env.C8Y_BOOTSTRAP_TENANT;
|
|
48
|
+
if (!deployedTenantId) throw new HTTPError({
|
|
49
|
+
status: 500,
|
|
50
|
+
statusText: "Internal Server Error",
|
|
51
|
+
message: "C8Y_BOOTSTRAP_TENANT environment variable is not set"
|
|
52
|
+
});
|
|
53
|
+
if (userTenantId !== deployedTenantId) throw new HTTPError({
|
|
54
|
+
status: 403,
|
|
55
|
+
statusText: "Forbidden",
|
|
56
|
+
message: `Only users from tenant '${deployedTenantId}' can access this resource.`
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
//#endregion
|
|
62
|
+
export { hasUserRequiredRole, isUserFromAllowedTenant, isUserFromDeployedTenant };
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { ICurrentUser } from "@c8y/client";
|
|
2
|
+
|
|
3
|
+
//#region src/utils/resources.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Fetches the current user from Cumulocity using credentials extracted from the current request's headers.
|
|
6
|
+
* This is a non-cached version - fetches fresh data on every call.
|
|
7
|
+
* Must be called within a request handler context.
|
|
8
|
+
* @returns The current user object from Cumulocity
|
|
9
|
+
* @example
|
|
10
|
+
* // In a request handler:
|
|
11
|
+
* const user = await useUser()
|
|
12
|
+
* console.log(user.userName, user.email)
|
|
13
|
+
*/
|
|
14
|
+
declare function useUser(): Promise<ICurrentUser>;
|
|
15
|
+
/**
|
|
16
|
+
* Fetches the roles of the current user from Cumulocity.
|
|
17
|
+
* Internally calls `useUser()` and extracts role IDs from the user object.
|
|
18
|
+
* This is a non-cached version - fetches fresh data on every call.
|
|
19
|
+
* Must be called within a request handler context.
|
|
20
|
+
* @returns Array of role ID strings assigned to the current user
|
|
21
|
+
* @example
|
|
22
|
+
* // In a request handler:
|
|
23
|
+
* const roles = await useUserRoles()
|
|
24
|
+
* console.log(roles) // ['ROLE_INVENTORY_READ', 'ROLE_INVENTORY_ADMIN']
|
|
25
|
+
*/
|
|
26
|
+
declare function useUserRoles(): Promise<string[]>;
|
|
27
|
+
//#endregion
|
|
28
|
+
export { useUser, useUserRoles };
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { useUserClient } from "./client.mjs";
|
|
2
|
+
import { useRequest } from "nitro/context";
|
|
3
|
+
import { HTTPError } from "nitro/h3";
|
|
4
|
+
|
|
5
|
+
//#region src/utils/resources.ts
|
|
6
|
+
/**
|
|
7
|
+
* Fetches the current user from Cumulocity using credentials extracted from the current request's headers.
|
|
8
|
+
* This is a non-cached version - fetches fresh data on every call.
|
|
9
|
+
* Must be called within a request handler context.
|
|
10
|
+
* @returns The current user object from Cumulocity
|
|
11
|
+
* @example
|
|
12
|
+
* // In a request handler:
|
|
13
|
+
* const user = await useUser()
|
|
14
|
+
* console.log(user.userName, user.email)
|
|
15
|
+
*/
|
|
16
|
+
async function useUser() {
|
|
17
|
+
const request = useRequest();
|
|
18
|
+
if (request.context?.["c8y_user"]) return request.context["c8y_user"];
|
|
19
|
+
const { res, data: user } = await useUserClient().user.currentWithEffectiveRoles();
|
|
20
|
+
if (!res.ok) throw new HTTPError({
|
|
21
|
+
message: `Failed to fetch current user`,
|
|
22
|
+
status: res.status,
|
|
23
|
+
statusText: res.statusText
|
|
24
|
+
});
|
|
25
|
+
request.context ??= {};
|
|
26
|
+
request.context["c8y_user"] = user;
|
|
27
|
+
return user;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Fetches the roles of the current user from Cumulocity.
|
|
31
|
+
* Internally calls `useUser()` and extracts role IDs from the user object.
|
|
32
|
+
* This is a non-cached version - fetches fresh data on every call.
|
|
33
|
+
* Must be called within a request handler context.
|
|
34
|
+
* @returns Array of role ID strings assigned to the current user
|
|
35
|
+
* @example
|
|
36
|
+
* // In a request handler:
|
|
37
|
+
* const roles = await useUserRoles()
|
|
38
|
+
* console.log(roles) // ['ROLE_INVENTORY_READ', 'ROLE_INVENTORY_ADMIN']
|
|
39
|
+
*/
|
|
40
|
+
async function useUserRoles() {
|
|
41
|
+
const request = useRequest();
|
|
42
|
+
if (request.context?.["c8y_user_roles"]) return request.context["c8y_user_roles"];
|
|
43
|
+
const userRoles = (await useUser()).effectiveRoles?.map((role) => role.name) ?? [];
|
|
44
|
+
request.context ??= {};
|
|
45
|
+
request.context["c8y_user_roles"] = userRoles;
|
|
46
|
+
return userRoles;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
//#endregion
|
|
50
|
+
export { useUser, useUserRoles };
|
package/dist/utils.d.mts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { useDeployedTenantClient, useSubscribedTenantClients, useUserClient, useUserTenantClient } from "./utils/client.mjs";
|
|
2
|
+
import { hasUserRequiredRole, isUserFromAllowedTenant, isUserFromDeployedTenant } from "./utils/middleware.mjs";
|
|
3
|
+
import { useUser, useUserRoles } from "./utils/resources.mjs";
|
|
4
|
+
import { useDeployedTenantCredentials, useSubscribedTenantCredentials, useUserTenantCredentials } from "./utils/credentials.mjs";
|
|
5
|
+
export { hasUserRequiredRole, isUserFromAllowedTenant, isUserFromDeployedTenant, useDeployedTenantClient, useDeployedTenantCredentials, useSubscribedTenantClients, useSubscribedTenantCredentials, useUser, useUserClient, useUserRoles, useUserTenantClient, useUserTenantCredentials };
|
package/dist/utils.mjs
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { useDeployedTenantCredentials, useSubscribedTenantCredentials, useUserTenantCredentials } from "./utils/credentials.mjs";
|
|
2
|
+
import { useDeployedTenantClient, useSubscribedTenantClients, useUserClient, useUserTenantClient } from "./utils/client.mjs";
|
|
3
|
+
import { useUser, useUserRoles } from "./utils/resources.mjs";
|
|
4
|
+
import { hasUserRequiredRole, isUserFromAllowedTenant, isUserFromDeployedTenant } from "./utils/middleware.mjs";
|
|
5
|
+
|
|
6
|
+
export { hasUserRequiredRole, isUserFromAllowedTenant, isUserFromDeployedTenant, useDeployedTenantClient, useDeployedTenantCredentials, useSubscribedTenantClients, useSubscribedTenantCredentials, useUser, useUserClient, useUserRoles, useUserTenantClient, useUserTenantCredentials };
|
package/package.json
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "c8y-nitro",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Lightning fast Cumulocity IoT microservice development powered by Nitro",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"cumulocity",
|
|
8
|
+
"c8y",
|
|
9
|
+
"microservice",
|
|
10
|
+
"nitro",
|
|
11
|
+
"typescript",
|
|
12
|
+
"iot",
|
|
13
|
+
"docker"
|
|
14
|
+
],
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"author": "schplitt",
|
|
17
|
+
"homepage": "https://github.com/schplitt/c8y-nitro#readme",
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "https://github.com/schplitt/c8y-nitro.git"
|
|
21
|
+
},
|
|
22
|
+
"bugs": {
|
|
23
|
+
"url": "https://github.com/schplitt/c8y-nitro/issues"
|
|
24
|
+
},
|
|
25
|
+
"exports": {
|
|
26
|
+
".": {
|
|
27
|
+
"types": "./dist/index.d.mts",
|
|
28
|
+
"import": "./dist/index.mjs"
|
|
29
|
+
},
|
|
30
|
+
"./types": {
|
|
31
|
+
"types": "./dist/types.d.mts",
|
|
32
|
+
"import": "./dist/types.mjs"
|
|
33
|
+
},
|
|
34
|
+
"./utils": {
|
|
35
|
+
"types": "./dist/utils.d.mts",
|
|
36
|
+
"import": "./dist/utils.mjs"
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
"main": "./dist/index.mjs",
|
|
40
|
+
"module": "./dist/index.mjs",
|
|
41
|
+
"types": "./dist/index.d.mts",
|
|
42
|
+
"bin": {
|
|
43
|
+
"c8y-nitro": "./dist/cli/index.mjs"
|
|
44
|
+
},
|
|
45
|
+
"files": [
|
|
46
|
+
"LICENSE",
|
|
47
|
+
"README.md",
|
|
48
|
+
"dist"
|
|
49
|
+
],
|
|
50
|
+
"dependencies": {
|
|
51
|
+
"c12": "^3.3.3",
|
|
52
|
+
"citty": "^0.2.0",
|
|
53
|
+
"consola": "^3.4.2",
|
|
54
|
+
"jszip": "^3.10.1",
|
|
55
|
+
"pathe": "^2.0.3",
|
|
56
|
+
"pkg-types": "^2.3.0",
|
|
57
|
+
"spinnies": "^0.5.1",
|
|
58
|
+
"tinyexec": "^1.0.2"
|
|
59
|
+
},
|
|
60
|
+
"devDependencies": {
|
|
61
|
+
"@schplitt/eslint-config": "^1.2.0",
|
|
62
|
+
"@types/spinnies": "^0.5.3",
|
|
63
|
+
"bumpp": "^10.4.0",
|
|
64
|
+
"eslint": "^9.39.2",
|
|
65
|
+
"memfs": "^4.56.10",
|
|
66
|
+
"tsdown": "^0.20.1",
|
|
67
|
+
"typescript": "^5.9.3",
|
|
68
|
+
"vitest": "^4.0.18"
|
|
69
|
+
},
|
|
70
|
+
"peerDependencies": {
|
|
71
|
+
"@c8y/client": ">=1021.0.0",
|
|
72
|
+
"nitro": "v3.0.1-alpha.2"
|
|
73
|
+
},
|
|
74
|
+
"engines": {
|
|
75
|
+
"node": ">=20.0.0"
|
|
76
|
+
},
|
|
77
|
+
"scripts": {
|
|
78
|
+
"dev": "tsdown --watch",
|
|
79
|
+
"build": "tsdown",
|
|
80
|
+
"lint": "eslint",
|
|
81
|
+
"lint:fix": "eslint --fix",
|
|
82
|
+
"typecheck": "tsc --noEmit",
|
|
83
|
+
"prerelease": "eslint && tsc --noEmit && tsdown",
|
|
84
|
+
"release": "bumpp",
|
|
85
|
+
"test": "vitest"
|
|
86
|
+
}
|
|
87
|
+
}
|