@infoxchange/make-it-so 2.11.0-internal-testing-vdt-199-add-auth-token-verify-function.4 → 2.11.0-internal-testing-vdt-199-add-auth-token-verify-function-2.2

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.
Files changed (36) hide show
  1. package/README.md +15 -29
  2. package/dist/cdk-constructs/IxNextjsSite.d.ts.map +1 -1
  3. package/dist/cdk-constructs/IxNextjsSite.js +2 -1
  4. package/dist/cdk-constructs/IxStaticSite.d.ts.map +1 -1
  5. package/dist/cdk-constructs/IxStaticSite.js +2 -1
  6. package/dist/cdk-constructs/SiteOidcAuth/auth-check-handler-body.d.ts +2 -0
  7. package/dist/cdk-constructs/SiteOidcAuth/auth-check-handler-body.d.ts.map +1 -0
  8. package/dist/cdk-constructs/{CloudFrontOidcAuth/auth-check.js → SiteOidcAuth/auth-check-handler-body.js} +39 -57
  9. package/dist/cdk-constructs/SiteOidcAuth/auth-route.d.ts.map +1 -0
  10. package/dist/cdk-constructs/SiteOidcAuth/index.d.ts +197 -0
  11. package/dist/cdk-constructs/SiteOidcAuth/index.d.ts.map +1 -0
  12. package/dist/cdk-constructs/SiteOidcAuth/index.js +184 -0
  13. package/dist/cdk-constructs/index.d.ts +1 -1
  14. package/dist/cdk-constructs/index.d.ts.map +1 -1
  15. package/dist/cdk-constructs/index.js +1 -1
  16. package/dist/lib/site/support.d.ts +15 -5
  17. package/dist/lib/site/support.d.ts.map +1 -1
  18. package/dist/lib/site/support.js +19 -0
  19. package/package.json +1 -1
  20. package/src/cdk-constructs/IxNextjsSite.ts +2 -0
  21. package/src/cdk-constructs/IxStaticSite.ts +2 -0
  22. package/src/cdk-constructs/{CloudFrontOidcAuth/auth-check.ts → SiteOidcAuth/auth-check-handler-body.ts} +44 -63
  23. package/src/cdk-constructs/SiteOidcAuth/index.ts +288 -0
  24. package/src/cdk-constructs/index.ts +1 -1
  25. package/src/lib/site/support.ts +80 -29
  26. package/dist/cdk-constructs/CloudFrontOidcAuth/auth-check.d.ts +0 -2
  27. package/dist/cdk-constructs/CloudFrontOidcAuth/auth-check.d.ts.map +0 -1
  28. package/dist/cdk-constructs/CloudFrontOidcAuth/auth-route.d.ts.map +0 -1
  29. package/dist/cdk-constructs/CloudFrontOidcAuth/index.d.ts +0 -27
  30. package/dist/cdk-constructs/CloudFrontOidcAuth/index.d.ts.map +0 -1
  31. package/dist/cdk-constructs/CloudFrontOidcAuth/index.js +0 -198
  32. package/src/cdk-constructs/CloudFrontOidcAuth/cloudfront.d.ts +0 -245
  33. package/src/cdk-constructs/CloudFrontOidcAuth/index.ts +0 -294
  34. /package/dist/cdk-constructs/{CloudFrontOidcAuth → SiteOidcAuth}/auth-route.d.ts +0 -0
  35. /package/dist/cdk-constructs/{CloudFrontOidcAuth → SiteOidcAuth}/auth-route.js +0 -0
  36. /package/src/cdk-constructs/{CloudFrontOidcAuth → SiteOidcAuth}/auth-route.ts +0 -0
@@ -15,6 +15,21 @@ import { CloudFrontTarget } from "aws-cdk-lib/aws-route53-targets";
15
15
  import { convertToBase62Hash } from "../utils/hash.js";
16
16
  import { type DistributionDomainProps } from "sst/constructs/Distribution.js";
