Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/lazy-lemons-grow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@aligent/cdk-domain-hosting": major
---

Initial release of new domain-hosting package
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
34 changes: 34 additions & 0 deletions packages/domain-hosting/.npmignore
Original file line number Diff line number Diff line change
@@ -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/
157 changes: 157 additions & 0 deletions packages/domain-hosting/README.md
Original file line number Diff line number Diff line change
@@ -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
});
```
3 changes: 3 additions & 0 deletions packages/domain-hosting/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { DomainHosting, DomainHostingProps } from "./lib/domain-hosting";

export { DomainHosting, DomainHostingProps };
11 changes: 11 additions & 0 deletions packages/domain-hosting/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/* eslint-disable */
export default {
displayName: "domain-hosting",
preset: "../../jest.preset.js",
testEnvironment: "node",
transform: {
"^.+\\.[tj]s$": ["ts-jest", { tsconfig: "<rootDir>/tsconfig.spec.json" }],
},
moduleFileExtensions: ["ts", "js", "html"],
coverageDirectory: "../../coverage/packages/domain-hosting",
};
124 changes: 124 additions & 0 deletions packages/domain-hosting/lib/domain-hosting.ts
Original file line number Diff line number Diff line change
@@ -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;
}
});
}
}
}
Loading