From eaa292a16f2b3e73ec46fdac622af53f3d65d71c Mon Sep 17 00:00:00 2001 From: Adam Moussa <166072409+amoussa1229@users.noreply.github.com> Date: Tue, 28 Apr 2026 20:09:35 -0400 Subject: [PATCH] Add lockdown poller Lambda and fix lockdown handler responses - Add VPC-connected poller Lambda that monitors lockdown status via Elements API every 15 seconds (4 polls per 1-min EventBridge schedule) - Handle Elements API rate limits (429) with retry-after support - Fix lockdown handler to use TextScreen XML instead of Execute XML (Execute shows globe icon on T58W, TextScreen renders properly) - Fix Elements API status parsing to be case-insensitive - Trust toggle action instead of re-checking status (eventual consistency) - Configure push_xml.server = any in T58W template for Push XML support - Clear action_url.setup_completed (poller replaces boot-time check) - Update README with lockdown architecture and known LED limitation Note: T58W line key LED color does not change to reflect lockdown status. Execute LED commands are transient on the T58W - the phone's XML Browser key type immediately overrides them. --- README.md | 53 +++++++++++++----- cdk.context.json | 47 ++++++++++++++++ lambda/lockdown/lockdown-handler.ts | 46 +++++++-------- lambda/poller/lockdown-poller.ts | 86 +++++++++++++++++++++++++++++ lib/door-unlock-stack.ts | 78 ++++++++++++++++++++++++++ yealinkT58W-door-unlock.ph.xml | 4 +- 6 files changed, 274 insertions(+), 40 deletions(-) create mode 100644 cdk.context.json create mode 100644 lambda/poller/lockdown-poller.ts diff --git a/README.md b/README.md index 27de860..994e910 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,34 @@ # Sea Haven Door Unlock API -AWS Lambda middleware that allows a Yealink T54W desk phone to unlock the front door controlled by LenelS2 Elements. Press a DSS key on the phone, and the door unlocks. +AWS Lambda middleware that allows Yealink desk phones to unlock the front door and manage lockdown profiles via LenelS2 Elements. ``` -Yealink T54W → HTTPS GET → API Gateway → Lambda → LenelS2 Elements API → Door Unlocks +Yealink T54W/T58W → HTTPS GET → API Gateway → Lambda → LenelS2 Elements API ``` ## Architecture -- **API Gateway (HTTP API)** — single `GET /unlock` endpoint with throttling (5 burst / 2 sustained req/sec) -- **Lambda (Node.js 20.x)** — validates a shared auth token, calls the Elements `TemporaryUnlock` command -- **SSM Parameter Store** — stores the Elements API key, auth token, and door device ID +- **API Gateway (HTTP API)** — `GET /unlock`, `GET /lockdown`, `GET /lockdown/status` with throttling (5 burst / 2 sustained req/sec) +- **Unlock Lambda** — validates a shared auth token, calls the Elements `TemporaryUnlock` command +- **Lockdown Lambda** — toggles lockdown profiles (start/stop) and checks status, returns Yealink XML TextScreen responses +- **Lockdown Poller Lambda** — VPC-connected, polls Elements API every 15 seconds for lockdown status (runs 4x per 1-minute EventBridge schedule) +- **SSM Parameter Store** — stores the Elements API key, auth token, door ID, and phone IPs +- **Secrets Manager** — stores the Yealink phone admin password - **Custom Domain** — `doorunlock.seahaven.com` via Route 53 + ACM wildcard cert +## Lockdown Profiles + +Two lockdown profiles are configured: + +| Profile | Elements ID | Line Key | +|---------|-------------|----------| +| Bohemia - Whole Building | `4b4a3e6b-c903-4cce-8cd6-288612bf0542` | 3 | +| Ronkonkoma - Whole Building | `ff9876bc-c54f-472e-aef9-d2bffd4b7cf7` | 4 | + +Pressing the line key toggles the lockdown on/off and displays the current status on the phone screen. + +**Known limitation:** Line key LED color does not currently change to reflect lockdown status. The T58W's XML Browser key type (17) does not support persistent LED color changes via Push XML or Execute commands — LED commands are transient and immediately overridden by the phone's key type management. + ## SSM Parameters | Parameter | Type | Description | @@ -20,6 +36,13 @@ Yealink T54W → HTTPS GET → API Gateway → Lambda → LenelS2 Elements API | `/seahaven/door-unlock/elements-api-key` | SecureString | LenelS2 Elements API key | | `/seahaven/door-unlock/auth-token` | SecureString | Shared secret embedded in the Yealink DSS key URL | | `/seahaven/door-unlock/door-id` | String | Elements device ID for the front door reader | +| `/seahaven/door-unlock/phone-ips` | String | Comma-separated phone IPs for lockdown poller | + +## Secrets Manager + +| Secret | Description | +|--------|-------------| +| `door-unlock-api/phone-password` | Yealink phone admin password for Push XML | ## Deployment @@ -30,18 +53,22 @@ npx cdk deploy ## Phone Configuration -Configure a DSS key on the Yealink T54W (via phone web UI or 3CX): +Configure DSS keys on the Yealink T54W/T58W (via phone web UI or 3CX): -- **Type:** URL -- **Label:** Unlock Door -- **Value:** `https://doorunlock.seahaven.com/unlock?token=` +- **Key 2 — Unlock Door** + - Type: URL + - Value: `https://doorunlock.seahaven.com/unlock?token=` + +- **Keys 3-4 — Lockdown Toggle** + - Type: XML Browser (17) + - Value: `https://doorunlock.seahaven.com/lockdown?token=&profile=bohemia|ronkonkoma` ## 3CX Provisioning Templates -Custom 3CX templates are included with the door unlock URL hardcoded on line key 2. +Custom 3CX templates are included with door unlock and lockdown URLs hardcoded. -| Template | Model | Line Key 2 | Keys 3+ | Display | -|----------|-------|-----------|---------|---------| +| Template | Model | Key 2 | Keys 3-4 | Display | +|----------|-------|-------|----------|---------| | `yealinkT54W-door-unlock.ph.xml` | T54W | Unlock Door | Managed by 3CX BLF | Dim after 5 min, never sleep | | `yealinkT54W-door-unlock-with-sp.ph.xml` | T54W | Unlock Door | Shared Parking SP1-3 | Dim after 5 min, never sleep | -| `yealinkT58W-door-unlock.ph.xml` | T58W | Unlock Door | Managed by 3CX BLF | Default T58W display settings | +| `yealinkT58W-door-unlock.ph.xml` | T58W | Unlock Door | Lockdown Toggle (Bohemia/Ronkonkoma) | Default T58W display settings | diff --git a/cdk.context.json b/cdk.context.json new file mode 100644 index 0000000..068ec0c --- /dev/null +++ b/cdk.context.json @@ -0,0 +1,47 @@ +{ + "vpc-provider:account=328440206208:filter.vpc-id=vpc-0d3d4b67bd0cf8a68:region=us-east-1:returnAsymmetricSubnets=true": { + "vpcId": "vpc-0d3d4b67bd0cf8a68", + "vpcCidrBlock": "10.20.0.0/16", + "ownerAccountId": "328440206208", + "availabilityZones": [], + "vpnGatewayId": "vgw-073737d44762dffc2", + "subnetGroups": [ + { + "name": "Private", + "type": "Private", + "subnets": [ + { + "subnetId": "subnet-04e38c507e96f1926", + "cidr": "10.20.30.0/24", + "availabilityZone": "us-east-1a", + "routeTableId": "rtb-06a2f56f492b9b4de" + }, + { + "subnetId": "subnet-0a0b4fc6f296dfba5", + "cidr": "10.20.40.0/24", + "availabilityZone": "us-east-1b", + "routeTableId": "rtb-01e152fe5cabca7d6" + } + ] + }, + { + "name": "Public", + "type": "Public", + "subnets": [ + { + "subnetId": "subnet-0eea820effe1b3ae5", + "cidr": "10.20.10.0/24", + "availabilityZone": "us-east-1a", + "routeTableId": "rtb-0f2232493a5c43fe8" + }, + { + "subnetId": "subnet-0012f5895182c1580", + "cidr": "10.20.20.0/24", + "availabilityZone": "us-east-1b", + "routeTableId": "rtb-0f2232493a5c43fe8" + } + ] + } + ] + } +} diff --git a/lambda/lockdown/lockdown-handler.ts b/lambda/lockdown/lockdown-handler.ts index 44cd3ff..706b942 100644 --- a/lambda/lockdown/lockdown-handler.ts +++ b/lambda/lockdown/lockdown-handler.ts @@ -43,7 +43,8 @@ async function getLockdownStatus(lockdownId: string, apiKey: string): Promise; - return data.status === "active" || data.isActive === true; + console.log(JSON.stringify({ action: "lockdown_raw_status", lockdownId, data })); + return String(data.status).toLowerCase() === "active"; } async function setLockdown(lockdownId: string, apiKey: string, start: boolean): Promise { @@ -63,14 +64,14 @@ async function setLockdown(lockdownId: string, apiKey: string, start: boolean): } } -// LED values: 0=off, 1=green, 2=green fast blink, 3=green slow blink, 4=red, 5=red fast blink, 6=red slow blink -function ledColor(active: boolean): number { - return active ? 4 : 1; -} - -function yealinkExecuteXml(items: string[]): string { - const body = items.map(uri => ` `).join("\n"); - return `\n\n${body}\n`; +function textScreenXml(title: string, text: string): string { + return [ + ``, + ``, + ` ${title}`, + ` ${text}`, + ``, + ].join("\n"); } function xmlResponse(statusCode: number, body: string) { @@ -81,10 +82,6 @@ function xmlResponse(statusCode: number, body: string) { }; } -function errorXml(message: string): string { - return `\n\n Error\n ${message}\n`; -} - export async function handler(event: { queryStringParameters?: Record; rawPath?: string; @@ -105,7 +102,7 @@ export async function handler(event: { secrets = await loadSecrets(); } catch (err) { console.error(JSON.stringify({ action: "lockdown", status: "error", reason: "ssm_failure", sourceIp, error: String(err) })); - return xmlResponse(500, errorXml("Internal error")); + return xmlResponse(500, textScreenXml("Error", "Internal error")); } if (token !== secrets.authToken) { @@ -122,24 +119,24 @@ export async function handler(event: { async function handleStatus(apiKey: string, sourceIp: string) { try { - const ledItems: string[] = []; + const lines: string[] = []; for (const [key, config] of Object.entries(LOCKDOWN_PROFILES)) { const active = await getLockdownStatus(config.id, apiKey); - ledItems.push(`Led:LINEKEY${config.linekey}=${ledColor(active)}`); + lines.push(`${config.name}: ${active ? "LOCKED DOWN" : "Normal"}`); console.log(JSON.stringify({ action: "lockdown_status", profile: key, active, sourceIp })); } - return xmlResponse(200, yealinkExecuteXml(ledItems)); + return xmlResponse(200, textScreenXml("Lockdown Status", lines.join("\n"))); } catch (err) { console.error(JSON.stringify({ action: "lockdown_status", status: "error", sourceIp, error: String(err) })); - return xmlResponse(502, errorXml("Unable to check lockdown status")); + return xmlResponse(502, textScreenXml("Error", "Unable to check lockdown status")); } } async function handleToggle(profile: string | undefined, apiKey: string, sourceIp: string) { if (!profile || !LOCKDOWN_PROFILES[profile]) { - return xmlResponse(400, errorXml("Invalid profile")); + return xmlResponse(400, textScreenXml("Error", "Invalid profile")); } const config = LOCKDOWN_PROFILES[profile]; @@ -147,21 +144,20 @@ async function handleToggle(profile: string | undefined, apiKey: string, sourceI try { const wasActive = await getLockdownStatus(config.id, apiKey); await setLockdown(config.id, apiKey, !wasActive); - const isActive = await getLockdownStatus(config.id, apiKey); + const nowActive = !wasActive; console.log(JSON.stringify({ action: "lockdown_toggle", profile, wasActive, - isActive, + nowActive, sourceIp, })); - return xmlResponse(200, yealinkExecuteXml([ - `Led:LINEKEY${config.linekey}=${ledColor(isActive)}`, - ])); + const statusText = nowActive ? "LOCKED DOWN" : "Normal"; + return xmlResponse(200, textScreenXml(config.name, statusText)); } catch (err) { console.error(JSON.stringify({ action: "lockdown_toggle", status: "error", profile, sourceIp, error: String(err) })); - return xmlResponse(502, errorXml(`Lockdown error: ${config.name}`)); + return xmlResponse(502, textScreenXml("Error", `Lockdown error: ${config.name}`)); } } diff --git a/lambda/poller/lockdown-poller.ts b/lambda/poller/lockdown-poller.ts new file mode 100644 index 0000000..1e7789a --- /dev/null +++ b/lambda/poller/lockdown-poller.ts @@ -0,0 +1,86 @@ +import { + SSMClient, + GetParameterCommand, +} from "@aws-sdk/client-ssm"; + +const ssm = new SSMClient({}); + +let cachedApiKey: string | undefined; + +const LOCKDOWN_PROFILES: { key: string; id: string }[] = [ + { key: "bohemia", id: "4b4a3e6b-c903-4cce-8cd6-288612bf0542" }, + { key: "ronkonkoma", id: "ff9876bc-c54f-472e-aef9-d2bffd4b7cf7" }, +]; + +const ELEMENTS_BASE_URL = "https://api.elementssecure.com/v1"; +const POLL_COUNT = 4; +const POLL_INTERVAL_MS = 15_000; + +async function getSsmParam(name: string, decrypt: boolean): Promise { + const res = await ssm.send( + new GetParameterCommand({ Name: name, WithDecryption: decrypt }) + ); + return res.Parameter!.Value!; +} + +async function loadApiKey(): Promise { + if (!cachedApiKey) { + cachedApiKey = await getSsmParam(process.env.ELEMENTS_API_KEY_PARAM!, true); + } + return cachedApiKey; +} + +function sleep(ms: number): Promise { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +async function getLockdownStatus(lockdownId: string, apiKey: string): Promise { + const response = await fetch(`${ELEMENTS_BASE_URL}/lockdowns/${lockdownId}`, { + headers: { "api-key": apiKey }, + }); + + if (response.status === 429) { + const retryAfter = parseInt(response.headers.get("retry-after") ?? "2", 10); + await sleep(retryAfter * 1000); + return getLockdownStatus(lockdownId, apiKey); + } + + if (!response.ok) { + throw new Error(`Elements status check failed: ${response.status}`); + } + + const data = await response.json() as Record; + return String(data.status).toLowerCase() === "active"; +} + +export async function handler() { + let apiKey: string; + try { + apiKey = await loadApiKey(); + } catch (err) { + console.error(JSON.stringify({ action: "poller_config_error", error: String(err) })); + return; + } + + for (let i = 0; i < POLL_COUNT; i++) { + try { + const statuses = []; + for (const profile of LOCKDOWN_PROFILES) { + const active = await getLockdownStatus(profile.id, apiKey); + statuses.push({ profile: profile.key, active }); + } + + console.log(JSON.stringify({ + action: "poller_cycle", + iteration: i + 1, + statuses, + })); + } catch (err) { + console.error(JSON.stringify({ action: "poller_poll_error", iteration: i + 1, error: String(err) })); + } + + if (i < POLL_COUNT - 1) { + await sleep(POLL_INTERVAL_MS); + } + } +} diff --git a/lib/door-unlock-stack.ts b/lib/door-unlock-stack.ts index 9244648..724f6f9 100644 --- a/lib/door-unlock-stack.ts +++ b/lib/door-unlock-stack.ts @@ -3,6 +3,10 @@ import * as lambda from "aws-cdk-lib/aws-lambda"; import * as apigwv2 from "aws-cdk-lib/aws-apigatewayv2"; import * as integrations from "aws-cdk-lib/aws-apigatewayv2-integrations"; import * as ssm from "aws-cdk-lib/aws-ssm"; +import * as secretsmanager from "aws-cdk-lib/aws-secretsmanager"; +import * as ec2 from "aws-cdk-lib/aws-ec2"; +import * as events from "aws-cdk-lib/aws-events"; +import * as targets from "aws-cdk-lib/aws-events-targets"; import * as route53 from "aws-cdk-lib/aws-route53"; import * as route53Targets from "aws-cdk-lib/aws-route53-targets"; import * as acm from "aws-cdk-lib/aws-certificatemanager"; @@ -96,6 +100,80 @@ export class DoorUnlockStack extends cdk.Stack { elementsApiKeyParam.grantRead(lockdownHandler); authTokenParam.grantRead(lockdownHandler); + const vpc = ec2.Vpc.fromLookup(this, "SeaHavenVpc", { + vpcId: "vpc-0d3d4b67bd0cf8a68", + }); + + const privateSubnet1 = ec2.Subnet.fromSubnetId( + this, "PrivateSubnet1", "subnet-04e38c507e96f1926" + ); + const privateSubnet2 = ec2.Subnet.fromSubnetId( + this, "PrivateSubnet2", "subnet-0a0b4fc6f296dfba5" + ); + + const pollerSg = new ec2.SecurityGroup(this, "PollerSecurityGroup", { + vpc, + securityGroupName: "door-unlock-api-poller", + description: "Lockdown poller - outbound to Elements API and phone LAN", + allowAllOutbound: false, + }); + pollerSg.addEgressRule( + ec2.Peer.anyIpv4(), ec2.Port.tcp(443), "HTTPS to Elements API and SSM via NAT" + ); + pollerSg.addEgressRule( + ec2.Peer.ipv4("10.10.0.0/16"), ec2.Port.tcp(443), "HTTPS to phone LAN via VPN" + ); + + const phoneIpsParam = ssm.StringParameter.fromStringParameterName( + this, "PhoneIps", "/seahaven/door-unlock/phone-ips" + ); + + const phonePasswordSecret = secretsmanager.Secret.fromSecretNameV2( + this, "PhonePassword", "door-unlock-api/phone-password" + ); + + const pollerHandler = new lambda.Function(this, "LockdownPoller", { + functionName: "door-unlock-api-lockdown-poller", + runtime: lambda.Runtime.NODEJS_22_X, + architecture: lambda.Architecture.ARM_64, + handler: "lockdown-poller.handler", + code: lambda.Code.fromAsset(path.join(__dirname, "../lambda/poller"), { + bundling: { + image: lambda.Runtime.NODEJS_22_X.bundlingImage, + local: { + tryBundle(outputDir: string) { + const { execSync } = require("child_process"); + execSync( + `esbuild ${path.join(__dirname, "../lambda/poller/lockdown-poller.ts")} --bundle --platform=node --target=node22 --outfile=${path.join(outputDir, "lockdown-poller.js")} --external:@aws-sdk/*` + ); + return true; + }, + }, + }, + }), + environment: { + ELEMENTS_API_KEY_PARAM: "/seahaven/door-unlock/elements-api-key", + PHONE_IPS_PARAM: "/seahaven/door-unlock/phone-ips", + PHONE_PASSWORD_SECRET: "door-unlock-api/phone-password", + }, + vpc, + vpcSubnets: { subnets: [privateSubnet1, privateSubnet2] }, + securityGroups: [pollerSg], + timeout: cdk.Duration.seconds(75), + memorySize: 128, + logRetention: logs.RetentionDays.TWO_MONTHS, + }); + + elementsApiKeyParam.grantRead(pollerHandler); + phoneIpsParam.grantRead(pollerHandler); + phonePasswordSecret.grantRead(pollerHandler); + + new events.Rule(this, "LockdownPollerSchedule", { + ruleName: "door-unlock-api-lockdown-poller-schedule", + schedule: events.Schedule.rate(cdk.Duration.minutes(1)), + targets: [new targets.LambdaFunction(pollerHandler)], + }); + const httpApi = new apigwv2.HttpApi(this, "DoorUnlockApi", { apiName: "door-unlock-api", }); diff --git a/yealinkT58W-door-unlock.ph.xml b/yealinkT58W-door-unlock.ph.xml index f71b776..698d4d9 100644 --- a/yealinkT58W-door-unlock.ph.xml +++ b/yealinkT58W-door-unlock.ph.xml @@ -897,7 +897,7 @@ voice.headset_send = #$call_id--The caller ID when in the incoming state, the outgoing state or during conversation. #For example, action_url.log_on = http://192.168.1.20/help.xml?mac=$mac -action_url.setup_completed = https://doorunlock.seahaven.com/lockdown/status?token=__DOOR_UNLOCK_TOKEN__ +action_url.setup_completed = action_url.registered = action_url.unregistered = action_url.register_failed = @@ -979,7 +979,7 @@ zero_touch.network_fail_delay_times = ## Push XML ## ####################################################################################### -push_xml.server = +push_xml.server = any #Enable or disable the phone to display the push XML interface when receiving an incoming call; 0-Disabled (default), 1-Enabled; push_xml.block_in_calling = 0