17
17
  import type { Plan as SSTPlan } from "sst/constructs/SsrSite.js";
18
+ import {
19
+ SiteOidcAuth,
20
+ type AddToSiteProps as SiteOidcAuthAddToSiteProps,
21
+ } from "../../cdk-constructs/SiteOidcAuth/index.js";
22
+
23
+ type SharedExtendedSiteProps = {
24
+ customDomain?: string | ExtendedCustomDomains;
25
+ auth?: {
26
+ oidc: {
27
+ issuerUrl: string;
28
+ clientId: string;
29
+ scope: string;
30
+ };
31
+ } & SiteOidcAuthAddToSiteProps;
32
+ };
18
33
 
19
34
  export type ExtendedCustomDomains = DistributionDomainProps & {
20
35
  isIxManagedDomain?: boolean;
@@ -23,36 +38,35 @@ export type ExtendedCustomDomains = DistributionDomainProps & {
23
38
  export type ExtendedNextjsSiteProps = Omit<
24
39
  NextjsSiteProps,
25
40
  "customDomain" | "environment"
26
- > & {
27
- customDomain?: string | ExtendedCustomDomains;
28
- /**
29
- * An object with the key being the environment variable name. The value can either be the environment variable value
30
- * as a string or as an object with `buildtime` and/or `runtime` properties where the values of `buildtime` and
31
- * `runtime` is the environment variable value that will be used during that step.
32
- *
33
- * @example
34
- * ```js
35
- * environment: {
36
- * USER_POOL_CLIENT: auth.cognitoUserPoolClient.userPoolClientId,
37
- * NODE_OPTIONS: {
38
- * buildtime: "--max-old-space-size=4096",
39
- * },
40
- * API_URL: {
41
- * buildtime: "https://external.domain",
42
- * runtime: "https://internal.domain",
43
- * },
44
- * },
45
- * ```
46
- */
47
- environment?: Record<
48
- string,
49
- string | { buildtime?: string; runtime?: string }
50
- >;
51
- };
41
+ > &
42
+ SharedExtendedSiteProps & {
43
+ /**
44
+ * An object with the key being the environment variable name. The value can either be the environment variable value
45
+ * as a string or as an object with `buildtime` and/or `runtime` properties where the values of `buildtime` and
46
+ * `runtime` is the environment variable value that will be used during that step.
47
+ *
48
+ * @example
49
+ * ```js
50
+ * environment: {
51
+ * USER_POOL_CLIENT: auth.cognitoUserPoolClient.userPoolClientId,
52
+ * NODE_OPTIONS: {
53
+ * buildtime: "--max-old-space-size=4096",
54
+ * },
55
+ * API_URL: {
56
+ * buildtime: "https://external.domain",
57
+ * runtime: "https://internal.domain",
58
+ * },
59
+ * },
60
+ * ```
61
+ */
62
+ environment?: Record<
63
+ string,
64
+ string | { buildtime?: string; runtime?: string }
65
+ >;
66
+ };
52
67
 
53
- export type ExtendedStaticSiteProps = Omit<StaticSiteProps, "customDomain"> & {
54
- customDomain?: string | ExtendedCustomDomains;
55
- };
68
+ export type ExtendedStaticSiteProps = Omit<StaticSiteProps, "customDomain"> &
69
+ SharedExtendedSiteProps;
56
70
 
57
71
  export function setupCustomDomain<
58
72
  Props extends ExtendedStaticSiteProps | ExtendedNextjsSiteProps,
@@ -386,3 +400,40 @@ export function getAlternativeDomains<
386
400
  }
387
401
  return [];
388
402
  }
