@webiny/api-composition-core 0.0.0-unstable.e1999482d0 → 6.6.0-alpha.14
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/auth/extractAuthToken.d.ts +3 -6
- package/auth/extractAuthToken.js +5 -4
- package/auth/extractAuthToken.js.map +1 -1
- package/auth/extractTenantId.d.ts +2 -1
- package/auth/extractTenantId.js +3 -3
- package/auth/extractTenantId.js.map +1 -1
- package/auth/index.d.ts +0 -2
- package/auth/index.js +0 -1
- package/auth/rejectedTokenResponse.d.ts +3 -6
- package/auth/rejectedTokenResponse.js +2 -6
- package/auth/rejectedTokenResponse.js.map +1 -1
- package/buildParams/registerRootBuildParams.d.ts +15 -0
- package/buildParams/registerRootBuildParams.js +11 -0
- package/buildParams/registerRootBuildParams.js.map +1 -0
- package/http/HttpAssumePermissionsDecorator.d.ts +19 -0
- package/http/HttpAssumePermissionsDecorator.js +22 -0
- package/http/HttpAssumePermissionsDecorator.js.map +1 -0
- package/http/HttpIdentityLoaderDecorator.d.ts +28 -0
- package/{nodeHttp/NodeHttpIdentityLoaderDecorator.js → http/HttpIdentityLoaderDecorator.js} +10 -15
- package/http/HttpIdentityLoaderDecorator.js.map +1 -0
- package/http/HttpInputTenantSource.d.ts +13 -0
- package/http/HttpInputTenantSource.js +11 -0
- package/http/HttpInputTenantSource.js.map +1 -0
- package/http/HttpRequestContextFeature.d.ts +20 -0
- package/http/HttpRequestContextFeature.js +13 -0
- package/http/HttpRequestContextFeature.js.map +1 -0
- package/http/HttpTenantScopeRouter.d.ts +33 -0
- package/http/HttpTenantScopeRouter.js +58 -0
- package/http/HttpTenantScopeRouter.js.map +1 -0
- package/http/index.d.ts +3 -0
- package/http/index.js +2 -0
- package/http/readStreamInScope.d.ts +12 -0
- package/http/readStreamInScope.js +43 -0
- package/http/readStreamInScope.js.map +1 -0
- package/http/registerHttpTransport.d.ts +23 -0
- package/http/registerHttpTransport.js +13 -0
- package/http/registerHttpTransport.js.map +1 -0
- package/http/registerRootAllowedRequestHeaders.d.ts +26 -0
- package/http/registerRootAllowedRequestHeaders.js +39 -0
- package/http/registerRootAllowedRequestHeaders.js.map +1 -0
- package/index.d.ts +5 -5
- package/index.js +4 -3
- package/package.json +26 -26
- package/registerApiRequestStack.d.ts +36 -6
- package/registerApiRequestStack.js +26 -6
- package/registerApiRequestStack.js.map +1 -1
- package/requestRegistration/abstractions.d.ts +13 -3
- package/requestRegistration/abstractions.js.map +1 -1
- package/auth/getHeader.d.ts +0 -5
- package/auth/getHeader.js +0 -8
- package/auth/getHeader.js.map +0 -1
- package/buildParams/readBuildParams.d.ts +0 -10
- package/buildParams/readBuildParams.js +0 -13
- package/buildParams/readBuildParams.js.map +0 -1
- package/nodeHttp/NodeHttpAssumePermissionsDecorator.d.ts +0 -19
- package/nodeHttp/NodeHttpAssumePermissionsDecorator.js +0 -23
- package/nodeHttp/NodeHttpAssumePermissionsDecorator.js.map +0 -1
- package/nodeHttp/NodeHttpIdentityLoaderDecorator.d.ts +0 -34
- package/nodeHttp/NodeHttpIdentityLoaderDecorator.js.map +0 -1
- package/nodeHttp/NodeHttpTenantLoaderDecorator.d.ts +0 -24
- package/nodeHttp/NodeHttpTenantLoaderDecorator.js +0 -28
- package/nodeHttp/NodeHttpTenantLoaderDecorator.js.map +0 -1
- package/nodeHttp/headersFromIncomingMessage.d.ts +0 -6
- package/nodeHttp/headersFromIncomingMessage.js +0 -9
- package/nodeHttp/headersFromIncomingMessage.js.map +0 -1
- package/nodeHttp/index.d.ts +0 -3
- package/nodeHttp/index.js +0 -3
|
@@ -1,13 +1,10 @@
|
|
|
1
|
-
|
|
2
|
-
method: string | undefined;
|
|
3
|
-
path: string | undefined;
|
|
4
|
-
}
|
|
1
|
+
import type { IHttpRequest } from "@webiny/api-kernel-core";
|
|
5
2
|
/**
|
|
6
3
|
* The `wby-id-token` cookie exists only for private file delivery: an `<img src>` cannot send an
|
|
7
4
|
* `Authorization` header. It must not log users in anywhere else, because the browser attaches it
|
|
8
5
|
* to cross-site requests too (`SameSite=None`), which would let any website call the API as the user.
|
|
9
6
|
*/
|
|
10
|
-
export declare function isCookieAuthenticationAllowed(request:
|
|
7
|
+
export declare function isCookieAuthenticationAllowed(request: Pick<IHttpRequest, "method" | "path">): boolean;
|
|
11
8
|
/**
|
|
12
9
|
* Reads the auth token, preferring `x-webiny-authorization` over `Authorization`.
|
|
13
10
|
*
|
|
@@ -18,4 +15,4 @@ export declare function isCookieAuthenticationAllowed(request: AuthTokenRequest)
|
|
|
18
15
|
* plain `Authorization` works for the API's main routes. The `wby-id-token` cookie is the last resort,
|
|
19
16
|
* and only for private file reads (see {@link isCookieAuthenticationAllowed}).
|
|
20
17
|
*/
|
|
21
|
-
export declare function extractAuthToken(
|
|
18
|
+
export declare function extractAuthToken(request: Pick<IHttpRequest, "method" | "path" | "headers">): string | null;
|
package/auth/extractAuthToken.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getHeader } from "
|
|
1
|
+
import { getHeader } from "@webiny/api-kernel-core";
|
|
2
2
|
const WEBINY_AUTHORIZATION_HEADER = "x-webiny-authorization";
|
|
3
3
|
function readCookie(cookieHeader, name) {
|
|
4
4
|
let rawValue = null;
|
|
@@ -14,11 +14,12 @@ function readCookie(cookieHeader, name) {
|
|
|
14
14
|
}
|
|
15
15
|
}
|
|
16
16
|
function isCookieAuthenticationAllowed(request) {
|
|
17
|
-
const method =
|
|
17
|
+
const method = request.method.toUpperCase();
|
|
18
18
|
if ("GET" !== method && "HEAD" !== method) return false;
|
|
19
|
-
return
|
|
19
|
+
return request.path.startsWith("/private/");
|
|
20
20
|
}
|
|
21
|
-
function extractAuthToken(
|
|
21
|
+
function extractAuthToken(request) {
|
|
22
|
+
const headers = request.headers;
|
|
22
23
|
const webinyAuth = getHeader(headers, WEBINY_AUTHORIZATION_HEADER).replace(/^Bearer\s+/i, "");
|
|
23
24
|
if (webinyAuth) return webinyAuth;
|
|
24
25
|
const bearer = getHeader(headers, "authorization").replace(/^Bearer\s+/i, "");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth/extractAuthToken.js","sources":["../../src/auth/extractAuthToken.ts"],"sourcesContent":["import { getHeader } from \"
|
|
1
|
+
{"version":3,"file":"auth/extractAuthToken.js","sources":["../../src/auth/extractAuthToken.ts"],"sourcesContent":["import { getHeader } from \"@webiny/api-kernel-core\";\nimport type { IHttpRequest } from \"@webiny/api-kernel-core\";\n\nconst WEBINY_AUTHORIZATION_HEADER = \"x-webiny-authorization\";\n\n/**\n * Finds one cookie and decodes only its value. Decoding every cookie would let any other cookie on the\n * domain that isn't valid URI encoding (`promo=50%off`) throw and fail the request. If the cookie is\n * sent more than once (same name, different Path or Domain), the last one wins, as it always has.\n */\nfunction readCookie(cookieHeader: string, name: string): string | null {\n let rawValue: string | null = null;\n for (const pair of cookieHeader.split(\";\")) {\n const idx = pair.indexOf(\"=\");\n if (idx > 0 && pair.slice(0, idx).trim() === name) {\n rawValue = pair.slice(idx + 1).trim();\n }\n }\n if (rawValue === null) {\n return null;\n }\n try {\n return decodeURIComponent(rawValue);\n } catch {\n // Not valid URI encoding, so not a token we issued.\n return null;\n }\n}\n\n/**\n * The `wby-id-token` cookie exists only for private file delivery: an `<img src>` cannot send an\n * `Authorization` header. It must not log users in anywhere else, because the browser attaches it\n * to cross-site requests too (`SameSite=None`), which would let any website call the API as the user.\n */\nexport function isCookieAuthenticationAllowed(\n request: Pick<IHttpRequest, \"method\" | \"path\">\n): boolean {\n const method = request.method.toUpperCase();\n if (method !== \"GET\" && method !== \"HEAD\") {\n return false;\n }\n return request.path.startsWith(\"/private/\");\n}\n\n/**\n * Reads the auth token, preferring `x-webiny-authorization` over `Authorization`.\n *\n * The order matters for CloudFront → Lambda Function URL (the streaming routes, file delivery): the\n * Origin Access Control signs those requests with SigV4 in the `Authorization` header, so a viewer's\n * bearer token cannot survive to the origin, and clients send it in `x-webiny-authorization` instead.\n * A Lambda web function origin is different: CloudFront keeps the viewer's `Authorization` there, so\n * plain `Authorization` works for the API's main routes. The `wby-id-token` cookie is the last resort,\n * and only for private file reads (see {@link isCookieAuthenticationAllowed}).\n */\nexport function extractAuthToken(\n request: Pick<IHttpRequest, \"method\" | \"path\" | \"headers\">\n): string | null {\n const headers = request.headers;\n const webinyAuth = getHeader(headers, WEBINY_AUTHORIZATION_HEADER).replace(/^Bearer\\s+/i, \"\");\n if (webinyAuth) {\n return webinyAuth;\n }\n\n const bearer = getHeader(headers, \"authorization\").replace(/^Bearer\\s+/i, \"\");\n if (bearer) {\n return bearer;\n }\n\n if (!isCookieAuthenticationAllowed(request)) {\n return null;\n }\n\n const cookieHeader = getHeader(headers, \"cookie\");\n return readCookie(cookieHeader, \"wby-id-token\");\n}\n"],"names":["WEBINY_AUTHORIZATION_HEADER","readCookie","cookieHeader","name","rawValue","pair","idx","decodeURIComponent","isCookieAuthenticationAllowed","request","method","extractAuthToken","headers","webinyAuth","getHeader","bearer"],"mappings":";AAGA,MAAMA,8BAA8B;AAOpC,SAASC,WAAWC,YAAoB,EAAEC,IAAY;IAClD,IAAIC,WAA0B;IAC9B,KAAK,MAAMC,QAAQH,aAAa,KAAK,CAAC,KAAM;QACxC,MAAMI,MAAMD,KAAK,OAAO,CAAC;QACzB,IAAIC,MAAM,KAAKD,KAAK,KAAK,CAAC,GAAGC,KAAK,IAAI,OAAOH,MACzCC,WAAWC,KAAK,KAAK,CAACC,MAAM,GAAG,IAAI;IAE3C;IACA,IAAIF,AAAa,SAAbA,UACA,OAAO;IAEX,IAAI;QACA,OAAOG,mBAAmBH;IAC9B,EAAE,OAAM;QAEJ,OAAO;IACX;AACJ;AAOO,SAASI,8BACZC,OAA8C;IAE9C,MAAMC,SAASD,QAAQ,MAAM,CAAC,WAAW;IACzC,IAAIC,AAAW,UAAXA,UAAoBA,AAAW,WAAXA,QACpB,OAAO;IAEX,OAAOD,QAAQ,IAAI,CAAC,UAAU,CAAC;AACnC;AAYO,SAASE,iBACZF,OAA0D;IAE1D,MAAMG,UAAUH,QAAQ,OAAO;IAC/B,MAAMI,aAAaC,UAAUF,SAASZ,6BAA6B,OAAO,CAAC,eAAe;IAC1F,IAAIa,YACA,OAAOA;IAGX,MAAME,SAASD,UAAUF,SAAS,iBAAiB,OAAO,CAAC,eAAe;IAC1E,IAAIG,QACA,OAAOA;IAGX,IAAI,CAACP,8BAA8BC,UAC/B,OAAO;IAGX,MAAMP,eAAeY,UAAUF,SAAS;IACxC,OAAOX,WAAWC,cAAc;AACpC"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import type { IHttpRequest } from "@webiny/api-kernel-core";
|
|
1
2
|
/**
|
|
2
3
|
* Reads the tenant id from the `x-tenant` header. A missing or empty header is no tenant, and the
|
|
3
4
|
* tenant loader then uses the root tenant.
|
|
4
5
|
*/
|
|
5
|
-
export declare function extractTenantId(
|
|
6
|
+
export declare function extractTenantId(request: Pick<IHttpRequest, "headers">): string | null;
|
package/auth/extractTenantId.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { getHeader } from "
|
|
2
|
-
function extractTenantId(
|
|
3
|
-
return getHeader(headers, "x-tenant") || null;
|
|
1
|
+
import { getHeader } from "@webiny/api-kernel-core";
|
|
2
|
+
function extractTenantId(request) {
|
|
3
|
+
return getHeader(request.headers, "x-tenant") || null;
|
|
4
4
|
}
|
|
5
5
|
export { extractTenantId };
|
|
6
6
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth/extractTenantId.js","sources":["../../src/auth/extractTenantId.ts"],"sourcesContent":["import { getHeader } from \"
|
|
1
|
+
{"version":3,"file":"auth/extractTenantId.js","sources":["../../src/auth/extractTenantId.ts"],"sourcesContent":["import { getHeader } from \"@webiny/api-kernel-core\";\nimport type { IHttpRequest } from \"@webiny/api-kernel-core\";\n\n/**\n * Reads the tenant id from the `x-tenant` header. A missing or empty header is no tenant, and the\n * tenant loader then uses the root tenant.\n */\nexport function extractTenantId(request: Pick<IHttpRequest, \"headers\">): string | null {\n return getHeader(request.headers, \"x-tenant\") || null;\n}\n"],"names":["extractTenantId","request","getHeader"],"mappings":";AAOO,SAASA,gBAAgBC,OAAsC;IAClE,OAAOC,UAAUD,QAAQ,OAAO,EAAE,eAAe;AACrD"}
|
package/auth/index.d.ts
CHANGED
|
@@ -1,4 +1,2 @@
|
|
|
1
1
|
export { extractAuthToken, isCookieAuthenticationAllowed } from "./extractAuthToken.js";
|
|
2
|
-
export type { AuthTokenRequest } from "./extractAuthToken.js";
|
|
3
2
|
export { extractTenantId } from "./extractTenantId.js";
|
|
4
|
-
export { rejectedTokenResponse } from "./rejectedTokenResponse.js";
|
package/auth/index.js
CHANGED
|
@@ -2,10 +2,7 @@ import type { AuthenticationError } from "@webiny/api-core/features/security/aut
|
|
|
2
2
|
import type { IHttpResponse } from "@webiny/api-kernel-core";
|
|
3
3
|
/**
|
|
4
4
|
* The answer to a request whose token an identity provider rejected, for example in
|
|
5
|
-
* `verifyTokenClaims`.
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* The identity loaders run before the router, so `SecureHeadersDecorator` never sees this response and
|
|
9
|
-
* the CORS headers are added here. Without them the browser reports a CORS failure instead of the 401.
|
|
5
|
+
* `verifyTokenClaims`. The body carries the error's `Authentication/...` code, which the Admin reads
|
|
6
|
+
* to recognise a bad login. `CorsHeadersDecorator` adds the CORS headers on the way out.
|
|
10
7
|
*/
|
|
11
|
-
export declare function rejectedTokenResponse(error: AuthenticationError
|
|
8
|
+
export declare function rejectedTokenResponse(error: AuthenticationError): IHttpResponse;
|
|
@@ -1,13 +1,9 @@
|
|
|
1
|
-
import { codedErrorBody
|
|
2
|
-
|
|
3
|
-
function rejectedTokenResponse(error, headers) {
|
|
4
|
-
const origin = getHeader(headers, "origin");
|
|
5
|
-
const cors = corsHeaders(origin);
|
|
1
|
+
import { codedErrorBody } from "@webiny/api-kernel-core";
|
|
2
|
+
function rejectedTokenResponse(error) {
|
|
6
3
|
const body = codedErrorBody(error);
|
|
7
4
|
return {
|
|
8
5
|
statusCode: 401,
|
|
9
6
|
headers: {
|
|
10
|
-
...cors,
|
|
11
7
|
"content-type": "application/json",
|
|
12
8
|
"www-authenticate": 'Bearer error="invalid_token"'
|
|
13
9
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth/rejectedTokenResponse.js","sources":["../../src/auth/rejectedTokenResponse.ts"],"sourcesContent":["import type { AuthenticationError } from \"@webiny/api-core/features/security/authentication/AuthenticationContext/index.js\";\nimport {
|
|
1
|
+
{"version":3,"file":"auth/rejectedTokenResponse.js","sources":["../../src/auth/rejectedTokenResponse.ts"],"sourcesContent":["import type { AuthenticationError } from \"@webiny/api-core/features/security/authentication/AuthenticationContext/index.js\";\nimport { codedErrorBody } from \"@webiny/api-kernel-core\";\nimport type { IHttpResponse } from \"@webiny/api-kernel-core\";\n\n/**\n * The answer to a request whose token an identity provider rejected, for example in\n * `verifyTokenClaims`. The body carries the error's `Authentication/...` code, which the Admin reads\n * to recognise a bad login. `CorsHeadersDecorator` adds the CORS headers on the way out.\n */\nexport function rejectedTokenResponse(error: AuthenticationError): IHttpResponse {\n const body = codedErrorBody(error);\n\n return {\n statusCode: 401,\n headers: {\n \"content-type\": \"application/json\",\n \"www-authenticate\": 'Bearer error=\"invalid_token\"'\n },\n body\n };\n}\n"],"names":["rejectedTokenResponse","error","body","codedErrorBody"],"mappings":";AASO,SAASA,sBAAsBC,KAA0B;IAC5D,MAAMC,OAAOC,eAAeF;IAE5B,OAAO;QACH,YAAY;QACZ,SAAS;YACL,gBAAgB;YAChB,oBAAoB;QACxB;QACAC;IACJ;AACJ"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Container } from "@webiny/di";
|
|
2
|
+
import { registerBuildParams } from "@webiny/handler";
|
|
3
|
+
import { BuildParams } from "@webiny/api-core/features/buildParams/index.js";
|
|
4
|
+
type Extensions = Parameters<typeof registerBuildParams>[1];
|
|
5
|
+
/**
|
|
6
|
+
* Registers the build params the project was built with, and their reader, in the root container.
|
|
7
|
+
* They come from the deploy, so they are the same for every request and every tenant: request
|
|
8
|
+
* containers and tenant scopes read them from the root. Call it once, in the root, before anything
|
|
9
|
+
* reads them (features gate themselves on `FeatureFlags`, a build param, at register() time).
|
|
10
|
+
*
|
|
11
|
+
* Returns the reader, for a root that needs a setting from them (or wants to check them) before any
|
|
12
|
+
* request runs.
|
|
13
|
+
*/
|
|
14
|
+
export declare function registerRootBuildParams(root: Container, extensions: Extensions): Promise<BuildParams.Interface>;
|
|
15
|
+
export {};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { registerBuildParams } from "@webiny/handler";
|
|
2
|
+
import { BuildParams } from "@webiny/api-core/features/buildParams/index.js";
|
|
3
|
+
import { BuildParamsFeature } from "@webiny/api-core/features/buildParams/feature.js";
|
|
4
|
+
async function registerRootBuildParams(root, extensions) {
|
|
5
|
+
BuildParamsFeature.register(root);
|
|
6
|
+
await registerBuildParams(root, extensions);
|
|
7
|
+
return root.resolve(BuildParams);
|
|
8
|
+
}
|
|
9
|
+
export { registerRootBuildParams };
|
|
10
|
+
|
|
11
|
+
//# sourceMappingURL=registerRootBuildParams.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"buildParams/registerRootBuildParams.js","sources":["../../src/buildParams/registerRootBuildParams.ts"],"sourcesContent":["import type { Container } from \"@webiny/di\";\nimport { registerBuildParams } from \"@webiny/handler\";\nimport { BuildParams } from \"@webiny/api-core/features/buildParams/index.js\";\nimport { BuildParamsFeature } from \"@webiny/api-core/features/buildParams/feature.js\";\n\ntype Extensions = Parameters<typeof registerBuildParams>[1];\n\n/**\n * Registers the build params the project was built with, and their reader, in the root container.\n * They come from the deploy, so they are the same for every request and every tenant: request\n * containers and tenant scopes read them from the root. Call it once, in the root, before anything\n * reads them (features gate themselves on `FeatureFlags`, a build param, at register() time).\n *\n * Returns the reader, for a root that needs a setting from them (or wants to check them) before any\n * request runs.\n */\nexport async function registerRootBuildParams(\n root: Container,\n extensions: Extensions\n): Promise<BuildParams.Interface> {\n BuildParamsFeature.register(root);\n await registerBuildParams(root, extensions);\n return root.resolve(BuildParams);\n}\n"],"names":["registerRootBuildParams","root","extensions","BuildParamsFeature","registerBuildParams","BuildParams"],"mappings":";;;AAgBO,eAAeA,wBAClBC,IAAe,EACfC,UAAsB;IAEtBC,mBAAmB,QAAQ,CAACF;IAC5B,MAAMG,oBAAoBH,MAAMC;IAChC,OAAOD,KAAK,OAAO,CAACI;AACxB"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { HttpRouter } from "@webiny/api-kernel-core";
|
|
2
|
+
import type { IHttpRequest } from "@webiny/api-kernel-core";
|
|
3
|
+
import type { IHttpResponse } from "@webiny/api-kernel-core";
|
|
4
|
+
import { RawAssumePermissions } from "@webiny/api-core/features/requestContext/index.js";
|
|
5
|
+
/**
|
|
6
|
+
* Reads the `x-webiny-assume-permissions` header, the role or team the Admin is previewing, into
|
|
7
|
+
* RawAssumePermissions. Nothing is checked here: AssumedPermissions checks the caller's real
|
|
8
|
+
* permissions before it honours the header.
|
|
9
|
+
*/
|
|
10
|
+
declare class HttpAssumePermissionsDecoratorImpl implements HttpRouter.Interface {
|
|
11
|
+
private rawAssumePermissions;
|
|
12
|
+
private decoratee;
|
|
13
|
+
constructor(rawAssumePermissions: RawAssumePermissions.Interface, decoratee: HttpRouter.Interface);
|
|
14
|
+
route(request: IHttpRequest): Promise<IHttpResponse>;
|
|
15
|
+
}
|
|
16
|
+
export declare const HttpAssumePermissionsDecorator: typeof HttpAssumePermissionsDecoratorImpl & {
|
|
17
|
+
__abstraction: import("@webiny/di").Abstraction<import("@webiny/api-kernel-core").IHttpRouter>;
|
|
18
|
+
};
|
|
19
|
+
export {};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { HttpRouter } from "@webiny/api-kernel-core";
|
|
2
|
+
import { RawAssumePermissions, extractAssumePermissions } from "@webiny/api-core/features/requestContext/index.js";
|
|
3
|
+
class HttpAssumePermissionsDecoratorImpl {
|
|
4
|
+
constructor(rawAssumePermissions, decoratee){
|
|
5
|
+
this.rawAssumePermissions = rawAssumePermissions;
|
|
6
|
+
this.decoratee = decoratee;
|
|
7
|
+
}
|
|
8
|
+
async route(request) {
|
|
9
|
+
const requested = extractAssumePermissions(request.headers);
|
|
10
|
+
this.rawAssumePermissions.set(requested);
|
|
11
|
+
return this.decoratee.route(request);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
const HttpAssumePermissionsDecorator = HttpRouter.createDecorator({
|
|
15
|
+
decorator: HttpAssumePermissionsDecoratorImpl,
|
|
16
|
+
dependencies: [
|
|
17
|
+
RawAssumePermissions
|
|
18
|
+
]
|
|
19
|
+
});
|
|
20
|
+
export { HttpAssumePermissionsDecorator };
|
|
21
|
+
|
|
22
|
+
//# sourceMappingURL=HttpAssumePermissionsDecorator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http/HttpAssumePermissionsDecorator.js","sources":["../../src/http/HttpAssumePermissionsDecorator.ts"],"sourcesContent":["import { HttpRouter } from \"@webiny/api-kernel-core\";\nimport type { IHttpRequest } from \"@webiny/api-kernel-core\";\nimport type { IHttpResponse } from \"@webiny/api-kernel-core\";\nimport { RawAssumePermissions } from \"@webiny/api-core/features/requestContext/index.js\";\nimport { extractAssumePermissions } from \"@webiny/api-core/features/requestContext/index.js\";\n\n/**\n * Reads the `x-webiny-assume-permissions` header, the role or team the Admin is previewing, into\n * RawAssumePermissions. Nothing is checked here: AssumedPermissions checks the caller's real\n * permissions before it honours the header.\n */\nclass HttpAssumePermissionsDecoratorImpl implements HttpRouter.Interface {\n constructor(\n private rawAssumePermissions: RawAssumePermissions.Interface,\n private decoratee: HttpRouter.Interface\n ) {}\n\n async route(request: IHttpRequest): Promise<IHttpResponse> {\n const requested = extractAssumePermissions(request.headers);\n this.rawAssumePermissions.set(requested);\n return this.decoratee.route(request);\n }\n}\n\nexport const HttpAssumePermissionsDecorator = HttpRouter.createDecorator({\n decorator: HttpAssumePermissionsDecoratorImpl,\n dependencies: [RawAssumePermissions]\n});\n"],"names":["HttpAssumePermissionsDecoratorImpl","rawAssumePermissions","decoratee","request","requested","extractAssumePermissions","HttpAssumePermissionsDecorator","HttpRouter","RawAssumePermissions"],"mappings":";;AAWA,MAAMA;IACF,YACYC,oBAAoD,EACpDC,SAA+B,CACzC;aAFUD,oBAAoB,GAApBA;aACAC,SAAS,GAATA;IACT;IAEH,MAAM,MAAMC,OAAqB,EAA0B;QACvD,MAAMC,YAAYC,yBAAyBF,QAAQ,OAAO;QAC1D,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAACC;QAC9B,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAACD;IAChC;AACJ;AAEO,MAAMG,iCAAiCC,WAAW,eAAe,CAAC;IACrE,WAAWP;IACX,cAAc;QAACQ;KAAqB;AACxC"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { HttpRouteDispatcher } from "@webiny/api-kernel-core";
|
|
2
|
+
import type { IHttpRequest } from "@webiny/api-kernel-core";
|
|
3
|
+
import type { IHttpResponse } from "@webiny/api-kernel-core";
|
|
4
|
+
import { RawAuthToken } from "@webiny/api-core/features/requestContext/index.js";
|
|
5
|
+
import { RequestIdentityLoader } from "@webiny/api-core/features/requestContext/index.js";
|
|
6
|
+
/**
|
|
7
|
+
* Runs in the request's tenant scope, as a decorator of `HttpRouteDispatcher`: API-key
|
|
8
|
+
* authentication looks the key up in the tenant, and the identity's permissions are the tenant's.
|
|
9
|
+
*
|
|
10
|
+
* Reads the auth token from the request into RawAuthToken (see {@link extractAuthToken} for the
|
|
11
|
+
* header precedence and when the `wby-id-token` cookie counts), then runs the shared load step,
|
|
12
|
+
* RequestIdentityLoader, which authenticates it and sets IdentityContext. A missing token
|
|
13
|
+
* authenticates as anonymous.
|
|
14
|
+
*
|
|
15
|
+
* A token an identity provider rejects ends the request with a 401. Any other error propagates, and
|
|
16
|
+
* `ErrorResponseDecorator` answers it with a 500.
|
|
17
|
+
*/
|
|
18
|
+
declare class HttpIdentityLoaderDecoratorImpl implements HttpRouteDispatcher.Interface {
|
|
19
|
+
private rawAuthToken;
|
|
20
|
+
private identityLoader;
|
|
21
|
+
private decoratee;
|
|
22
|
+
constructor(rawAuthToken: RawAuthToken.Interface, identityLoader: RequestIdentityLoader.Interface, decoratee: HttpRouteDispatcher.Interface);
|
|
23
|
+
route(request: IHttpRequest): Promise<IHttpResponse>;
|
|
24
|
+
}
|
|
25
|
+
export declare const HttpIdentityLoaderDecorator: typeof HttpIdentityLoaderDecoratorImpl & {
|
|
26
|
+
__abstraction: import("@webiny/di").Abstraction<import("@webiny/api-kernel-core").IHttpRouter>;
|
|
27
|
+
};
|
|
28
|
+
export {};
|
|
@@ -1,38 +1,33 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { HttpRouteDispatcher } from "@webiny/api-kernel-core";
|
|
2
2
|
import { RawAuthToken, RequestIdentityLoader } from "@webiny/api-core/features/requestContext/index.js";
|
|
3
3
|
import { AuthenticationError } from "@webiny/api-core/features/security/authentication/AuthenticationContext/index.js";
|
|
4
4
|
import { extractAuthToken } from "../auth/extractAuthToken.js";
|
|
5
5
|
import { rejectedTokenResponse } from "../auth/rejectedTokenResponse.js";
|
|
6
|
-
|
|
7
|
-
class NodeHttpIdentityLoaderDecoratorImpl {
|
|
6
|
+
class HttpIdentityLoaderDecoratorImpl {
|
|
8
7
|
constructor(rawAuthToken, identityLoader, decoratee){
|
|
9
8
|
this.rawAuthToken = rawAuthToken;
|
|
10
9
|
this.identityLoader = identityLoader;
|
|
11
10
|
this.decoratee = decoratee;
|
|
12
11
|
}
|
|
13
|
-
async
|
|
14
|
-
const
|
|
15
|
-
const authToken = extractAuthToken(headers, {
|
|
16
|
-
method: ctx.input.method,
|
|
17
|
-
path: ctx.input.url
|
|
18
|
-
});
|
|
12
|
+
async route(request) {
|
|
13
|
+
const authToken = extractAuthToken(request);
|
|
19
14
|
this.rawAuthToken.set(authToken);
|
|
20
15
|
try {
|
|
21
16
|
await this.identityLoader.establish();
|
|
22
17
|
} catch (error) {
|
|
23
|
-
if (error instanceof AuthenticationError) return rejectedTokenResponse(error
|
|
18
|
+
if (error instanceof AuthenticationError) return rejectedTokenResponse(error);
|
|
24
19
|
throw error;
|
|
25
20
|
}
|
|
26
|
-
return this.decoratee.
|
|
21
|
+
return this.decoratee.route(request);
|
|
27
22
|
}
|
|
28
23
|
}
|
|
29
|
-
const
|
|
30
|
-
decorator:
|
|
24
|
+
const HttpIdentityLoaderDecorator = HttpRouteDispatcher.createDecorator({
|
|
25
|
+
decorator: HttpIdentityLoaderDecoratorImpl,
|
|
31
26
|
dependencies: [
|
|
32
27
|
RawAuthToken,
|
|
33
28
|
RequestIdentityLoader
|
|
34
29
|
]
|
|
35
30
|
});
|
|
36
|
-
export {
|
|
31
|
+
export { HttpIdentityLoaderDecorator };
|
|
37
32
|
|
|
38
|
-
//# sourceMappingURL=
|
|
33
|
+
//# sourceMappingURL=HttpIdentityLoaderDecorator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http/HttpIdentityLoaderDecorator.js","sources":["../../src/http/HttpIdentityLoaderDecorator.ts"],"sourcesContent":["import { HttpRouteDispatcher } from \"@webiny/api-kernel-core\";\nimport type { IHttpRequest } from \"@webiny/api-kernel-core\";\nimport type { IHttpResponse } from \"@webiny/api-kernel-core\";\nimport { RawAuthToken } from \"@webiny/api-core/features/requestContext/index.js\";\nimport { RequestIdentityLoader } from \"@webiny/api-core/features/requestContext/index.js\";\nimport { AuthenticationError } from \"@webiny/api-core/features/security/authentication/AuthenticationContext/index.js\";\nimport { extractAuthToken } from \"~/auth/extractAuthToken.js\";\nimport { rejectedTokenResponse } from \"~/auth/rejectedTokenResponse.js\";\n\n/**\n * Runs in the request's tenant scope, as a decorator of `HttpRouteDispatcher`: API-key\n * authentication looks the key up in the tenant, and the identity's permissions are the tenant's.\n *\n * Reads the auth token from the request into RawAuthToken (see {@link extractAuthToken} for the\n * header precedence and when the `wby-id-token` cookie counts), then runs the shared load step,\n * RequestIdentityLoader, which authenticates it and sets IdentityContext. A missing token\n * authenticates as anonymous.\n *\n * A token an identity provider rejects ends the request with a 401. Any other error propagates, and\n * `ErrorResponseDecorator` answers it with a 500.\n */\nclass HttpIdentityLoaderDecoratorImpl implements HttpRouteDispatcher.Interface {\n constructor(\n private rawAuthToken: RawAuthToken.Interface,\n private identityLoader: RequestIdentityLoader.Interface,\n private decoratee: HttpRouteDispatcher.Interface\n ) {}\n\n async route(request: IHttpRequest): Promise<IHttpResponse> {\n /*\n * The method and path decide whether the `wby-id-token` cookie may be used (private file\n * reads only). Every transport hands the router the path with any API Gateway stage prefix\n * already stripped, so this is the path the route matched on.\n */\n const authToken = extractAuthToken(request);\n this.rawAuthToken.set(authToken);\n try {\n await this.identityLoader.establish();\n } catch (error) {\n if (error instanceof AuthenticationError) {\n return rejectedTokenResponse(error);\n }\n throw error;\n }\n return this.decoratee.route(request);\n }\n}\n\nexport const HttpIdentityLoaderDecorator = HttpRouteDispatcher.createDecorator({\n decorator: HttpIdentityLoaderDecoratorImpl,\n dependencies: [RawAuthToken, RequestIdentityLoader]\n});\n"],"names":["HttpIdentityLoaderDecoratorImpl","rawAuthToken","identityLoader","decoratee","request","authToken","extractAuthToken","error","AuthenticationError","rejectedTokenResponse","HttpIdentityLoaderDecorator","HttpRouteDispatcher","RawAuthToken","RequestIdentityLoader"],"mappings":";;;;;AAqBA,MAAMA;IACF,YACYC,YAAoC,EACpCC,cAA+C,EAC/CC,SAAwC,CAClD;aAHUF,YAAY,GAAZA;aACAC,cAAc,GAAdA;aACAC,SAAS,GAATA;IACT;IAEH,MAAM,MAAMC,OAAqB,EAA0B;QAMvD,MAAMC,YAAYC,iBAAiBF;QACnC,IAAI,CAAC,YAAY,CAAC,GAAG,CAACC;QACtB,IAAI;YACA,MAAM,IAAI,CAAC,cAAc,CAAC,SAAS;QACvC,EAAE,OAAOE,OAAO;YACZ,IAAIA,iBAAiBC,qBACjB,OAAOC,sBAAsBF;YAEjC,MAAMA;QACV;QACA,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAACH;IAChC;AACJ;AAEO,MAAMM,8BAA8BC,oBAAoB,eAAe,CAAC;IAC3E,WAAWX;IACX,cAAc;QAACY;QAAcC;KAAsB;AACvD"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Abstraction } from "@webiny/di";
|
|
2
|
+
import type { InputChainRunner, InputHandler } from "@webiny/api-kernel-core";
|
|
3
|
+
import { InputTenantSource } from "@webiny/api-core/features/tenancy/TenantScopes/index.js";
|
|
4
|
+
/**
|
|
5
|
+
* An HTTP transport's handler chain runs at request level, in no tenant's scope: the HTTP router
|
|
6
|
+
* answers a CORS preflight there, and enters the request's tenant scope itself, once the tenant is
|
|
7
|
+
* loaded (`HttpTenantScopeRouter`).
|
|
8
|
+
*/
|
|
9
|
+
export declare class HttpInputTenantSource implements InputTenantSource.Interface {
|
|
10
|
+
private readonly inputHandler;
|
|
11
|
+
constructor(inputHandler: Abstraction<InputHandler.Interface>);
|
|
12
|
+
getTenant(request: InputChainRunner.Request): InputTenantSource.Tenant | undefined;
|
|
13
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
class HttpInputTenantSource {
|
|
2
|
+
constructor(inputHandler){
|
|
3
|
+
this.inputHandler = inputHandler;
|
|
4
|
+
}
|
|
5
|
+
getTenant(request) {
|
|
6
|
+
return request.abstraction === this.inputHandler ? "tenant-neutral" : void 0;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
export { HttpInputTenantSource };
|
|
10
|
+
|
|
11
|
+
//# sourceMappingURL=HttpInputTenantSource.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http/HttpInputTenantSource.js","sources":["../../src/http/HttpInputTenantSource.ts"],"sourcesContent":["import type { Abstraction } from \"@webiny/di\";\nimport type { InputChainRunner, InputHandler } from \"@webiny/api-kernel-core\";\nimport { InputTenantSource } from \"@webiny/api-core/features/tenancy/TenantScopes/index.js\";\n\n/**\n * An HTTP transport's handler chain runs at request level, in no tenant's scope: the HTTP router\n * answers a CORS preflight there, and enters the request's tenant scope itself, once the tenant is\n * loaded (`HttpTenantScopeRouter`).\n */\nexport class HttpInputTenantSource implements InputTenantSource.Interface {\n constructor(private readonly inputHandler: Abstraction<InputHandler.Interface>) {}\n\n getTenant(request: InputChainRunner.Request): InputTenantSource.Tenant | undefined {\n return request.abstraction === this.inputHandler ? \"tenant-neutral\" : undefined;\n }\n}\n"],"names":["HttpInputTenantSource","inputHandler","request","undefined"],"mappings":"AASO,MAAMA;IACT,YAA6BC,YAAiD,CAAE;aAAnDA,YAAY,GAAZA;IAAoD;IAEjF,UAAUC,OAAiC,EAAwC;QAC/E,OAAOA,QAAQ,WAAW,KAAK,IAAI,CAAC,YAAY,GAAG,mBAAmBC;IAC1E;AACJ"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sets up the previewed permissions and the identity for every HTTP request, on every transport.
|
|
3
|
+
* The tenant step, and the hand-off into the tenant's scope, is `HttpTenantScopeRouter`, which
|
|
4
|
+
* `registerHttpTransport` registers after the transport feature.
|
|
5
|
+
*
|
|
6
|
+
* Register it BEFORE the transport feature (`ApiGatewayFeature`, `FunctionUrlStreamFeature`,
|
|
7
|
+
* `NodeHttpFeature`), which registers `HttpFeature`. A decorator registered earlier sits further
|
|
8
|
+
* inside, so these run inside `CorsHeadersDecorator` and `ErrorResponseDecorator`: their responses and
|
|
9
|
+
* errors get the CORS headers, and a CORS preflight is answered before any of them runs. Registered
|
|
10
|
+
* after it, a rejected token's 401 reaches the browser without CORS headers and reads as a CORS
|
|
11
|
+
* failure.
|
|
12
|
+
*
|
|
13
|
+
* They run in this order: assume-permissions at request level (a raw header value), then the tenant
|
|
14
|
+
* step and the hand-off, then the identity in the tenant's scope. The tenant comes before the
|
|
15
|
+
* identity because API-key authentication looks the key up in the tenant's partition.
|
|
16
|
+
*/
|
|
17
|
+
export declare const HttpRequestContextFeature: {
|
|
18
|
+
name: string;
|
|
19
|
+
register(container: import("@webiny/di").Container): void;
|
|
20
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { createFeature } from "@webiny/feature/api";
|
|
2
|
+
import { HttpIdentityLoaderDecorator } from "./HttpIdentityLoaderDecorator.js";
|
|
3
|
+
import { HttpAssumePermissionsDecorator } from "./HttpAssumePermissionsDecorator.js";
|
|
4
|
+
const HttpRequestContextFeature = createFeature({
|
|
5
|
+
name: "HttpRequestContext",
|
|
6
|
+
register (container) {
|
|
7
|
+
container.registerDecorator(HttpIdentityLoaderDecorator);
|
|
8
|
+
container.registerDecorator(HttpAssumePermissionsDecorator);
|
|
9
|
+
}
|
|
10
|
+
});
|
|
11
|
+
export { HttpRequestContextFeature };
|
|
12
|
+
|
|
13
|
+
//# sourceMappingURL=HttpRequestContextFeature.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http/HttpRequestContextFeature.js","sources":["../../src/http/HttpRequestContextFeature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/api\";\nimport { HttpIdentityLoaderDecorator } from \"./HttpIdentityLoaderDecorator.js\";\nimport { HttpAssumePermissionsDecorator } from \"./HttpAssumePermissionsDecorator.js\";\n\n/**\n * Sets up the previewed permissions and the identity for every HTTP request, on every transport.\n * The tenant step, and the hand-off into the tenant's scope, is `HttpTenantScopeRouter`, which\n * `registerHttpTransport` registers after the transport feature.\n *\n * Register it BEFORE the transport feature (`ApiGatewayFeature`, `FunctionUrlStreamFeature`,\n * `NodeHttpFeature`), which registers `HttpFeature`. A decorator registered earlier sits further\n * inside, so these run inside `CorsHeadersDecorator` and `ErrorResponseDecorator`: their responses and\n * errors get the CORS headers, and a CORS preflight is answered before any of them runs. Registered\n * after it, a rejected token's 401 reaches the browser without CORS headers and reads as a CORS\n * failure.\n *\n * They run in this order: assume-permissions at request level (a raw header value), then the tenant\n * step and the hand-off, then the identity in the tenant's scope. The tenant comes before the\n * identity because API-key authentication looks the key up in the tenant's partition.\n */\nexport const HttpRequestContextFeature = createFeature({\n name: \"HttpRequestContext\",\n register(container) {\n // Decorates HttpRouteDispatcher, which the hand-off resolves from the tenant's scope.\n container.registerDecorator(HttpIdentityLoaderDecorator);\n // Decorates HttpRouter, at request level.\n container.registerDecorator(HttpAssumePermissionsDecorator);\n }\n});\n"],"names":["HttpRequestContextFeature","createFeature","container","HttpIdentityLoaderDecorator","HttpAssumePermissionsDecorator"],"mappings":";;;AAoBO,MAAMA,4BAA4BC,cAAc;IACnD,MAAM;IACN,UAASC,SAAS;QAEdA,UAAU,iBAAiB,CAACC;QAE5BD,UAAU,iBAAiB,CAACE;IAChC;AACJ"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { HttpRouter } from "@webiny/api-kernel-core";
|
|
2
|
+
import type { IHttpRequest } from "@webiny/api-kernel-core";
|
|
3
|
+
import type { IHttpResponse } from "@webiny/api-kernel-core";
|
|
4
|
+
import { RawTenantId } from "@webiny/api-core/features/requestContext/index.js";
|
|
5
|
+
import { RequestTenantLoader } from "@webiny/api-core/features/requestContext/index.js";
|
|
6
|
+
import { TenantScopes, TenantScopeUsage } from "@webiny/api-core/features/tenancy/TenantScopes/index.js";
|
|
7
|
+
/**
|
|
8
|
+
* The tenant step of an HTTP request, and its hand-off into the tenant's scope. Registered as
|
|
9
|
+
* `HttpRouter`'s implementation, so it runs at request level, inside `HttpRouter`'s decorators
|
|
10
|
+
* (errors, CORS, compression, assume-permissions). A CORS preflight is answered before it runs.
|
|
11
|
+
*
|
|
12
|
+
* It reads the tenant id from the `x-tenant` header (none means the root tenant), loads the tenant
|
|
13
|
+
* from the request's tenant registry, and runs the request's route in that tenant's scope:
|
|
14
|
+
* `HttpRouteDispatcher`, with its decorators (the identity loader), is resolved from the scope. An
|
|
15
|
+
* unknown tenant (`TenantNotFoundError`) or a disabled one fails here, before any scope is built, and
|
|
16
|
+
* `ErrorResponseDecorator` answers it with CORS headers.
|
|
17
|
+
*
|
|
18
|
+
* A streamed body is read in the scope too, and the scope stays in use until it is read. When the
|
|
19
|
+
* request's work in its scope ends, it logs what the request's tenant scopes held.
|
|
20
|
+
*/
|
|
21
|
+
declare class HttpTenantScopeRouterImpl implements HttpRouter.Interface {
|
|
22
|
+
private readonly rawTenantId;
|
|
23
|
+
private readonly tenantLoader;
|
|
24
|
+
private readonly tenantScopes;
|
|
25
|
+
private readonly usage;
|
|
26
|
+
constructor(rawTenantId: RawTenantId.Interface, tenantLoader: RequestTenantLoader.Interface, tenantScopes: TenantScopes.Interface, usage: TenantScopeUsage.Interface | undefined);
|
|
27
|
+
route(request: IHttpRequest): Promise<IHttpResponse>;
|
|
28
|
+
private routeInScope;
|
|
29
|
+
}
|
|
30
|
+
export declare const HttpTenantScopeRouter: typeof HttpTenantScopeRouterImpl & {
|
|
31
|
+
__abstraction: import("@webiny/di").Abstraction<import("@webiny/api-kernel-core").IHttpRouter>;
|
|
32
|
+
};
|
|
33
|
+
export {};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { HttpRouteDispatcher, HttpRouter, HttpStreamBody } from "@webiny/api-kernel-core";
|
|
2
|
+
import { RawTenantId, RequestTenantLoader } from "@webiny/api-core/features/requestContext/index.js";
|
|
3
|
+
import { TenantScopeUsage, TenantScopes } from "@webiny/api-core/features/tenancy/TenantScopes/index.js";
|
|
4
|
+
import { extractTenantId } from "../auth/extractTenantId.js";
|
|
5
|
+
import { readStreamInScope } from "./readStreamInScope.js";
|
|
6
|
+
class HttpTenantScopeRouterImpl {
|
|
7
|
+
constructor(rawTenantId, tenantLoader, tenantScopes, usage){
|
|
8
|
+
this.rawTenantId = rawTenantId;
|
|
9
|
+
this.tenantLoader = tenantLoader;
|
|
10
|
+
this.tenantScopes = tenantScopes;
|
|
11
|
+
this.usage = usage;
|
|
12
|
+
}
|
|
13
|
+
async route(request) {
|
|
14
|
+
this.rawTenantId.set(extractTenantId(request));
|
|
15
|
+
const tenant = await this.tenantLoader.establish();
|
|
16
|
+
let streamed = ()=>{};
|
|
17
|
+
const streamResponse = new Promise((resolve)=>{
|
|
18
|
+
streamed = resolve;
|
|
19
|
+
});
|
|
20
|
+
const inScope = this.routeInScope(tenant, request, streamed).finally(()=>{
|
|
21
|
+
this.usage?.report();
|
|
22
|
+
});
|
|
23
|
+
return Promise.race([
|
|
24
|
+
inScope,
|
|
25
|
+
streamResponse
|
|
26
|
+
]);
|
|
27
|
+
}
|
|
28
|
+
routeInScope(tenant, request, streamed) {
|
|
29
|
+
return this.tenantScopes.withTenant(tenant, async (scope)=>{
|
|
30
|
+
const response = await scope.resolve(HttpRouteDispatcher).route(request);
|
|
31
|
+
if (!HttpStreamBody.is(response.body)) return response;
|
|
32
|
+
return new Promise((resolve)=>{
|
|
33
|
+
const body = readStreamInScope(response.body, ()=>resolve(response));
|
|
34
|
+
streamed({
|
|
35
|
+
...response,
|
|
36
|
+
body
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const HttpTenantScopeRouter = HttpRouter.createImplementation({
|
|
43
|
+
implementation: HttpTenantScopeRouterImpl,
|
|
44
|
+
dependencies: [
|
|
45
|
+
RawTenantId,
|
|
46
|
+
RequestTenantLoader,
|
|
47
|
+
TenantScopes,
|
|
48
|
+
[
|
|
49
|
+
TenantScopeUsage,
|
|
50
|
+
{
|
|
51
|
+
optional: true
|
|
52
|
+
}
|
|
53
|
+
]
|
|
54
|
+
]
|
|
55
|
+
});
|
|
56
|
+
export { HttpTenantScopeRouter };
|
|
57
|
+
|
|
58
|
+
//# sourceMappingURL=HttpTenantScopeRouter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http/HttpTenantScopeRouter.js","sources":["../../src/http/HttpTenantScopeRouter.ts"],"sourcesContent":["import { HttpRouteDispatcher, HttpRouter, HttpStreamBody } from \"@webiny/api-kernel-core\";\nimport type { IHttpRequest } from \"@webiny/api-kernel-core\";\nimport type { IHttpResponse } from \"@webiny/api-kernel-core\";\nimport { RawTenantId } from \"@webiny/api-core/features/requestContext/index.js\";\nimport { RequestTenantLoader } from \"@webiny/api-core/features/requestContext/index.js\";\nimport {\n TenantScopes,\n TenantScopeUsage\n} from \"@webiny/api-core/features/tenancy/TenantScopes/index.js\";\nimport type { Tenant } from \"@webiny/api-core/types/tenancy.js\";\nimport { extractTenantId } from \"~/auth/extractTenantId.js\";\nimport { readStreamInScope } from \"./readStreamInScope.js\";\n\n/**\n * The tenant step of an HTTP request, and its hand-off into the tenant's scope. Registered as\n * `HttpRouter`'s implementation, so it runs at request level, inside `HttpRouter`'s decorators\n * (errors, CORS, compression, assume-permissions). A CORS preflight is answered before it runs.\n *\n * It reads the tenant id from the `x-tenant` header (none means the root tenant), loads the tenant\n * from the request's tenant registry, and runs the request's route in that tenant's scope:\n * `HttpRouteDispatcher`, with its decorators (the identity loader), is resolved from the scope. An\n * unknown tenant (`TenantNotFoundError`) or a disabled one fails here, before any scope is built, and\n * `ErrorResponseDecorator` answers it with CORS headers.\n *\n * A streamed body is read in the scope too, and the scope stays in use until it is read. When the\n * request's work in its scope ends, it logs what the request's tenant scopes held.\n */\nclass HttpTenantScopeRouterImpl implements HttpRouter.Interface {\n constructor(\n private readonly rawTenantId: RawTenantId.Interface,\n private readonly tenantLoader: RequestTenantLoader.Interface,\n private readonly tenantScopes: TenantScopes.Interface,\n private readonly usage: TenantScopeUsage.Interface | undefined\n ) {}\n\n async route(request: IHttpRequest): Promise<IHttpResponse> {\n this.rawTenantId.set(extractTenantId(request));\n const tenant = await this.tenantLoader.establish();\n\n let streamed: (response: IHttpResponse) => void = () => {};\n const streamResponse = new Promise<IHttpResponse>(resolve => {\n streamed = resolve;\n });\n\n const inScope = this.routeInScope(tenant, request, streamed).finally(() => {\n this.usage?.report();\n });\n\n // A buffered response once the scope's callback ends, a streamed one as soon as it starts.\n return Promise.race([inScope, streamResponse]);\n }\n\n private routeInScope(\n tenant: Tenant,\n request: IHttpRequest,\n streamed: (response: IHttpResponse) => void\n ): Promise<IHttpResponse> {\n return this.tenantScopes.withTenant(tenant, async scope => {\n const response = await scope.resolve(HttpRouteDispatcher).route(request);\n if (!HttpStreamBody.is(response.body)) {\n return response;\n }\n\n // The callback, and with it the scope's use, lasts until the transport has read the body.\n return new Promise<IHttpResponse>(resolve => {\n const body = readStreamInScope(response.body, () => resolve(response));\n streamed({ ...response, body });\n });\n });\n }\n}\n\nexport const HttpTenantScopeRouter = HttpRouter.createImplementation({\n implementation: HttpTenantScopeRouterImpl,\n dependencies: [\n RawTenantId,\n RequestTenantLoader,\n TenantScopes,\n [TenantScopeUsage, { optional: true }]\n ]\n});\n"],"names":["HttpTenantScopeRouterImpl","rawTenantId","tenantLoader","tenantScopes","usage","request","extractTenantId","tenant","streamed","streamResponse","Promise","resolve","inScope","scope","response","HttpRouteDispatcher","HttpStreamBody","body","readStreamInScope","HttpTenantScopeRouter","HttpRouter","RawTenantId","RequestTenantLoader","TenantScopes","TenantScopeUsage"],"mappings":";;;;;AA2BA,MAAMA;IACF,YACqBC,WAAkC,EAClCC,YAA2C,EAC3CC,YAAoC,EACpCC,KAA6C,CAChE;aAJmBH,WAAW,GAAXA;aACAC,YAAY,GAAZA;aACAC,YAAY,GAAZA;aACAC,KAAK,GAALA;IAClB;IAEH,MAAM,MAAMC,OAAqB,EAA0B;QACvD,IAAI,CAAC,WAAW,CAAC,GAAG,CAACC,gBAAgBD;QACrC,MAAME,SAAS,MAAM,IAAI,CAAC,YAAY,CAAC,SAAS;QAEhD,IAAIC,WAA8C,KAAO;QACzD,MAAMC,iBAAiB,IAAIC,QAAuBC,CAAAA;YAC9CH,WAAWG;QACf;QAEA,MAAMC,UAAU,IAAI,CAAC,YAAY,CAACL,QAAQF,SAASG,UAAU,OAAO,CAAC;YACjE,IAAI,CAAC,KAAK,EAAE;QAChB;QAGA,OAAOE,QAAQ,IAAI,CAAC;YAACE;YAASH;SAAe;IACjD;IAEQ,aACJF,MAAc,EACdF,OAAqB,EACrBG,QAA2C,EACrB;QACtB,OAAO,IAAI,CAAC,YAAY,CAAC,UAAU,CAACD,QAAQ,OAAMM;YAC9C,MAAMC,WAAW,MAAMD,MAAM,OAAO,CAACE,qBAAqB,KAAK,CAACV;YAChE,IAAI,CAACW,eAAe,EAAE,CAACF,SAAS,IAAI,GAChC,OAAOA;YAIX,OAAO,IAAIJ,QAAuBC,CAAAA;gBAC9B,MAAMM,OAAOC,kBAAkBJ,SAAS,IAAI,EAAE,IAAMH,QAAQG;gBAC5DN,SAAS;oBAAE,GAAGM,QAAQ;oBAAEG;gBAAK;YACjC;QACJ;IACJ;AACJ;AAEO,MAAME,wBAAwBC,WAAW,oBAAoB,CAAC;IACjE,gBAAgBpB;IAChB,cAAc;QACVqB;QACAC;QACAC;QACA;YAACC;YAAkB;gBAAE,UAAU;YAAK;SAAE;KACzC;AACL"}
|
package/http/index.d.ts
ADDED
package/http/index.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { HttpStreamBody } from "@webiny/api-kernel-core";
|
|
2
|
+
/**
|
|
3
|
+
* A streamed body that is read in the tenant scope it was created in.
|
|
4
|
+
*
|
|
5
|
+
* The transport reads a stream after the router has returned, so outside the scope's callback. Its
|
|
6
|
+
* chunks are produced by the route's services (an AI provider, a use case), which belong to the
|
|
7
|
+
* scope and throw `StaleKernelExecutionError` outside it. Call this inside the scope's callback: each
|
|
8
|
+
* read then runs in the async context captured here, the scope's.
|
|
9
|
+
*
|
|
10
|
+
* `onEnd` is called once, when the stream is fully read, fails, or the reader stops early.
|
|
11
|
+
*/
|
|
12
|
+
export declare function readStreamInScope(body: HttpStreamBody, onEnd: () => void): HttpStreamBody;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { HttpStreamBody } from "@webiny/api-kernel-core";
|
|
3
|
+
function readStreamInScope(body, onEnd) {
|
|
4
|
+
const runInScope = AsyncLocalStorage.snapshot();
|
|
5
|
+
let ended = false;
|
|
6
|
+
const end = ()=>{
|
|
7
|
+
if (!ended) {
|
|
8
|
+
ended = true;
|
|
9
|
+
onEnd();
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
return new HttpStreamBody({
|
|
13
|
+
[Symbol.asyncIterator] () {
|
|
14
|
+
const iterator = runInScope(()=>body.source[Symbol.asyncIterator]());
|
|
15
|
+
return {
|
|
16
|
+
async next () {
|
|
17
|
+
try {
|
|
18
|
+
const result = await runInScope(()=>iterator.next());
|
|
19
|
+
if (result.done) end();
|
|
20
|
+
return result;
|
|
21
|
+
} catch (error) {
|
|
22
|
+
end();
|
|
23
|
+
throw error;
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
async return (value) {
|
|
27
|
+
try {
|
|
28
|
+
if (iterator.return) return await runInScope(()=>iterator.return(value));
|
|
29
|
+
return {
|
|
30
|
+
done: true,
|
|
31
|
+
value
|
|
32
|
+
};
|
|
33
|
+
} finally{
|
|
34
|
+
end();
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
export { readStreamInScope };
|
|
42
|
+
|
|
43
|
+
//# sourceMappingURL=readStreamInScope.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http/readStreamInScope.js","sources":["../../src/http/readStreamInScope.ts"],"sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { HttpStreamBody } from \"@webiny/api-kernel-core\";\nimport type { HttpStreamChunk } from \"@webiny/api-kernel-core\";\n\n/**\n * A streamed body that is read in the tenant scope it was created in.\n *\n * The transport reads a stream after the router has returned, so outside the scope's callback. Its\n * chunks are produced by the route's services (an AI provider, a use case), which belong to the\n * scope and throw `StaleKernelExecutionError` outside it. Call this inside the scope's callback: each\n * read then runs in the async context captured here, the scope's.\n *\n * `onEnd` is called once, when the stream is fully read, fails, or the reader stops early.\n */\nexport function readStreamInScope(body: HttpStreamBody, onEnd: () => void): HttpStreamBody {\n const runInScope = AsyncLocalStorage.snapshot();\n\n let ended = false;\n const end = () => {\n if (!ended) {\n ended = true;\n onEnd();\n }\n };\n\n return new HttpStreamBody({\n [Symbol.asyncIterator](): AsyncIterator<HttpStreamChunk> {\n const iterator = runInScope(() => body.source[Symbol.asyncIterator]());\n return {\n async next() {\n try {\n const result = await runInScope(() => iterator.next());\n if (result.done) {\n end();\n }\n return result;\n } catch (error) {\n end();\n throw error;\n }\n },\n async return(value?: any) {\n try {\n if (iterator.return) {\n return await runInScope(() => iterator.return!(value));\n }\n return { done: true, value };\n } finally {\n end();\n }\n }\n };\n }\n });\n}\n"],"names":["readStreamInScope","body","onEnd","runInScope","AsyncLocalStorage","ended","end","HttpStreamBody","Symbol","iterator","result","error","value"],"mappings":";;AAcO,SAASA,kBAAkBC,IAAoB,EAAEC,KAAiB;IACrE,MAAMC,aAAaC,kBAAkB,QAAQ;IAE7C,IAAIC,QAAQ;IACZ,MAAMC,MAAM;QACR,IAAI,CAACD,OAAO;YACRA,QAAQ;YACRH;QACJ;IACJ;IAEA,OAAO,IAAIK,eAAe;QACtB,CAACC,OAAO,aAAa,CAAC;YAClB,MAAMC,WAAWN,WAAW,IAAMF,KAAK,MAAM,CAACO,OAAO,aAAa,CAAC;YACnE,OAAO;gBACH,MAAM;oBACF,IAAI;wBACA,MAAME,SAAS,MAAMP,WAAW,IAAMM,SAAS,IAAI;wBACnD,IAAIC,OAAO,IAAI,EACXJ;wBAEJ,OAAOI;oBACX,EAAE,OAAOC,OAAO;wBACZL;wBACA,MAAMK;oBACV;gBACJ;gBACA,MAAM,QAAOC,KAAW;oBACpB,IAAI;wBACA,IAAIH,SAAS,MAAM,EACf,OAAO,MAAMN,WAAW,IAAMM,SAAS,MAAM,CAAEG;wBAEnD,OAAO;4BAAE,MAAM;4BAAMA;wBAAM;oBAC/B,SAAU;wBACNN;oBACJ;gBACJ;YACJ;QACJ;IACJ;AACJ"}
|