diff --git a/.changeset/lazy-lemons-grow.md b/.changeset/lazy-lemons-grow.md new file mode 100644 index 00000000..ac71b70c --- /dev/null +++ b/.changeset/lazy-lemons-grow.md @@ -0,0 +1,5 @@ +--- +"@aligent/cdk-domain-hosting": major +--- + +Initial release of new domain-hosting package diff --git a/README.md b/README.md index fe1b33a3..2bc83092 100644 --- a/README.md +++ b/README.md @@ -8,13 +8,14 @@ These are all written for CDK v2. See the offical AWS guide for how to migrate f | ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | [basic-auth](packages/basic-auth) | Restricts CloudFront access behind authentication | | [cloudfront-security-headers](packages/cloudfront-security-headers) | Adds HTTP security headers to origin responses | +| [domain-hosting](packages/domain-hosting) | Provides a construct to manage a Route53 or external domain along with (optionally) the certificate and records | | [esbuild](packages/esbuild) | Provides a construct which allows AWS CDK's bundling process to use the esbuild tool to generate a bundled output | | [feature-env-handlers](packages/feature-env-handlers) | Lambda@Edge handlers to support feature environments | | [geoip-redirect](packages/geoip-redirect) | Lambda@Edge handlers to redirect users based on region | | [graphql-server](packages/graphql-mesh-server) | Creates a [GraphQL Mesh](https://the-guild.dev/graphql/mesh) server to assist with data transformation from multiple sources | | [header-change-detection](packages/header-change-detection) | Creates a Lambda function that periodically scans security headers and sends the results to SNS | | [prerender-fargate](packages/prerender-fargate) | Self-hosted prerender to handle prerender bot requests | -| [prerender-proxy](packages/prerender-proxy) | Provides an functions to adjust self-hosted prerender behaviour | +| [prerender-proxy](packages/prerender-proxy) | Provides functions to adjust self-hosted prerender behaviour | | [rabbitmq](packages/rabbitmq) | Create a RabbitMQ cluster within CDK | | [shared-vpc](packages/shared-vpc) | Creates a single VPC with static IP for micro-services with DNS management | | [static-hosting](packages/static-hosting) | Construct to deploy infrastructure for static webpage hosting | diff --git a/packages/domain-hosting/.npmignore b/packages/domain-hosting/.npmignore new file mode 100644 index 00000000..cdd96308 --- /dev/null +++ b/packages/domain-hosting/.npmignore @@ -0,0 +1,34 @@ +# TypeScript source files +*.ts +!*.d.ts + +# But keep Lambda handler TypeScript files +!lib/handlers/**/*.ts + +# TypeScript configuration +tsconfig*.json + +# Jest configuration +jest.config.ts + +# Nx project configuration +project.json + +# Test files +test/ +**/*.test.ts +**/*.test.js +**/*.spec.ts +**/*.spec.js + +# Development dependencies +node_modules/ + +# Keep these files in published package: +# *.js (compiled JavaScript) +# *.d.ts (TypeScript declarations) +# README.md +# CHANGELOG.md +# package.json +# lib/handlers/ (Lambda handler files) +# docs/ \ No newline at end of file diff --git a/packages/domain-hosting/README.md b/packages/domain-hosting/README.md new file mode 100644 index 00000000..f966ae98 --- /dev/null +++ b/packages/domain-hosting/README.md @@ -0,0 +1,157 @@ +# Aligent AWS Domain Hosting + +## Overview + +![TypeScript version](https://img.shields.io/github/package-json/dependency-version/aligent/cdk-constructs/dev/typescript?filename=packages/static-hosting/package.json&color=red) ![AWS CDK version](https://img.shields.io/github/package-json/dependency-version/aligent/cdk-constructs/dev/aws-cdk?filename=packages/static-hosting/package.json) ![NPM version](https://img.shields.io/npm/v/%40aligent%2Fcdk-static-hosting?color=green) + +A simple package used for creating and/or managing a hosted zone in AWS. Handy for setting up a cloudfront site from scratch when there's no existing domain management in place or integrating into an already existing setup. +You are able to use a domain that was requested through AWS Route53 or an external provider. + +It can be imported and used within CDK applications. By default this construct will create a hosted zone and a certificate to validate a domain against. Records are not created unless explicitly stated. + +It has the following features that can optionally be enabled: + +- Create custom records of `CNAME`, `A`, `AAAA`, `MX`, and `SRV` types +- Create a certificate for the specified domain (and any subdomains) + +## If using an external provider +You will need to set the NS record in your provider's management page to the values in the hosted zone after you run `cdk deploy` as the certificate will not validate otherwise + +## Installation + +```bash +npm install @aligent/cdk-domain-hosting aws-cdk-lib constructs +``` + +Or with yarn: + +```bash +yarn add @aligent/cdk-static-hosting aws-cdk-lib constructs +``` + +### Peer Dependencies + +This package has peer dependencies on: +- `aws-cdk-lib` (^2.120.0) +- `constructs` (^10.0.0) + +Make sure to install compatible versions of these packages in your CDK application. + +## Usage +### `domainName`(string) +- Domain name for the hosted zone. This is also the base for the certificate that is created. Combined with the subDomainName it is used as the name for the S3 origin and an alternative domain name for the CloudFront distribution + +### `hostedZoneId?`(string) +- If you are using a zone that already exists just put its id instead. This will make the CDK update the existing zone in place (it will not remove records that aren't in the code yet) + +Default: **undefined** + +### `createCertificate?` (boolean) + +- Explicitly state if you want a certificate created for the default domain `domainName` value. Hosted Zones do not require a cert on creation. This is set to true if you pass in `subDomains` +- The Cert is created in `us-east-1` + +Default: **false** + +### `certificateArn?` (string) + +- The arn of the certificate to validate against if one already exists. + +Default: **undefined** + +### `subDomains?` (string) + +- Extra subdomains to add to the certificate for validation. + +Default: **[]** + +### `records?` (string) + +- Any records to create in the zone, can be of types `CNAME`, `A`, `AAAA`, `MX`, and `SRV` +- See usage block below for an example + + +## Example + +The following CDK snippet can be used to provision a zone with records and a certificate using this construct. + +``` +import { Construct } from "constructs"; +import { Stack } from "aws-cdk-lib"; +import { DomainHosting } from "@aligent/cdk-domain-hosting"; +import { DomainHostingProps } from "../types"; +import { RecordTarget } from "aws-cdk-lib/aws-route53"; +import { CloudFrontTarget } from "aws-cdk-lib/aws-route53-targets"; + +export class DomainHostingStack extends Stack { + constructor(scope: Construct, id: string, props: DomainHostingProps) { + super(scope, id, props); + + new DomainHosting(this, "DomainHostingStack", { + domainName: props.domainName, + subDomains: ['www'], + records: [ + { + type: 'CNAME', + name: 'www.example.com', + value: props.distribution.distributionDomainName + }, + { + type: 'A', + name: 'www.example.com', + value: RecordTarget.fromAlias(new CloudFrontTarget(props.distribution)) + }, + { + type: 'SRV', + name: 'xmpp.example.com', + value: [{ port: 443, priority: 1, hostName: 'xmpp-srv', weight: 10 }] + }, + { + type: 'MX', + name: 'mail.example.com', + value: [{ priority: 1, hostName: 'mymail' }] + }, + { + type: 'AAAA', + name: 'www.example.com', + value: RecordTarget.fromAlias(new CloudFrontTarget(props.distribution)) + }, + ] + }); + } +} +``` + +The below one would be used if you already had a certificate or hosted zone and just wanted to control it with CDK + +``` +new DomainHosting(this, "DomainHostingStack", { + domainName: props.domainName, + hostedZoneId: 'Z0123ABC', + certificateArn: 'arn:aws:acm:us-east-1:xyz', +}) +``` +### Little note +If you are using the StaticHostingStack you can get the CloudFront distribution value to pass as an Alias like so: + +#### static-hosting-stack.ts +``` +export class StaticHostingStack extends Stack { + public readonly distribution: IDistribution; // create a class variable + ... + const hosting = new StaticHosting(this, "StaticHostingStack", {...}) // save it to a variable + this.distribution = hosting.distribution // get the variable here +} +``` + + #### application.ts +``` + const staticHosting = new StaticHostingStack(this, "StaticHostingStack", { + ... + }); // from static-hosting-stack.ts class + + const domainHosting = new DomainHostingStack(this, "DomainHostingStack", { + ...props, + distribution: staticHosting.distribution // pass in here + }); +``` diff --git a/packages/domain-hosting/index.ts b/packages/domain-hosting/index.ts new file mode 100644 index 00000000..e198c9f8 --- /dev/null +++ b/packages/domain-hosting/index.ts @@ -0,0 +1,3 @@ +import { DomainHosting, DomainHostingProps } from "./lib/domain-hosting"; + +export { DomainHosting, DomainHostingProps }; diff --git a/packages/domain-hosting/jest.config.ts b/packages/domain-hosting/jest.config.ts new file mode 100644 index 00000000..34da2ebe --- /dev/null +++ b/packages/domain-hosting/jest.config.ts @@ -0,0 +1,11 @@ +/* eslint-disable */ +export default { + displayName: "domain-hosting", + preset: "../../jest.preset.js", + testEnvironment: "node", + transform: { + "^.+\\.[tj]s$": ["ts-jest", { tsconfig: "/tsconfig.spec.json" }], + }, + moduleFileExtensions: ["ts", "js", "html"], + coverageDirectory: "../../coverage/packages/domain-hosting", +}; diff --git a/packages/domain-hosting/lib/domain-hosting.ts b/packages/domain-hosting/lib/domain-hosting.ts new file mode 100644 index 00000000..b6eb3b30 --- /dev/null +++ b/packages/domain-hosting/lib/domain-hosting.ts @@ -0,0 +1,124 @@ +import { Construct } from "constructs"; +import { + Certificate, + DnsValidatedCertificate, +} from "aws-cdk-lib/aws-certificatemanager"; +import { + AaaaRecord, + ARecord, + CnameRecord, + HostedZone, + MxRecord, + MxRecordValue, + PublicHostedZone, + RecordTarget, + SrvRecord, + SrvRecordValue, + TxtRecord, +} from "aws-cdk-lib/aws-route53"; + +type DNSRecord = + | { type: "A"; name: string; value: RecordTarget } + | { type: "AAAA"; name: string; value: RecordTarget } + | { type: "CNAME"; name: string; value: string } + | { type: "TXT"; name: string; value: string[] } + | { type: "MX"; name: string; value: MxRecordValue[] } + | { type: "SRV"; name: string; value: SrvRecordValue[] }; + +export interface DomainHostingProps { + domainName: string; + hostedZoneId?: string; + createCertificate?: boolean; + certificateArn?: string; + subDomains?: string[]; + records?: DNSRecord[]; +} + +export class DomainHosting extends Construct { + constructor(scope: Construct, id: string, props: DomainHostingProps) { + super(scope, id); + + const { + domainName, + hostedZoneId, + createCertificate = false, + certificateArn, + subDomains = [], + records = [], + } = props; + + let hostedZone; + const createCert = createCertificate || subDomains.length > 0; + if (!hostedZoneId) { + hostedZone = new PublicHostedZone(this, "HostedZone", { + zoneName: domainName, + }); + } else { + hostedZone = HostedZone.fromHostedZoneAttributes(this, "HostedZone", { + hostedZoneId, + zoneName: domainName, + }); + } + if (certificateArn) { + Certificate.fromCertificateArn(this, "DomainCertificate", certificateArn); + } else if (createCert) { + // If you are creating a certificate and your domain is hosted outside AWS don't forget to update the NS record in your provider + // @deprecated but no replacement for generating cert and creating CNAMEs in zone + new DnsValidatedCertificate(this, "Certificate", { + domainName: domainName, + subjectAlternativeNames: [...subDomains.map(s => `${s}.${domainName}`)], + hostedZone: hostedZone, + region: "us-east-1", + }); + } + if (records) { + records.map(r => { + const recordId = `${r.name}-${r.type}`; + switch (r.type) { + case "A": + new ARecord(this, recordId, { + zone: hostedZone, + target: r.value, + }); + break; + case "AAAA": + new AaaaRecord(this, recordId, { + zone: hostedZone, + target: r.value, + }); + break; + case "CNAME": + new CnameRecord(this, recordId, { + zone: hostedZone, + domainName: r.value, + recordName: r.name, + }); + break; + case "TXT": + new TxtRecord(this, recordId, { + zone: hostedZone, + values: r.value, + recordName: r.name, + }); + break; + case "MX": + new MxRecord(this, recordId, { + zone: hostedZone, + values: r.value, + recordName: r.name, + }); + break; + case "SRV": + new SrvRecord(this, recordId, { + zone: hostedZone, + values: r.value, + recordName: r.name, + }); + break; + default: + break; + } + }); + } + } +} diff --git a/packages/domain-hosting/package.json b/packages/domain-hosting/package.json new file mode 100644 index 00000000..c6f24f60 --- /dev/null +++ b/packages/domain-hosting/package.json @@ -0,0 +1,46 @@ +{ + "name": "@aligent/cdk-domain-hosting", + "version": "0.0.1", + "main": "index.js", + "license": "MIT", + "homepage": "https://github.com/aligent/aws-cdk-constructs/tree/main/packages/domain-hosting#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/aligent/aws-cdk-constructs.git" + }, + "types": "index.d.ts", + "scripts": { + "build": "tsc", + "test": "npx nx test domain-hosting", + "lint": "npx nx lint domain-hosting" + }, + "devDependencies": { + "@aligent/cdk-esbuild": "^2.5.1", + "@types/aws-lambda": "^8.10.150", + "@types/jest": "^29.5.10", + "@types/node": "^20.6.3", + "aws-cdk": "^2.1019.1", + "aws-cdk-lib": "^2.168.0", + "aws-sdk-client-mock": "^3.0.0", + "constructs": "^10.4.2", + "jest": "^29.7.0", + "ts-jest": "^29.1.1", + "ts-node": "^10.9.1", + "typescript": "^5.3.2" + }, + "dependencies": { + "source-map-support": "^0.5.21" + }, + "peerDependencies": { + "aws-cdk-lib": "^2.120.0", + "constructs": "^10.0.0" + }, + "peerDependenciesMeta": { + "aws-cdk-lib": { + "optional": false + }, + "constructs": { + "optional": false + } + } +} diff --git a/packages/domain-hosting/project.json b/packages/domain-hosting/project.json new file mode 100644 index 00000000..48463231 --- /dev/null +++ b/packages/domain-hosting/project.json @@ -0,0 +1,36 @@ +{ + "name": "domain-hosting", + "$schema": "../../node_modules/nx/schemas/project-schema.json", + "sourceRoot": "packages/domain-hosting/lib", + "projectType": "application", + "targets": { + "build": { + "executor": "nx:run-commands", + "options": { + "command": "tsc --project tsconfig.app.json", + "cwd": "packages/domain-hosting" + } + }, + "lint": { + "executor": "@nx/eslint:lint", + "outputs": ["{options.outputFile}"] + }, + "test": { + "executor": "@nx/jest:jest", + "outputs": ["{workspaceRoot}/coverage/{projectRoot}"], + "options": { + "jestConfig": "packages/domain-hosting/jest.config.ts", + "passWithNoTests": true + } + }, + "publish": { + "executor": "nx:run-commands", + "options": { + "command": "npm publish --access public", + "cwd": "packages/domain-hosting" + }, + "dependsOn": ["build"] + } + }, + "tags": [] +} diff --git a/packages/domain-hosting/tsconfig.app.json b/packages/domain-hosting/tsconfig.app.json new file mode 100644 index 00000000..a0fc582a --- /dev/null +++ b/packages/domain-hosting/tsconfig.app.json @@ -0,0 +1,16 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": ".", + "rootDir": ".", + "module": "commonjs", + "types": ["node"] + }, + "exclude": [ + "./jest.config.ts", + "lib/handlers", + "**/*.test.ts", + "**/*.spec.ts" + ], + "include": ["lib/**/*.ts", "index.ts"] +} diff --git a/packages/domain-hosting/tsconfig.json b/packages/domain-hosting/tsconfig.json new file mode 100644 index 00000000..c1e2dd4e --- /dev/null +++ b/packages/domain-hosting/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../tsconfig.base.json", + "files": [], + "include": [], + "references": [ + { + "path": "./tsconfig.app.json" + }, + { + "path": "./tsconfig.spec.json" + } + ], + "compilerOptions": { + "esModuleInterop": true + } +} diff --git a/packages/domain-hosting/tsconfig.spec.json b/packages/domain-hosting/tsconfig.spec.json new file mode 100644 index 00000000..f14c3559 --- /dev/null +++ b/packages/domain-hosting/tsconfig.spec.json @@ -0,0 +1,8 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "../../dist/out-tsc", + "module": "commonjs", + "types": ["jest", "node"] + } +} diff --git a/yarn.lock b/yarn.lock index ee34acd3..52fd162b 100644 --- a/yarn.lock +++ b/yarn.lock @@ -74,6 +74,34 @@ __metadata: languageName: unknown linkType: soft +"@aligent/cdk-domain-hosting@workspace:packages/domain-hosting": + version: 0.0.0-use.local + resolution: "@aligent/cdk-domain-hosting@workspace:packages/domain-hosting" + dependencies: + "@aligent/cdk-esbuild": "npm:^2.5.1" + "@types/aws-lambda": "npm:^8.10.150" + "@types/jest": "npm:^29.5.10" + "@types/node": "npm:^20.6.3" + aws-cdk: "npm:^2.1019.1" + aws-cdk-lib: "npm:^2.168.0" + aws-sdk-client-mock: "npm:^3.0.0" + constructs: "npm:^10.4.2" + jest: "npm:^29.7.0" + source-map-support: "npm:^0.5.21" + ts-jest: "npm:^29.1.1" + ts-node: "npm:^10.9.1" + typescript: "npm:^5.3.2" + peerDependencies: + aws-cdk-lib: ^2.120.0 + constructs: ^10.0.0 + peerDependenciesMeta: + aws-cdk-lib: + optional: false + constructs: + optional: false + languageName: unknown + linkType: soft + "@aligent/cdk-esbuild@npm:^2.5.1, @aligent/cdk-esbuild@workspace:packages/esbuild": version: 0.0.0-use.local resolution: "@aligent/cdk-esbuild@workspace:packages/esbuild"