403
+
404
+ export function processAuthProps<
405
+ SiteType extends "StaticSite" | "SsrSite",
406
+ Props extends SiteType extends "StaticSite"
407
+ ? ExtendedStaticSiteProps
408
+ : ExtendedNextjsSiteProps,
409
+ >(
410
+ scope: Construct,
411
+ id: string,
412
+ siteType: SiteType,
413
+ props: Readonly<Props>,
414
+ ): Props {
415
+ if (!props.auth) return props;
416
+ const { oidc, ...otherAuthProps } = props.auth;
417
+ const auth = new SiteOidcAuth(scope, `${id}-SiteOidcAuth`, {
418
+ oidcIssuerUrl: oidc.issuerUrl,
419
+ oidcClientId: oidc.clientId,
420
+ oidcScope: oidc.scope,
421
+ });
422
+ if (siteType === "StaticSite") {
423
+ return auth.addToStaticSiteProps(
424
+ scope,
425
+ props as ExtendedStaticSiteProps,
426
+ otherAuthProps,
427
+ ) as Props;
428
+ } else if (siteType === "SsrSite") {
429
+ return auth.addToSsrSiteProps(
430
+ scope,
431
+ props as ExtendedNextjsSiteProps,
432
+ otherAuthProps,
433
+ ) as Props;
434
+ }
435
+ siteType satisfies never;
436
+ throw new Error(
437
+ `Unsupported site type ${siteType} when processing auth prop.`,
438
+ );
439
+ }
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=auth-check.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"auth-check.d.ts","sourceRoot":"","sources":["../../../src/cdk-constructs/CloudFrontOidcAuth/auth-check.ts"],"names":[],"mappings":""}
@@ -1 +0,0 @@
1
- {"version":3,"file":"auth-route.d.ts","sourceRoot":"","sources":["../../../src/cdk-constructs/CloudFrontOidcAuth/auth-route.ts"],"names":[],"mappings":"AAyBA,eAAO,MAAM,OAAO,4CAiCnB,CAAC"}
@@ -1,27 +0,0 @@
1
- import { Construct } from "constructs";
2
- import { BaseSiteCdkDistributionProps } from "sst/constructs/BaseSite.js";
3
- type ConstructScope = ConstructorParameters<typeof Construct>[0];
4
- type ConstructId = ConstructorParameters<typeof Construct>[1];
5
- type Mutable<T> = {
6
- -readonly [P in keyof T]: T[P];
7
- };
8
- type Props = {
9
- oidcIssuerUrl: string;
10
- oidcClientId: string;
11
- oidcScope: string;
12
- };
13
- export declare class CloudFrontOidcAuth extends Construct {
14
- readonly oidcIssuerUrl: string;
15
- readonly oidcClientId: string;
16
- readonly oidcScope: string;
17
- readonly id: string;
18
- constructor(scope: ConstructScope, id: ConstructId, props: Props);
19
- addToDistributionDefinition<DistributionProps extends BaseSiteCdkDistributionProps>(scope: ConstructScope, { distributionDefinition, prefix, }: {
20
- distributionDefinition: Mutable<DistributionProps>;
21
- prefix?: string;
22
- }): Mutable<DistributionProps>;
23
- private getFunctionAssociation;
24
- private getAuthBehaviorOptions;
25
- }
26
- export {};
27
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/cdk-constructs/CloudFrontOidcAuth/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AASvC,OAAO,EAAE,4BAA4B,EAAE,MAAM,4BAA4B,CAAC;AAI1E,KAAK,cAAc,GAAG,qBAAqB,CAAC,OAAO,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;AACjE,KAAK,WAAW,GAAG,qBAAqB,CAAC,OAAO,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;AAE9D,KAAK,OAAO,CAAC,CAAC,IAAI;IAChB,CAAC,UAAU,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;CAC/B,CAAC;AAEF,KAAK,KAAK,GAAG;IACX,aAAa,EAAE,MAAM,CAAC;IACtB,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,qBAAa,kBAAmB,SAAQ,SAAS;IAC/C,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;gBAER,KAAK,EAAE,cAAc,EAAE,EAAE,EAAE,WAAW,EAAE,KAAK,EAAE,KAAK;IAQhE,2BAA2B,CACzB,iBAAiB,SAAS,4BAA4B,EAEtD,KAAK,EAAE,cAAc,EACrB,EACE,sBAAsB,EACtB,MAAgB,GACjB,EAAE;QAAE,sBAAsB,EAAE,OAAO,CAAC,iBAAiB,CAAC,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE;IAwC5E,OAAO,CAAC,sBAAsB;IAgI9B,OAAO,CAAC,sBAAsB;CA8E/B"}
@@ -1,198 +0,0 @@
1
- import { Construct } from "constructs";
2
- import SecretsManager from "aws-cdk-lib/aws-secretsmanager";
3
- import CloudFront from "aws-cdk-lib/aws-cloudfront";
4
- import CDK from "aws-cdk-lib";
5
- import CdkCustomResources from "aws-cdk-lib/custom-resources";
6
- import Lambda from "aws-cdk-lib/aws-lambda";
7
- import * as SST from "sst/constructs";
8
- import { Config as SSTInternalConfig } from "sst/config.js";
9
- import CloudFrontOrigins from "aws-cdk-lib/aws-cloudfront-origins";
10
- import path from "node:path";
11
- import fs from "node:fs";
12
- export class CloudFrontOidcAuth extends Construct {
13
- oidcIssuerUrl;
14
- oidcClientId;
15
- oidcScope;
16
- id;
17
- constructor(scope, id, props) {
18
- super(scope, id);
19
- this.oidcIssuerUrl = props.oidcIssuerUrl;
20
- this.oidcClientId = props.oidcClientId;
21
- this.oidcScope = props.oidcScope;
22
- this.id = id;
23
- }
24
- addToDistributionDefinition(scope, { distributionDefinition, prefix = "/auth", }) {
25
- prefix = prefix.replace(/\/$/, ""); // Remove trailing slash from prefix if it has one
26
- const updatedDistributionDefinition = { ...distributionDefinition };
27
- const behaviourName = `${prefix.replace(/^\//g, "")}/*`;
28
- updatedDistributionDefinition.additionalBehaviors =
29
- updatedDistributionDefinition.additionalBehaviors
30
- ? { ...updatedDistributionDefinition.additionalBehaviors }
31
- : {};
32
- if (updatedDistributionDefinition.additionalBehaviors[behaviourName]) {
33
- throw new Error(`Behavior for prefix ${prefix} already exists in distribution definition`);
34
- }
35
- const jwtSecret = new SecretsManager.Secret(this, `${this.id}JwtSecret`, {
36
- description: "JWT Signing Secret",
37
- generateSecretString: {
38
- passwordLength: 32,
39
- excludePunctuation: true,
40
- includeSpace: false,
41
- requireEachIncludedType: true,
42
- },
43
- // Secret is only used for sessions so it's safe to delete on stack removal
44
- removalPolicy: CDK.RemovalPolicy.DESTROY,
45
- });
46
- updatedDistributionDefinition.defaultBehavior = {
47
- ...updatedDistributionDefinition.defaultBehavior,
48
- functionAssociations: [
49
- ...(updatedDistributionDefinition.defaultBehavior
50
- ?.functionAssociations || []),
51
- this.getFunctionAssociation(scope, jwtSecret, prefix),
52
- ],
53
- };
54
- updatedDistributionDefinition.additionalBehaviors[behaviourName] =
55
- this.getAuthBehaviorOptions(scope, jwtSecret, prefix);
56
- return updatedDistributionDefinition;
57
- }
58
- getFunctionAssociation(scope, jwtSecret, authRoutePrefix) {
59
- const cfKeyValueStore = new CloudFront.KeyValueStore(scope, `${this.id}CFKeyValueStore`);
60
- const kvStoreId = cfKeyValueStore.keyValueStoreId; // Your KV store ID
61
- const key = "jwt-secret";
62
- const kvsArn = `arn:aws:cloudfront::${CDK.Stack.of(this).account}:key-value-store/${kvStoreId}`;
63
- // Updating the KVM requires a valid ETag to be provided in the IfMatch parameter so we first must fetch the ETag
64
- const getEtag = new CdkCustomResources.AwsCustomResource(this, `${this.id}GetKVStoreEtag`, {
65
- installLatestAwsSdk: false, // No real benefit in our case for the cost of a longer execution time
66
- onUpdate: {
67
- // Since there's no onCreate, onUpdate will be called for CREATE events
68
- service: "@aws-sdk/client-cloudfront-keyvaluestore",
69
- action: "describeKeyValueStore",
70
- parameters: { KvsARN: kvsArn },
71
- // We include a timestamp in the physicalResourceId to ensure we fetch the latest etag on every update
72
- physicalResourceId: CdkCustomResources.PhysicalResourceId.of(`${kvStoreId}-etag-${Date.now()}`),
73
- },
74
- policy: CdkCustomResources.AwsCustomResourcePolicy.fromSdkCalls({
75
- resources: [kvsArn],
76
- }),
77
- });
78
- const etag = getEtag.getResponseField("ETag");
79
- // An annoying limitation of CloudFormation is that it won't resolve dynamic references for secrets when
80
- // used as a parameter to a custom resource. To get around this we manually resolve it with another custom
81
- // resource. Note this won't result in the secret being exposed in CloudFormation templates but it will
82
- // be visible in the CloudWatch logs of the custom resource lambda. In our case that is acceptable.
83
- // https://github.com/aws-cloudformation/cloudformation-coverage-roadmap/issues/341
84
- const secretValue = new CdkCustomResources.AwsCustomResource(this, `${this.id}GetSecret`, {
85
- // There's no real benefit of fetching the latest sdk our case for the cost of a longer execution time
86
- installLatestAwsSdk: false,
87
- // Since there's no onCreate, onUpdate will be called for CREATE events
88
- onUpdate: {
89
- service: "@aws-sdk/client-secrets-manager",
90
- action: "getSecretValue",
91
- parameters: {
92
- SecretId: jwtSecret.secretArn,
93
- },
94
- // We include a timestamp in the physicalResourceId to ensure we fetch the latest secret value on every update
95
- physicalResourceId: CdkCustomResources.PhysicalResourceId.of(`${this.id}GetSecret-${Date.now()}`),
96
- },
97
- policy: CdkCustomResources.AwsCustomResourcePolicy.fromSdkCalls({
98
- resources: [jwtSecret.secretArn],
99
- }),
100
- });
101
- // Now we can actually update the KVS with the secret value
102
- const putKeyValue = new CdkCustomResources.AwsCustomResource(this, `${this.id}PutKeyValue`, {
103
- installLatestAwsSdk: false, // No real benefit in our case for the cost of a longer execution time
104
- onUpdate: {
105
- // Since there's no onCreate, onUpdate will be called for CREATE events
106
- service: "@aws-sdk/client-cloudfront-keyvaluestore",
107
- action: "putKey",
108
- parameters: {
109
- KvsARN: kvsArn,
110
- Key: key,
111
- Value: secretValue.getResponseField("SecretString"),
112
- IfMatch: etag,
113
- },
114
- physicalResourceId: CdkCustomResources.PhysicalResourceId.of(`${kvStoreId}-${key}`),
115
- },
116
- policy: CdkCustomResources.AwsCustomResourcePolicy.fromSdkCalls({
117
- resources: [kvsArn],
118
- }),
119
- });
120
- // putKey in the @aws-sdk/client-cloudfront-keyvaluestore package requires @aws-sdk/signature-v4-crt to be imported
121
- // as well. But AwsCustomResource doesn't give us direct access to the underlying Lambda function so we inject a
122
- // NODE_OPTIONS env var to import on start. At some point AwsCustomResource will presumably switch to a later node
123
- // version and we might need to update this to '--import=' instead of '--require='.
124
- const fn = putKeyValue.node.findChild("Provider");
125
- if (!(fn instanceof Lambda.SingletonFunction)) {
126
- throw new Error("Could not find the underlying Lambda function of the AwsCustomResource");
127
- }
128
- fn.addEnvironment("NODE_OPTIONS", "--require=@aws-sdk/signature-v4-crt");
129
- const authCheckFunction = new CloudFront.Function(scope, `${this.id}AuthCheckFunction`, {
130
- code: CloudFront.FunctionCode.fromInline(fs
131
- .readFileSync(path.join(import.meta.dirname, "auth-check.js"), "utf8")
132
- .replace("__placeholder-for-jwt-secret-key__", key)
133
- .replace("__placeholder-for-auth-route-prefix__", authRoutePrefix)),
134
- runtime: CloudFront.FunctionRuntime.JS_2_0,
135
- keyValueStore: cfKeyValueStore,
136
- });
137
- return {
138
- function: authCheckFunction,
139
- eventType: CloudFront.FunctionEventType.VIEWER_REQUEST,
140
- };
141
- }
142
- getAuthBehaviorOptions(scope, jwtSecret, prefix) {
143
- const authRouteFunction = new SST.Function(scope, `${this.id}AuthRouteFunction`, {
144
- runtime: "nodejs20.x",
145
- handler: path.join(import.meta.dirname, "auth-route.handler"),
146
- environment: {
147
- OIDC_ISSUER_URL: this.oidcIssuerUrl,
148
- OIDC_CLIENT_ID: this.oidcClientId,
149
- OIDC_SCOPE: this.oidcScope,
150
- JWT_SECRET: jwtSecret.secretValue.toString(),
151
- },
152
- });
153
- // authRouteFunction uses SST's AuthHandler construct which is normally run inside a lambda that's
154
- // created by SST's Auth construct. AuthHandler expects certain environment variables to be set
155
- // by the Auth construct so we have to set them ourselves here to keep it happy.
156
- const envVarName = SSTInternalConfig.envFor({
157
- type: "Auth",
158
- id: "id", // It seems like the env var will still be found no matter what this value is
159
- prop: "prefix",
160
- });
161
- authRouteFunction.addEnvironment(envVarName, prefix);
162
- const authRouteFunctionUrl = authRouteFunction.addFunctionUrl({
163
- authType: Lambda.FunctionUrlAuthType.NONE,
164
- });
165
- const forwardHostHeaderCfFunction = new CloudFront.Function(scope, `${this.id}ForwardHostHeaderFunction`, {
166
- code: CloudFront.FunctionCode.fromInline(`
167
- function handler(event) {
168
- const request = event.request;
169
- request.headers["x-forwarded-host"] = { value: request.headers.host.value };
170
- return request;
171
- }
172
- `),
173
- runtime: CloudFront.FunctionRuntime.JS_2_0,
174
- });
175
- return {
176
- origin: new CloudFrontOrigins.HttpOrigin(CDK.Fn.parseDomainName(authRouteFunctionUrl.url)),
177
- allowedMethods: CloudFront.AllowedMethods.ALLOW_ALL,
178
- cachePolicy: new CloudFront.CachePolicy(scope, `${this.id}AllowAllCookiesPolicy`, {
179
- cachePolicyName: `${this.id}-AllowAllCookiesPolicy`,
180
- comment: "Cache policy that forwards all cookies",
181
- defaultTtl: CDK.Duration.seconds(1),
182
- minTtl: CDK.Duration.seconds(1),
183
- maxTtl: CDK.Duration.seconds(1),
184
- cookieBehavior: CloudFront.CacheCookieBehavior.all(),
185
- headerBehavior: CloudFront.CacheHeaderBehavior.allowList("X-Forwarded-Host"),
186
- queryStringBehavior: CloudFront.CacheQueryStringBehavior.all(),
187
- enableAcceptEncodingGzip: true,
188
- enableAcceptEncodingBrotli: true,
189
- }),
190
- functionAssociations: [
191
- {
192
- function: forwardHostHeaderCfFunction,
193
- eventType: CloudFront.FunctionEventType.VIEWER_REQUEST,
194
- },
195
- ],
196
- };
197
- }
198
- }
@@ -1,245 +0,0 @@
1
- // NOTE: once this is no longer needed we can remove typeRoots from tsconfig.json as well
2
-
3
- // This is a copy of @types/aws-cloudfront-function but with optional kvsId in kvs() function. We can't just modify the
4
- // kvs type since we can't modify the default export without messing up the rest of the types. Which is why we
5
- // unfortunately have to duplicate the whole file here.
6
- // But once https://github.com/DefinitelyTyped/DefinitelyTyped/issues/73959 is sorted we can get rid of this.
7
-
8
- declare namespace AWSCloudFrontFunction {
9
- interface Event {
10
- version: "1.0";
11
- context: Context;
12
- viewer: Viewer;
13
- request: Request;
14
- response: Response;
15
- }
16
-
17
- interface Context {
18
- distributionDomainName: string;
19
- distributionId: string;
20
- eventType: "viewer-request" | "viewer-response";
21
- requestId: string;
22
- }
23
-
24
- interface Viewer {
25
- ip: string;
26
- }
27
-
28
- interface Request {
29
- method: string;
30
- uri: string;
31
- querystring: ValueObject;
32
- headers: ValueObject;
33
- cookies: ValueObject;
34
- }
35
-
36
- interface Response {
37
- statusCode: number;
38
- statusDescription?: string;
39
- headers?: ValueObject;
40
- cookies?: ResponseCookie;
41
- body?: string | ResponseBody;
42
- }
43
-
44
- interface ResponseBody {
45
- data: string;
46
- encoding: "text" | "base64";
47
- }
48
-
49
- interface ValueObject {
50
- [name: string]: {
51
- value: string;
52
- multiValue?: Array<{
53
- value: string;
54
- }>;
55
- };
56
- }
57
-
58
- interface ResponseCookie {
59
- [name: string]: {
60
- value: string;
61
- attributes: string;
62
- multiValue?: Array<{
63
- value: string;
64
- attributes: string;
65
- }>;
66
- };
67
- }
68
- }
69
-
70
- declare module "cloudfront" {
71
- /**
72
- * Retrieves a reference to a CloudFront Key-Value Store (KVS) by its ID.
73
- * @param kvsId The identifier of the KVS to use.
74
- * @see https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/functions-custom-methods.html
75
- */
76
- function kvs(kvsId?: string): KVStore;
77
-
78
- interface KVStore {
79
- /**
80
- * Retrieve a value from the store.
81
- * @param key Key to retrieve.
82
- * @throws If key does not exist.
83
- */
84
- get(key: string): Promise<string>;
85
- get(key: string, options: { format: "string" }): Promise<string>;
86
- get(key: string, options: { format: "bytes" }): Promise<Uint8Array>;
87
- get(key: string, options: { format: "json" }): Promise<unknown>;
88
-
89
- /**
90
- * Check if the key exists in the store.
91
- * @param key Key to check.
92
- */
93
- exists(key: string): Promise<boolean>;
94
-
95
- /**
96
- * Retrieve metadata about the key-value store.
97
- */
98
- meta(): Promise<{
99
- creationDateTime: string;
100
- lastUpdatedDateTime: string;
101
- keyCount: number;
102
- }>;
103
- }
104
-
105
- interface OriginAccessControlConfig {
106
- enabled: boolean;
107
- signingBehavior: "always" | "never" | "no-override";
108
- signingProtocol: "sigv4";
109
- originType: "s3" | "mediapackagev2" | "mediastore" | "lambda";
110
- }
111
-
112
- interface OriginShield {
113
- enabled: boolean;
114
- region: string;
115
- }
116
-
117
- interface Timeouts {
118
- /**
119
- * Max time (seconds) to wait for a response or next packet. (1–60)
120
- */
121
- readTimeout?: number;
122
-
123
- /**
124
- * Max time (seconds) to keep the connection alive after response. (1–60)
125
- */
126
- keepAliveTimeout?: number;
127
-
128
- /**
129
- * Max time (seconds) to wait for connection establishment. (1–10)
130
- */
131
- connectionTimeout?: number;
132
- }
133
-
134
- interface CustomOriginConfig {
135
- /**
136
- * Port number of the origin. e.g., 80 or 443
137
- */
138
- port: number;
139
-
140
- /**
141
- * Protocol used to connect. Must be "http" or "https"
142
- */
143
- protocol: "http" | "https";
144
-
145
- /**
146
- * Minimum TLS/SSL version to use for HTTPS connections.
147
- */
148
- sslProtocols: Array<"SSLv3" | "TLSv1" | "TLSv1.1" | "TLSv1.2">;
149
- }
150
-
151
- interface UpdateRequestOriginParams {
152
- /**
153
- * New origin's domain name. Optional if reusing existing origin's domain.
154
- */
155
- domainName?: string;
156
-
157
- /**
158
- * Path prefix to append when forwarding request to origin.
159
- */
160
- originPath?: string;
161
-
162
- /**
163
- * Override or clear custom headers for the origin request.
164
- */
165
- customHeaders?: Record<string, string>;
166
-
167
- /**
168
- * Number of connection attempts (1–3).
169
- */
170
- connectionAttempts?: number;
171
-
172
- /**
173
- * Origin Shield configuration. Enables shield layer if specified.
174
- */
175
- originShield?: OriginShield;
176
-
177
- /**
178
- * Origin Access Control (OAC) configuration.
179
- */
180
- originAccessControlConfig?: OriginAccessControlConfig;
181
-
182
- /**
183
- * Response and connection timeout configurations.
184
- */
185
- timeouts?: Timeouts;
186
-
187
- /**
188
- * Settings for non-S3 origins or S3 with static website hosting.
189
- */
190
- customOriginConfig?: CustomOriginConfig;
191
- }
192
-
193
- /**
194
- * Mutates the current request’s origin.
195
- * You can specify a new origin (e.g., S3 or ALB), change custom headers, enable OAC, or enable Origin Shield.
196
- * Missing fields will inherit values from the assigned origin.
197
- * @see https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/helper-functions-origin-modification.html#update-request-origin-helper-function
198
- */
199
- function updateRequestOrigin(params: UpdateRequestOriginParams): void;
200
-
201
- /**
202
- * Switches to another origin already defined in the distribution by origin ID.
203
- * This is more efficient than defining a new one via `updateRequestOrigin()`.
204
- * @see https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/helper-functions-origin-modification.html#select-request-origin-id-helper-function
205
- */
206
- function selectRequestOriginById(originId: string): void;
207
-
208
- interface CreateRequestOriginGroupParams {
209
- /**
210
- * Two origin IDs to form an origin group.
211
- * The first is primary; the second is used for failover.
212
- */
213
- originIds: [string, string];
214
-
215
- /**
216
- * Failover selection strategy: default or media-quality-score.
217
- */
218
- selectionCriteria?: "default" | "media-quality-score";
219
-
220
- /**
221
- * List of status codes that trigger failover to the secondary origin.
222
- */
223
- failoverCriteria: {
224
- statusCodes: number[];
225
- };
226
- }
227
-
228
- /**
229
- * Creates a new origin group for failover logic.
230
- * The origin group can be referenced later via origin ID.
231
- * @see https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/helper-functions-origin-modification.html#create-request-origin-group-helper-function
232
- */
233
- function createRequestOriginGroup(
234
- params: CreateRequestOriginGroupParams,
235
- ): void;
236
-
237
- const cf: {
238
- kvs: typeof kvs;
239
- updateRequestOrigin: typeof updateRequestOrigin;
240
- selectRequestOriginById: typeof selectRequestOriginById;
241
- createRequestOriginGroup: typeof createRequestOriginGroup;
242
- };
243
-
244
- export default cf;
245
- }