Skip to main content

Infrastructure

Four AWS CDK v2 stacks (bin/app.ts in cse-http-be), named cse-http-be-<stage>-<component>, region us-east-1. All four were deployed to the dev stage on 2026-09-17 (account 574317420690). No prod stack exists. See Intro for what "deployed" does and doesn't mean yet.

Stack name (dev)ClassStateful?
cse-http-be-dev-dataDataStack (lib/data-stack.ts)Yes, RETAIN
cse-http-be-dev-authAuthStack (lib/auth-stack.ts)Yes, RETAIN
cse-http-be-dev-apiApiStack (lib/api-stack.ts)No, safe to destroy and redeploy
cse-http-be-dev-observabilityObservabilityStack (lib/observability-stack.ts)No

Every resource carries four cost-allocation tags: Project=cse-http-be, Environment=<stage>, Component=management-api, ManagedBy=cdk. A tag key only appears in the Billing console's activation list after AWS has seen it on a resource: deploy, wait up to 24 h, activate the keys, then wait again for cost data.

Deployed dev resource IDs​

ResourceValue
Cognito User Pool IDus-east-1_L8woOafje
App client — flutter-app-default2ccs07cj0be3sedqne7v4m6ud1
App client — flutter-app-remembered3u6cc24r46e8llhtu1mhqaa19k
App client — server-admin372s6dl49t4o3ujh9gtt9hl3qk
HTTP API base URLhttps://inv-api.crownsolarenergy.com (from the next deploy). The old https://jaqui4ocdf.execute-api.us-east-1.amazonaws.com URL is disabled (owner, 2026-12-03) and answers 403
HTTP API custom domainhttps://inv-api.crownsolarenergy.com — configured 2026-12-02 (apiDomainName in cdk.json), not deployed yet: works once the steps in Operations → API custom domain are done. The only working URL: the execute-api URL is disabled (disableExecuteApiEndpoint) whenever apiDomainName is set
DynamoDB tablecse-http-be-dev-main
Alert SNS topiccse-http-be-dev-alerts

All of these are public identifiers. None is a credential, and none of the app clients has a secret. See Authentication for how the FE team uses them.

CDK stacks​

DataStack — STATEFUL, RETAIN​

One DynamoDB table:

PropertyValueWhy
Namecse-http-be-<stage>-main
KeysPK (S) / SK (S)Single-table design
GSIGSI1: GSI1PK / GSI1SK, projection ALLOne generic inverted index for serial lookup and members-of-plant
GSI (deployed)GSI2: GSI2PK / GSI2SK, projection ALL (FR-022, T002-069/070)Sparse collection index ("all X of org O ordered by S"). Deployed and ACTIVE on dev
GSI (deployed)GSI3: GSI3PK / GSI3SK, projection ALL (FR-022, T002-071/134)Sparse facet index ("X of org O with facet F=v"). Deployed to dev on 2026-10-13 (T002-134, data stack alone); packages/api/test/infra/data-stack.test.ts asserts exactly 3 GSIs
BillingOn-demand (PAY_PER_REQUEST)No capacity planning until real traffic data exists
EncryptionAWS-managed keyFree. A customer-managed KMS key would add $1/month plus per-request charges
TTL attributettl (epoch seconds)Only one TTL attribute is allowed per table. Used today by the OTP throttle item
StreamNEW_AND_OLD_IMAGESEnabled up front for future outbox/audit consumers. Nothing consumes it yet
PITRprod onlyNo dev data worth recovering (~$0.20/GB-month)
Removal policyRETAINcdk destroy orphans the table, never deletes it
Deletion protectionprod onlyIn dev, deletion protection would make cdk destroy fail instead of orphaning

Outputs: TableName, TableStreamArn. SSM parameter: /cse-http-be/<stage>/table-name.

GSI2 → GSI3 rollout (FR-022, research R11) — complete​

CloudFormation allows only one GSI change per UpdateTable, so GSI2 and GSI3 are two separate, sequential deploys of the same stack (cse-http-be-<stage>-data), never combined in one update. As of 2026-10-13:

StepState
GSI2 authored in lib/data-stack.ts (T002-069)Done
GSI2 deployed (T002-070, human-run)Done — ACTIVE on dev
GSI3 authored in lib/data-stack.ts (T002-071)Done (2026-10-13) — the infra test pins the template at exactly 3 GSIs
GSI3 deployed (T002-134, human-run)Done (2026-10-13)

The rollout is complete. Routes whose only dev failure was the missing GSI3 are expected to work now, not yet re-verified on dev: GET /v1/orgs/{orgId}/customers (the default status=ACTIVE path), partner lists filtered by relationship/status, member lists filtered by a single status, and the web plant list's created-order/lifecycle path (packages/core/src/plants/list-paths.ts).

Any future index needs its own separate deploy of the data stack alone — never cdk deploy --all, never combined with another GSI change:

npx cdk deploy cse-http-be-dev-data -c stage=dev

No backfill runs for either index: existing items carry no GSI2*/GSI3* attributes, and both are sparse, so they cost nothing until a later feature's writer starts populating them on write.

The key schema is the most irreversible part of the project. Adding a GSI later is an online backfill, and CloudFormation allows only one GSI change per UpdateTable. New access patterns should reuse GSI1.

AuthStack — STATEFUL, RETAIN​

A Cognito user pool can't be moved between accounts, and its sign-in attributes can't change after creation. A destroy-and-redeploy would mint a new pool with a new ID and new JWKS, invalidating every issued token. So the pool is RETAIN, with a fixed name cse-http-be-<stage>, plus deletion protection in prod.

User pool (UserPool):

SettingValue
Feature planLITE. The default is ESSENTIALS; the difference is ~$6,055/month at 600k MAU. Never enable Managed Login
Self sign-upEnabled
Sign-in (username attributes)email, phone, case-insensitive. Immutable after creation
Auto-verifyemail only
Standard attributesemail (required, mutable), phone_number (required, mutable), name (optional, mutable)
Custom attributecustom:terms_accepted_at (string, immutable)
Password policyMin 10 chars, upper + lower + digit, no symbol required. Temporary passwords valid 3 days
MFAOptional, TOTP only (sms: false)
SMS roleDisabled (enableSmsRole: false). The OTP SMS is sent by CreateAuthChallengeFn through SNS directly. A Cognito SMS config without SMS MFA is rejected at creation
Account recoveryEmail only
Email senderCognito's built-in sender (~50/day). Not SES: SES is still sandboxed

App clients (all public, none has a secret):

ClientAuth flowsAccess/ID tokenRefresh tokenUsed by
flutter-app-defaultUSER_SRP_AUTH, CUSTOM_AUTH1 h1 dayFlutter, "keep me signed in" off
flutter-app-rememberedUSER_SRP_AUTH, CUSTOM_AUTH1 h90 daysFlutter, "keep me signed in" on (pre-ticked in the app)
server-adminADMIN_USER_PASSWORD_AUTH1 h1 dayCI/support tooling. Accepted by the API authorizer in dev only (KI-18 fixed, T002-048); rejected in prod and every other stage
web-consoleUSER_SRP_AUTH only1 h1 day (24 h, same as flutter-app-default, 2026-11-12)The planned web admin console (ADR 0009). Accepted by the API authorizer in every stage (T002-058) — see below

All four set preventUserExistenceErrors: true and enableTokenRevocation: true. The mobile clients and web-console declare OAuth scopes openid, email, profile, but no hosted UI or domain is configured for any of them.

web-console (T002-057, lib/auth-stack.ts). A fourth, public app client (no secret — a browser SPA can't protect one any better than a distributed APK can), SRP-only like the mobile clients: no custom-auth (email OTP) and no ADMIN_USER_PASSWORD_AUTH. Its id is published the same way as the others — StringParameter at /cse-http-be/<stage>/web-client-id and a WebClientId stack output.

Now wired into the API (T002-058, lib/api-stack.ts). webClient is added to the authorizer's userPoolClients audience in every stage — unlike server-admin, the web console is a real, always-on surface, not a dev-only convenience. ApiStack also gained CORS support purely for this client's browser callers; see CORS below. No real dev client id has been captured for it yet (code/synth-verified only, not confirmed against a live deploy as of this writing).

Lambda triggers (all created with ApiFunction):

TriggerFunctionHandler entryEnvExtra permissions
PostConfirmationPostConfirmationFnpost-confirmationTABLE_NAMETable read + write
DefineAuthChallengeDefineAuthChallengeFndefine-auth-challenge—None (pure logic)
CreateAuthChallengeCreateAuthChallengeFncreate-auth-challengeTABLE_NAME, OTP_SENDER_EMAIL / OTP_SES_CONFIGURATION_SET (only when -c otpSenderEmail / -c otpSesConfigurationSet are set)Table read/write (OTP throttle); with otpSenderEmail, ses:SendEmail on the sender's address identity, its domain identity and the configuration set (if any), conditioned on ses:FromAddress = the sender. No SNS / SMS
VerifyAuthChallengeResponseVerifyAuthChallengeFnverify-auth-challenge—None

SSM parameters (standard tier, free): /cse-http-be/<stage>/user-pool-id, /mobile-client-default-id, /mobile-client-remembered-id, /server-client-id, /web-client-id.

Outputs: UserPoolId, MobileClientDefaultId, MobileClientRememberedId, ServerClientId, WebClientId.

Realtime ticket signing key (feature 003, A10/A11, ADR 0003) — opt-in, absent by default. Only created when -c realtimeTicketsEnabled=true: a KMS asymmetric key (Key, keySpec: ECC_NIST_P256, keyUsage: SIGN_VERIFY, enableKeyRotation: false — KMS cannot auto-rotate an asymmetric key's material; "rotation" here means minting a whole new key via the manual runbook below), logical id RealtimeTicketKey<generation> where <generation> comes from -c realtimeKeyGeneration=N (default 1). Both the key and its alias (cse-http-be-<stage>-realtime-ticket-gen<generation>) are RemovalPolicy.RETAIN. An additional SSM parameter, /cse-http-be/<stage>/realtime-ticket-key-arn, always points at whichever generation is currently active (plain in-place update, never a replace) — distinct from the key/alias above, which are generation-specific. Outputs: RealtimeTicketKeyArn, RealtimeTicketKeyGeneration. Only the realtime family function is granted kms:Sign (and kms:GetPublicKey) on this key. Full rotation runbook: Operations → Realtime ticket signing key rotation.

ApiStack — STATELESS​

  • HTTP API v2 named cse-http-be-<stage>, with the $default auto-deploy stage. That means no stage prefix in URLs: a named stage would produce /<stage>/..., which breaks a CloudFront origin pointed at the bare hostname.
  • CORS (FR-034/FR-035, T002-058), configured for web-console's browser callers only — native Flutter doesn't need it and nothing here changes Flutter's requests. HttpApi's corsPreflight:
    • allowOrigins come from CDK context webOrigins (-c webOrigins=https://a,https://b, comma-separated, or a JSON array). dev defaults to http://localhost:5173 when the context is omitted. Every other stage throws at cdk synth if webOrigins resolves to an empty list, and '*' is rejected in every stage (CLAUDE.md Hard Rules: an open CORS policy plus bearer tokens is a real exposure, not a cost guardrail).
    • allowMethods: GET, POST, PUT, PATCH, DELETE, OPTIONS.
    • allowHeaders: Authorization, Content-Type, Idempotency-Key, If-Match, If-None-Match, X-Org-Id, X-Correlation-Id.
    • exposeHeaders: ETag, X-Request-Id, X-Correlation-Id, Idempotent-Replayed, Retry-After, Location.
    • allowCredentials: false — the console authenticates via the Authorization header, not cookies.
    • maxAge: Duration.seconds(7_200) (2 h preflight cache).
  • HttpUserPoolAuthorizer (CognitoAuthorizer, JWT type, identity source $request.header.Authorization). The issuer is the user pool. The audience is flutter-app-default, flutter-app-remembered and web-console in every stage (T002-058), plus server-admin only when props.stage === 'dev' (lib/api-stack.ts, KI-18 fixed by T002-048) — a server-admin token is never accepted in prod or any other stage, since trusting a password-based, non-SRP client in production would be a deliberate security decision nobody has made. It's attached per route, since a new HTTP API route defaults to open.
  • Stage throttling (FR-037, T002-059), CfnStage (the HttpApi L2 doesn't expose this):
    • Default: throttlingRateLimit 50 req/s, throttlingBurstLimit 100, applied via defaultRouteSettings. Context-tunable without a code change: -c throttleRateLimit=… -c throttleBurstLimit=…. This sits in front of the account's Lambda concurrency quota (1000, L-B99A9384, shared with live TCP ingest) as the first line of defence against exhausting it.
    • Per-route overrides: RouteDef.throttle ({ rate, burst } in lib/routes.ts), applied via CfnStage.routeSettings keyed by "METHOD /path". No route sets one today — every route runs at the 50/100 default.
  • One Lambda per route family, not per route (CR-1). ApiStack reads lib/routes.ts, the only route table (CR-14: no package adds a route directly in api-stack.ts), groups its RouteDefs by family, and creates one ApiFunction per family. Every route of the family points at that function's integration, and the function dispatches on event.routeKey inside packages/api (http/router.ts, familyHandler). Per-operation handler files are unchanged; handlers/families/<family>.ts is only the router. One Lambda per route at ~150 planned operations would push the stack past CloudFormation's 500-resource limit.
Family functionRoutesFamily entryDynamoDB grant (union of the family's routes)
meFnGET /v1/me, PUT /v1/me/selected-plant, GET /v1/me/context (A03, feature 003)families/meRead/write
plantsFnGET /v1/plants, POST /v1/plants, GET /v1/plants/{plantId}, PATCH /v1/plants/{plantId}, DELETE /v1/plants/{plantId}, GET /v1/plants/{plantId}/devices, POST /v1/plants/{plantId}/devicesfamilies/plantsRead/write (CreatePlant, UpdatePlant, DeletePlant and ClaimDevice write; DeletePlant also uses BatchWriteItem, covered by the same read/write grant)
discoveryFnGET /v1/lookup, GET /v1/search/suggestions, GET /v1/catalog/{name}families/discoveryRead
membersFn (feature 003, 20 routes — the largest family)GET/PATCH /v1/orgs/{orgId} (B01), GET /v1/orgs/{orgId}/members… (B02–B06, including the :suspend|:restore|:end-sessions|:reset-mfa|:remove colon-verb route and :bulk-assign-scope, B07), GET/POST/PATCH/DELETE /v1/orgs/{orgId}/roles… (B08), GET /v1/orgs/{orgId}/scopes/summary (B10), GET/POST/PATCH/DELETE /v1/orgs/{orgId}/departments… (B09)families/membersRead/write
invitationsFnPOST/GET /v1/orgs/{orgId}/invitations, POST /v1/orgs/{orgId}/invitations/{inviteId} (:resend), DELETE /v1/orgs/{orgId}/invitations/{inviteId} (B11)families/invitationsRead/write
invitation-acceptFnPOST /v1/invitations (public URL shorthand :accept, B12)families/invitation-acceptRead/write
sharesFnGET/POST /v1/orgs/{orgId}/shares, PATCH /v1/orgs/{orgId}/shares/{shareId} (B13; DELETE removed 2026-11-27, ADR 0035)families/sharesRead/write
realtimeFnPOST /v1/realtime/tickets (A10), GET /v1/realtime/jwks (A11, public)families/realtimeRead (plus kms:Sign/kms:GetPublicKey, only when realtimeTicketsEnabled)
access-logFnGET /v1/orgs/{orgId}/access-log (B14)families/access-logRead
access-requestsFnPOST /v1/plants/{plantId}/access-requests, GET /v1/orgs/{orgId}/access-requests, POST /v1/orgs/{orgId}/access-requests/{requestId} (:approve|:reject, B15)families/access-requestsRead/write

The grant is the union: a family gets grantReadWriteData if any of its routes is marked write or has idempotency !== 'none' (T002-054) — even a read-only route's idempotency record (IDEM#<sub>) needs a conditional PutItem/UpdateItem, so write and idempotency are independent triggers for the same write grant. No route is required/ optional yet (every RouteDef.idempotency in lib/routes.ts is 'none'), so this doesn't currently widen either family's grant beyond what write alone would give it — see API overview → Idempotency for the feature itself. This is coarser than the per-route grants of the original seven functions, so plantsFn can also write on the read-only routes. Per-operation access control is enforced in code, not IAM.

meFn's extra Cognito grant (T002-039). meFn alone also gets USER_POOL_ID and SERVER_CLIENT_ID (both public, non-secret identifiers — a pool id and a public app client id, not a credential) in its environment, and an IAM policy statement granting cognito-idp:AdminGetUser scoped to props.userPool.userPoolArn (this one pool only). It's used by IdentityProvider.getUserEmail(sub) to resolve or repair email when the caller's bearer token has no email claim (an AccessToken call) — see GET /v1/me. SERVER_CLIENT_ID is unused by that call (AdminGetUser needs only the pool id) but CognitoIdentityProvider's constructor requires a client id, so it's passed regardless. ApiStack now takes serverClient as a required prop (lib/api-stack.ts), sourced from AuthStack.serverClient in bin/app.ts. No other family function gets a Cognito grant.

Per-routeKey config. Each RouteDef also carries strict, idempotency (required / optional / none), versioned, write and optional actions. ApiStack serialises them, keyed by routeKey ("METHOD /path"), into the family function's ROUTE_CONFIG environment variable (JSON). The family entry parses it once at cold start and hands it to familyHandler. The seven current routes are all strict: false (lenient, CR-13: the shipped APK sends any Content-Type, unknown query params are ignored, a malformed cursor restarts), idempotency: none, not versioned. A separate, optional throttle field ({ rate, burst }) is read directly off RouteDef by ApiStack itself (not serialised into ROUTE_CONFIG, since it's an API Gateway stage setting, not something the Lambda needs at runtime) — see Stage throttling above. No route sets it yet.

Colon-verb routes. API Gateway path variables must fill a whole path segment, so {id}:assign can't be a route template. A route with actions is declared as POST /v1/<resource>/{id}, and the family router splits the <id>:<verb> path parameter. See API overview. A synth-only probe (packages/api/test/infra/colon-probe.test.ts) asserts the synthesised template never contains a colon-in-template route. No colon-verb route exists yet.

Authorizer. Still attached per route in the same loop. A route is left open only if its public flag is set and its id is in PUBLIC_ROUTE_ALLOWLIST (empty today).

Verification is synth-only. packages/api/test/infra/api-stack-size.test.ts synthesises ApiStack offline and guards resource growth and bundle size; nothing in the test suite deploys.

Resource cap and route-area stacks (Q27, 2026-10-22). The size test's projected cap (API_STACK_RESOURCE_CAP in lib/route-area-stack.ts) was raised from 400 to 450 as a stopgap; CloudFormation's hard limit is 500. The longer-term mechanism: a RouteDef in lib/routes.ts may carry an optional area (service, notify, reports-settings, reports, account; the former devices-ops area was removed by ADR 0012 phase 2). Each area with routes becomes its own stack cse-http-be-<stage>-api-<area> (RouteAreaStack), which builds that area's families (via the shared lib/route-family.ts) and attaches them to ApiStack's HttpApi and Cognito authorizer. ApiStack publishes the ids to SSM at /cse-http-be/<stage>/api/http-api-id and /cse-http-be/<stage>/api/authorizer-id, only when some area has routes; area stacks resolve them at deploy time and declare a dependency on ApiStack. Synth fails on an area value that does not match the stack, a family split across areas, or a route that sets throttle in an area stack. Covered by packages/api/test/infra/route-area-stack.test.ts.

:::note First area: service (feature 006) 31 of the feature-006 routes (E01–E13) set area: 'service', so synth now produces cse-http-be-<stage>-api-service with five families: work-orders (12 routes, the only one with the service-files S3 grant), service-roster (8), maintenance-plans (7), plant-service (3) and maintenance-history (1). The four E07 bulk verbs (POST /v1/work-orders:bulk-*) are not in this stack: they stay in ApiStack's plants-write function via POST /v1/{collection} (CR-2). ApiStack therefore now publishes the two SSM parameters above. Not deployed yet — the owner's next deploy creates the stack. The former devices-ops area (stack cse-http-be-<stage>-api-devices-ops, the 21 feature-007 routes and the always-on command sweep) is gone — ADR 0012 phase 2 unregistered those routes, so synth no longer produces that stack; the notify area holds the nine feature-008 routes in four functions (push-tokens, notification-rules, notification-settings, alert-work-orders; stack cse-http-be-<stage>-api-notify, not deployed yet — G03 stays in ApiStack via POST /v1/{collection}); the reports-settings area has no routes yet and synthesizes nothing. :::

:::caution Deployed dev still has the old shape The dev stack deployed on 2026-09-17 has seven per-route functions (GetMeFn, ListPlantsFn, and so on). The family-dispatch code is in the repo and synthesises, but has not been deployed. The two tables above and the counts below describe the code. The next deploy:dev replaces the seven functions with meFn and plantsFn. Function names, log groups and per-function logs change with it. :::

grantReadData / grantReadWriteData (called in ApiStack, not in ApiFunction) cover both the table ARN and table/<name>/index/*. A hand-written policy that omits the index ARN makes GSI queries fail with AccessDenied while base-table reads keep working.

  • Stage access logging to a dedicated LogGroup (14 days; RETAIN in prod, DESTROY otherwise). It's set through the CfnStage escape hatch, because the HttpApi L2 doesn't expose it. One JSON line per request:
{
"requestId": "$context.requestId",
"routeKey": "$context.routeKey",
"status": "$context.status",
"integrationStatus": "$context.integrationStatus",
"integrationErrorMessage": "$context.integrationErrorMessage",
"authorizerError": "$context.authorizer.error",
"responseLatency": "$context.responseLatency",
"integrationLatency": "$context.integrationLatency",
"sourceIp": "$context.identity.sourceIp",
"userAgent": "$context.identity.userAgent"
}

DetailedMetricsEnabled is deliberately off. It bills per-route metrics as custom metrics ($0.30 each per month).

Output: ApiUrl (the apiEndpoint).

ObservabilityStack — STATELESS​

Alert topic: SNS cse-http-be-<stage>-alerts. If -c alertEmail=... is set at deploy time, that address is subscribed. The subscription stays PendingConfirmation until someone clicks the emailed link, while CloudFormation already reports CREATE_COMPLETE, so a green stack can have a mute alert channel. The topic policy lets budgets.amazonaws.com publish.

Alarms (all >= threshold, missing data = not breaching, action → alert topic). The first six are always present; BacklogAge (T002-093, FR-049, merged by Q12) exists only when ObservabilityStack is given integration refs — bin/app.ts only passes them when -c busEnabled=true (same opt-in as IntegrationStack itself). There is no DLQ alarm: DlqDepth was dropped by owner decision 2026-10-27 to stay within the CloudWatch free tier; DLQs are checked by hand (runbook). IntegrationStack no longer exports the DLQ names — if a bus-on ObservabilityStack is already deployed, deploy it first or deploy --all can fail with "export in use".

Alarm nameMetricScopePeriodThreshold
cse-http-be-<stage>-LambdaThrottlesAWS/Lambda Throttles SumAccount-wide, no dimension. Includes the live TCP Server's functions1 min≥ 1
cse-http-be-<stage>-LambdaErrorsAWS/Lambda Errors SumAccount-wide. Includes TCP Server functions5 min≥ 1
cse-http-be-<stage>-Api5xxAWS/ApiGateway 5xx SumThis API (ApiId)5 min≥ 1
cse-http-be-<stage>-DynamoThrottlesAWS/DynamoDB ThrottledRequests SumThis table5 min≥ 1
cse-http-be-<stage>-PlantDeletionOverdueCseHttpBe/<stage> PlantDeletionOverdue (Sum), no dimensions (namespace carries the stage)This service's own custom metric (004, FR-041) — emitted by the hourly plant-deletion-sweep Lambda (EventBridge Scheduler, only when busEnabled=true)5 min≥ 1
cse-http-be-<stage>-BacklogAgemetric math MAX([…]), seconds: stream-router IteratorAge/1000, from-tcp and alert-events ApproximateAgeOfOldestMessage, notify-recompute oldest message/3busEnabled only5 min> 300

The thresholds are absolute counts, not rates, on purpose. At near-zero dev traffic a rate alarm sits in INSUFFICIENT_DATA forever. Switch to rate-based math alarms once there's real traffic. Because the two Lambda alarms are account-wide, they also fire for errors or throttles in the TCP Server's functions. LambdaThrottles is the most important alarm here: the concurrency quota (1000) is shared with live inverter ingest.

BacklogAge is created together with IntegrationStack itself, i.e. only with -c busEnabled=true (CR-21/B-01). Renamed, T002-148: this single flag (was two: withIntegration created the stack shell, busEnabled separately enabled the event-source mappings inside it) now does both — the stack and its live mappings appear in the same deploy, so there's no longer an intermediate "stack exists, mappings disabled" state. Until a human passes it, these sit entirely absent rather than NOT_BREACHING. See Operations → Alarms runbook for what each one means and the first response.

Budgets (the first two per account are free):

BudgetTypeLimitNotifications
cse-http-be-<stage>-actualMonthly cost, actual$50> 50 % and > 100 %
cse-http-be-<stage>-forecastMonthly cost, forecast$200> 100 %

Subscribers are the alert topic, plus the alertEmail address directly if one is set. Budgets evaluate billing data that lags 8–24 h. They're a same-day tripwire; the alarms give minute-level coverage.

The budgets are account-wide, so they also include the TCP Server's spend.

Output: AlertTopicArn.

IntegrationStack — STATELESS, AUTHORED, NOT DEPLOYED​

lib/integration-stack.ts (T002-085; ADR 0005; research R15). bin/app.ts only instantiates it when CDK context busEnabled=true is passed — a plain cdk deploy --all (or npm run deploy:dev) never creates it, and the dev account has no cse-http-be-dev-integration stack today. Its deploy is a separate human step (npx cdk deploy cse-http-be-<stage>-integration -c stage=<stage> -c busEnabled=true, never --all) — see Operations → Deployment process. Renamed, T002-148 (CR-26): this flag was withIntegration, and used to only create the stack shell with its event-source mappings still disabled (a separate busEnabled flag flipped those on in a second deploy). Now busEnabled alone does both — creates the stack and enables every mapping in it — in one deploy.

This is the integration bus to/from the TCP Server (blueprint 05 §3):

ResourceDetail
SNS FIFO topic cse-http-be-<stage>-to-tcp.fifocontentBasedDeduplication: false (envelope ids are already unique ULIDs — R15). Topic policy allows sns:Subscribe only to the TCP account's principal, conditioned on sns:Protocol = sqs and sns:Endpoint matching cse-tcp-be-<stage>-*
SQS from-tcp + DLQStandard, SSE (SQS-managed key), visibility 60 s, retention 4 d; DLQ retention 14 d, maxReceiveCount 5
SQS alert-events + DLQSame shape as from-tcp. The alert-events consumer logic (notifier) belongs to a later feature (008) — this stack only creates the queue/DLQ
SQS plant-jobs + DLQcse-http-be-<stage>-plant-jobs, DLQ maxReceiveCount 3 (004 bulk plant jobs, FR-035). Consumed by PlantJobsWorkerFn (plant-jobs-worker, 120 s timeout): SqsEventSource batch 1, maxConcurrency 2, partial batch responses, enabled: busEnabled. Granted table read/write. Output PlantJobsQueueUrl; its DLQ has no alarm (checked by hand)
stream-router LambdaApiFunction, 30 s timeout. DynamoEventSource on the table stream: batch 100, window 1 s, LATEST, parallelizationFactor: 1, bisectBatchOnError: false, retry 10, max record age 6 h, partial batch responses (reportBatchItemFailures), SqsDlq on failure, filter criteria dropping TTL-driven removes and non-META/non-OUTBOX# records. Granted table read/write and sns:Publish on the topic — the only function with publish rights (R15)
tcp-events LambdaOne ApiFunction with two SqsEventSources (from-tcp, alert-events), batch 10 each, maxConcurrency: 2 each (SQS's own minimum), partial batch responses. One consumer dispatches both queues by envelope type (CR-21) — it never knows which queue delivered a given message. The feature-005 device events (inbound device.observed.v1, device.binding.result.v1, device.erasure.completed.v1, command.status.v1; outbound device.upserted.v1, device.removed.v1, command.requested.v1, command.cancelled.v1) are removed (ADR 0012) from the SNS allowlist, the from-tcp filter and this dispatcher; devices and commands belong to the TCP server. Granted table read/write
plant-deletion-sweep Lambda + hourly schedule (T004-714, FR-041)ApiFunction (arm64, 256 MB, 60 s, 14-day log group, no reserved concurrency) invoked by an EventBridge Scheduler schedule cse-http-be-<stage>-plant-deletion-sweep, rate(1 hour), no retries. It Queries the PLANTDELETIONS partition (no Scan), counts pending-deletion markers older than 24 h and emits the dimension-less PlantDeletionOverdue metric. Granted table read only, plus cloudwatch:PutMetricData restricted to the CseHttpBe/<stage> namespace (the metric is actually written as an EMF log line). Exists only with -c busEnabled=true, like the rest of this stack
SQS device-import-jobs + DLQ, device-import-workerRemoved (ADR 0012) — never deployed; the DeviceImportDlqDepth alarm went with it
device-registry-sweeper Lambda + hourly ruleRemoved (ADR 0012) — never deployed; the DeviceRemovalStuck metric and alarm went with it
SNS subscriptions (from-tcp, alert-events)Created only when context tcpEventsTopicArn is set (absent means TCP hasn't created its topic yet — this stack still creates the queues/DLQs, just skips subscribing them). Raw message delivery, payload-based filter policies (FilterPolicyScope: MessageBody) on type so TCP never has to add message attributes

Context keys (CDK -c, none are secrets):

KeyDefaultEffect
busEnabledfalse, every stageRead twice: by bin/app.ts to decide whether IntegrationStack is instantiated at all, and by IntegrationStack itself (same context value, inherited down the construct tree) to set enabled: busEnabled on every event-source mapping above (stream-router's DynamoEventSource, both tcp-events SqsEventSources). false (the default) means the stack doesn't exist at all. true creates it with the Lambdas, queues and topic fully IAM-wired and live-invoking from the first deploy — B-01 (L-B99A9384, quota 10 → 1000) is closed, so this is purely a human deploy decision. A human flips it with -c busEnabled=true at deploy time; the code never does
tcpAccountIdthe current account (Stack.of(this).account)The account whose principal may subscribe to the topic. Only needs overriding if TCP is ever deployed to a different account than this standalone one (CLAUDE.md: not currently the case)
tcpEventsTopicArnunsetTCP's own inbound topic ARN. Present → this stack's queues subscribe to it (with the filter policies above). Absent → queues/DLQs still exist, subscription is skipped. Dev: arn:aws:sns:us-east-1:574317420690:cse-tcp-be-dev-events, set in cdk.json context.stages.dev (2026-11-04; the subscription was first deployed that day with -c). The from-tcp filter allows report.render.status.v1, plant.erasure.completed.v1, notify.endpoint.invalid.v1 and device.binding.changed.v1 (ADR 0018)

Outputs: ToTcpTopicArn, FromTcpQueueUrl, AlertEventsQueueUrl, BusEnabled (echoes the resolved busEnabled value for a quick post-deploy check).

EdgeStack — STATELESS, AUTHORED, NOT DEPLOYED​

lib/edge-stack.ts (T002-060; FR-036). Same opt-in pattern as IntegrationStack: bin/app.ts only instantiates it with CDK context edgeEnabled=true, and its deploy is a separate human step (npx cdk deploy cse-http-be-<stage>-edge -c stage=<stage> -c edgeEnabled=true, never --all) — CloudFront + WAF are real recurring cost and a real public surface. Renamed, T002-148 (CR-26): this flag was withEdge — same gate, name only.

CloudFront in front of the HTTP API — this is a control-plane API, not a CDN target, so every response is per-caller:

SettingValueWhy
Cache policyCACHING_DISABLEDNothing here should ever be cached at the edge
Origin request policyALL_VIEWER_EXCEPT_HOST_HEADERForwards everything API Gateway needs (headers, cookies, query strings), minus the Host header execute-api needs to resolve its own stage
Response headers policyHSTS (max-age 365 d, includeSubDomains), X-Content-Type-Options: nosniff, Referrer-Policy: no-referrer, X-Frame-Options: DENY, default Cache-Control: no-store (a route's own value still wins)Standard edge security headers (FR-036)
HTTP versionHTTP/2 and HTTP/3
Price classPRICE_CLASS_200 (North America + Europe + Asia)No need for the full (priciest) class for an admin/mobile API
WAF Web ACLOne rate-based rule, RateLimitPerIp: 1,000 requests per 5-minute window per IP, action block (WAF's rate-based rules always evaluate over a fixed 5-minute window)Edge-level abuse protection ahead of the API Gateway stage throttle

SSM parameter: /cse-http-be/<stage>/api-cdn-url (the distribution's https://<domain> URL). Output: ApiCdnUrl.

AssetsStack — STATEFUL, RETAIN, deployed to dev 2026-11-26​

cse-http-be-dev-assets, in its own CDK app (bin/assets.ts), so npm run deploy:dev (--all on bin/app.ts) never includes it. Deployed only with npm run deploy:assets.

  • Private S3 bucket (Block Public Access, bucket-owner-enforced, SSE-S3, TLS-only policy, versioned with 30-day non-current expiry, RETAIN).
  • CloudFront distribution (RETAIN, PriceClass_100, HTTP/2+3) reading the bucket through an Origin Access Control that signs every origin request with SigV4; HTTPS-only viewers, GET/HEAD, CORS * + security headers.
  • BucketDeployment uploads assets/ with prune: false and retainOnDelete: true and invalidates /*. Its CDK-managed upload Lambda is a custom-resource handler (not an ApiFunction), with its own 14-day log group.
  • Outputs: AssetsBaseUrl, AssetsBucketName, AssetsDistributionId. Deployed dev values: base URL https://d3syd906e6xgu5.cloudfront.net, distribution E3GORJE21CSWMC, bucket cse-http-be-dev-assets-assetsbucket5cb76180-739d0mbemaed.
  • Verified 2026-11-26 against dev: all 38 URLs return 200, HTTP redirects 301 to HTTPS, a direct S3 object URL returns 403.

Gallery, URL rules and cost: Static assets.

Audit wave 1 infrastructure changes (2026-10-27)​

Per-stage context. Non-secret deploy context lives in cdk.json under context.stages.<stage>. Precedence: CLI -c > stages.<stage> > the stack's default. Empty values count as unset, and an unknown key fails synth. Allowed keys (lib/stage-context.ts): tcpRendererRoleArn, reportDispatchQueueArn, reportDispatchPerMinute, reportsGenerateEnabled, tcpEventsTopicArn, busEnabled, realtimeTicketsEnabled, alertEmail, otpSenderEmail, alarmsEnabled, metricsEnabled.

Alarms and metrics are prod-only by default. alarmsEnabled and metricsEnabled default to true only for stage=prod. Account total with prod and busEnabled: 10 standard alarm metrics (no Insights alarm, Q12), and 8 dimensionless custom metric series: AuthzDenied, DependencyUnavailable, OutboxPublishFailed, PlantDeletionOverdue, PlantDeviceReleaseFailed, ReconcileCompleted, ReportsOverdue, TcpEvents. Category, dependency and event type are log fields, not dimensions. In dev, metrics appear only as msg:"metric" log lines.

Budgets filter on the Project=cse-http-be cost-allocation tag. The owner must activate that tag in Billing.

Security hardening: OAuth is disabled on the Cognito clients. AdminGetUser is scoped to the pool. Table grants exclude Scan. CloudFront redirects HTTP to HTTPS (with apiDomainName set the execute-api endpoint is disabled; the edge stack then uses the custom domain as its origin).

Streams and queues: see integration bus.

Lambda functions​

Every Lambda in this repo, route handlers and Cognito triggers alike, is created through one construct, lib/constructs/api-function.ts (ApiFunction, a NodejsFunction subclass). It centralises every default:

SettingValueWhy
Handlerpackages/api/src/handlers/<entry>.ts, export main. Route families use families/<family> as the entry
RuntimeNODEJS_24_XMatches local Node 24 and the account's existing functions
Architecturearm64~20 % cheaper per GB-second
Memory256 MB (overridable, but nothing overrides it)128 MB isn't cheaper for a function that finishes 4× faster
Timeout10 sWell under API Gateway's 30 s integration limit
LoggingJSON format, dedicated LogGroup, 14 days (RETAIN in prod, DESTROY otherwise)The default is never-expire
TracingX-Ray active outside prod, disabled in prod
Reserved concurrencyNever set without owner approvalThe account quota is 1000 (raised from 10), shared with live TCP ingest. Consumers cap themselves with maxConcurrency instead
Provisioned concurrencyNone
Bundlingesbuild, target node24, CJS, minified, source maps, AWS SDK bundled (bundleAwsSDK: true), no external modulesThe runtime's SDK copy pins versions and can lack clients (MODULE_NOT_FOUND)
Lockfile / project rootRepo root package-lock.jsonOtherwise bundling in an npm-workspaces repo falls back to Docker

Environment variables on every function:

VariableValue
STAGECDK stage
LOG_LEVELWARN in prod, INFO otherwise. Read by config.logLevel, but no code uses it to filter logs yet
NODE_OPTIONS--enable-source-maps
AWS_NODEJS_CONNECTION_REUSE_ENABLED1
TABLE_NAMEOnly on functions that touch the table: every route-family function, PostConfirmationFn, CreateAuthChallengeFn
ROUTE_CONFIGFamily functions only: JSON map of routeKey → { write, strict, idempotency, versioned, actions? }, generated from lib/routes.ts
WEB_CONSOLE_CLIENT_IDS (feature 003, T003-140)Every family function, not just members — comma-separated, non-secret Cognito app client ids. Default: the deployed web-console client id; override with -c webConsoleClientIds=id1,id2. See Operations → Environment setup
SESSION_CLIENTS (2026-11-12, not deployed)Every family with an authorized route. JSON { "<appClientId>": { "kind": "WEB"|"MOBILE"|"SERVER", "refreshSeconds": n } } built from lib/auth-stack.ts REFRESH_TOKEN_VALIDITY (web-console 1 d, flutter-app-default 1 d, flutter-app-remembered 90 d, server-admin 1 d). Gives each sign-in record its clientKind and expiresAt. Public client ids only
SESSION_IP_CLIENT_IDS (2026-11-12, not deployed)Every family with an authorized route. Comma-separated app client ids whose X-Forwarded-For first hop is recorded as the user's IP (S-3/S-4). Default: WEB_CONSOLE_CLIENT_IDS plus both Flutter clients (the dev console signs in with them today); override with -c sessionIpClientIds=id1,id2
MFA_ENFORCEMENT (feature 003, T003-140)No effect since 2026-11-11 (two-factor is never required). Every family function — warn (default) or on. Override with -c mfaEnforcement=on, only after the OQ-09 verification procedure. See Authorization → MFA enforcement rollout
USER_POOL_ID (every family with a non-public route, B-4)lib/route-family.ts gives every route family that has at least one authorized route USER_POOL_ID and cognito-idp:AdminGetUser on this user pool only, for the live MFA re-check (refreshMfaMirror → getMfaStatus). Families whose routes are all public get neither
USER_POOL_ID, SERVER_CLIENT_IDmeFn (T002-039) and invitation-acceptFn (FR-044): the pool id and the server-admin app client's id, both public non-secret identifiers, for IdentityProvider.getUserEmail/getUserContact's AdminGetUser call. membersFn gets USER_POOL_ID alone (FR-035, memberAction's :reset-mfa → AdminSetUserMFAPreference)
REALTIME_TICKET_KEY_ARN, REALTIME_TICKET_PREVIOUS_KEY_ARN, REALTIME_WS_URLrealtimeFn only, only when -c realtimeTicketsEnabled=true. See Realtime ticket signing key rotation

In code that's 14 functions in total: 10 route-family functions in ApiStack and 4 triggers in AuthStack. (The deployed dev stack still has 11, with 7 per-route functions in ApiStack — the family-dispatch refactor and every feature-003 family are code/synth-verified only as of this writing, not yet deployed.) Together with the TCP Server's functions, they share the account-wide concurrency pool of 1000 (L-B99A9384, raised from 10).

IntegrationStack adds more functions (stream-router, tcp-events, plant-deletion-sweep, PlantJobsWorkerFn) to that same shared pool once deployed with busEnabled=true. Every SQS mapping caps itself with maxConcurrency: 2 (tcp-events has two mappings, so up to 4); stream-router's DynamoEventSource has no such cap and scales with the table's active shard count. Against a quota of 1000 this is small, but the pool is still shared with live inverter ingest, so busEnabled stays a human, opt-in deploy decision.

Data model​

See Types & schemas → Database entity shapes for every item's keys and attributes. Scan is banned; every access is a targeted GetItem, Query, PutItem, UpdateItem or TransactWriteItems.

Resource dependencies​

DataStack (table)
│
├──▶ AuthStack (table name + grants for PostConfirmationFn, CreateAuthChallengeFn)
│ │
│ ▼
└──▶ ApiStack (table + userPool + both mobile clients + serverClient → family Lambdas + authorizer)
│
▼
ObservabilityStack (api.apiId, table.tableName)

Cross-stack references are weak (@aws-cdk/core:defaultCrossStackReferences: "weak" in cdk.json). They resolve with Fn::GetStackOutput instead of CloudFormation Export/ImportValue, so a producing stack can change an output without an export lock blocking the deploy. The ordering is still enforced by CDK's dependency graph (--all deploys Data → Auth → Api → Observability). Nothing depends on ObservabilityStack.

Current resources (summary)​

ResourceStackStateful?
DynamoDB table (+ GSI1, stream, TTL)DataStackYes (RETAIN)
SSM parameter: table nameDataStackNo
Cognito User PoolAuthStackYes (RETAIN)
4 Cognito app clientsAuthStackYes (part of the pool)
4 Cognito trigger Lambdas + 4 log groupsAuthStackNo
5 SSM parameters (pool ID, 4 client IDs)AuthStackNo
HTTP API v2 + $default stage + JWT authorizerApiStackNo
2 route-family Lambdas + 2 log groups (one per family, CR-1; deployed dev still has 7 per-route Lambdas until redeployed)ApiStackNo
Stage access-log LogGroupApiStackNo
SNS alert topic (+ optional email subscription)ObservabilityStackNo
CloudWatch alarms: 7 on a default synth (all in ObservabilityStack; the cost-gate test asserts ≤ 10); ObservabilityStack has 15 with -c busEnabled=true (21 account-wide with notify 3 + service 1 + reports 2)ObservabilityStackNo
2 AWS BudgetsObservabilityStackNo
SNS FIFO topic, 2 SQS queues + 2 DLQs, stream-router + tcp-events LambdasIntegrationStack — authored, not deployed; created only with -c busEnabled=trueNo
CloudFront distribution, WAF Web ACL, 1 SSM parameterEdgeStack — authored, not deployed; created only with -c edgeEnabled=trueNo

There's no VPC, NAT gateway, EC2, Fargate, SES configuration, Secrets Manager secret, or KMS key in this repo's infrastructure. CloudFront and WAF are authored (EdgeStack) but not deployed in any stage today — see above. Every resource above is either fully managed or serverless.

Cost-gate posture and the unused 004+ flags (T002-148, CR-26)​

Every non-free resource in this repo is behind an explicit CDK context flag, default false in every stage — a plain cdk deploy --all (or npm run deploy:dev) never creates any of them. edgeEnabled and busEnabled (above) are the two flags with a resource to gate today. Three more are declared in bin/app.ts for later features and currently read but unused: realtimeTicketsEnabled (007's KMS ticket-signing key) and reportsEnabled/notificationsEnabled (009's report/notification infra) — declared now so those features read the SAME flag name from day one instead of each inventing its own context key. All five default false.

packages/api/test/infra/cost-gates.test.ts enforces this as a synth assertion, not just a convention: building the full stack graph with no context flags passed asserts EdgeStack/IntegrationStack don't exist, no AWS::CloudFront::Distribution, AWS::WAFv2::WebACL or AWS::SQS::Queue resource exists anywhere in the graph (one AWS::SNS::Topic only — the always-on alert topic), at most 10 AWS::CloudWatch::Alarm resources exist, and the whole service's putMetric() call sites use at most 10 distinct custom EMF metric names (FR-048, $0.30/metric/month). A second set of assertions in the same file confirms edgeEnabled=true/busEnabled=true each still create their resource when explicitly passed.

Service / O&M resources (feature 006)​

:::warning Partly built, nothing deployed The service-files bucket and the route-area stack cse-http-be-<stage>-api-service (31 of the 006 routes, see the Q27 note above) are now in code and appear in cdk synth; neither is deployed until the owner's next deploy. Everything from the -service stack row down is still planned (Q20) and not in any CDK stack — treat those names as the intended design. :::

ResourceStackNotes
Stack cse-http-be-<stage>-api-serviceRouteAreaStack (lib/route-area-stack.ts), builtFive Lambda families on ApiStack's HttpApi + Cognito authorizer (ids via SSM): work-orders, service-roster, maintenance-plans, plant-service, maintenance-history. Depends on ApiStack
S3 bucket cse-http-be-<stage>-service-filesDataStack, builtBlock Public Access all, enforceSSL, SSE-S3, no versioning; lifecycle expires pending/ and (since 2026-11-11, not deployed) avatar-pending/ after 1 day and aborts incomplete multipart after 1 day; CORS PUT/GET for the webOrigins context; RETAIN in every stage, no autoDeleteObjects (it would add a CDK-managed Lambda outside ApiFunction). SSM parameter /cse-http-be/<stage>/service-files-bucket. Lambdas read it as SERVICE_FILES_BUCKET — unset → E09 answers 503 DEPENDENCY_UNAVAILABLE
S3 bucket cse-http-be-<stage>-reportsDataStack, built (009; read by the report routes — download, delete)Block Public Access all, enforceSSL, SSE-S3; lifecycle expires reports/ after 90 days; RETAIN in every stage, no autoDeleteObjects. Keys are server-generated: reports/incoming/<reportId>/<attempt>/<fileId>.<ext> (renderer uploads) and reports/manifests/<reportId>/<attempt>/manifest.json. The TCP renderer-role bucket policy (s3:GetObject on reports/manifests/*, s3:PutObject on reports/incoming/*) is added only when context tcpRendererRoleArn is set. Dev sets it in cdk.json context.stages.dev (arn:aws:iam::574317420690:role/cse-tcp-be-dev-report-renderer, committed 2026-11-04, takes effect at the next deploy:dev); before that, the dev bucket policy had no renderer statement, so every dev render failed reading the manifest. The s3:LifecycleExpiration:Delete notification (prefix reports/incoming/) → report-dispatch queue only when reportDispatchQueueArn is set (dev: in cdk.json stages.dev since 2026-11-04; otherwise -c reportDispatchQueueArn=<ReportsStack output> on a second data-stack deploy, see Operations → Reports deploy order). SSM parameter /cse-http-be/<stage>/reports-bucket.
S3 bucket cse-http-be-<stage>-uploadsRemoved (ADR 0012)Never deployed, with its SSM parameter /cse-http-be/<stage>/uploads-bucket; device import moved to the TCP server
Stack cse-http-be-<stage>-servicelib/service-stack.ts, built in code, not deployed; instantiated only with -c busEnabled=true (STATELESS, no routes)holds the queue, DLQ, scheduler and plan worker. The maintenance-plans route family gets PLAN_CYCLES_QUEUE_URL + sqs:SendMessage on this queue (by its deterministic name) only with busEnabled; without it :run-now answers 503 DEPENDENCY_UNAVAILABLE
SQS cse-http-be-<stage>-plan-cycles + DLQ-servicevisibility timeout 360 s (6 × worker timeout), retention 4 days; DLQ -dlq 14 days, maxReceiveCount 5; SSE-SQS
EventBridge Scheduler plan-tick-servicecse-http-be-<stage>-plan-tick, rate(1 hour) → the queue ({"kind":"TICK"}), retries 3 / max event age 900 s. Role cse-http-be-<stage>-plan-tick-scheduler: sqs:SendMessage on this queue only, assumable only by this account's plan-tick schedule. State DISABLED unless -c servicePlansEnabled=true
plan-worker Lambda (ApiFunction)-service256 MB, 60 s, arm64; SQS event source batchSize 1, maximumConcurrency 2, reportBatchItemFailures; env PLAN_CYCLES_QUEUE_URL; table read/write + sqs:SendMessage (continuations). Never reservedConcurrentExecutions
DLQ depthno alarm (DlqDepth dropped 2026-10-27); check by hand (runbook)

Without -c busEnabled=true none of these exist: scheduled plans never fire and :run-now answers 503. With busEnabled but without -c servicePlansEnabled=true the stack deploys but the hourly tick is DISABLED (run-now still works). The SQS mapping is enabled: busEnabled.

Device operations resources (feature 007) — removed​

:::danger Removed — ADR 0012 phase 2 The 007 routes and the cse-http-be-<stage>-api-devices-ops stack, including its always-on command-sweep rule (rate(1 minute)), no longer exist in code. Devices and commands are served by the TCP server over the WebSocket. The buckets, driver, flags and events below were removed in phase 3; the table is kept as a record. :::

ResourceStateNotes
007 HTTP routes (command-catalog, commands, operation-log, operation-log-export, bulk-tasks, firmware-packages, device-files families)Removed — ADR 0012 phase 2No longer registered; stack cse-http-be-<stage>-api-devices-ops is no longer synthesized. Devices and commands are served by the TCP server over the WebSocket
Firmware bucket cse-http-be-<stage>-firmwareRemoved (ADR 0012)Never deployed; SSM /cse-http-be/<stage>/firmware-bucket removed too
Firmware bucket policy TcpExecutorReadReleasedFirmwareRemoved (ADR 0012)Went with the firmware bucket
Engineering-files bucket cse-http-be-<stage>-engineering-filesRemoved (ADR 0012)Never deployed; SSM /cse-http-be/<stage>/engineering-files-bucket removed too
Context flags commandsDispatchEnabled / firmwareTasksEnabledRemoved (ADR 0012)No longer read by any stack
Bulk-task driver bulk-task-driver (per-minute rule)Removed (ADR 0012)Never deployed
command.status.v1 subscriptionRemoved (ADR 0012)Dropped from the from-tcp filter
Outbound command.requested.v1 / command.cancelled.v1Removed (ADR 0012)Dropped from the SNS allowlist

Commands, bulk tasks, firmware packages and device files are removed from this service (ADR 0012).

Notifications stack (built — opt-in, not deployed)​

NotifyStack (lib/notify-stack.ts, stack cse-http-be-<stage>-notify) is built (T008-017/018/019/040/041/073/083). Like the integration stack it is created only with -c busEnabled=true; a default synth has no notify queue, consumer or alarm. It has no routes (those are in cse-http-be-<stage>-api-notify). It depends on -data (table) and -observability (alerts topic). It has not been deployed.

ResourceDetails
SQS cse-http-be-<stage>-notify-recompute + …-notify-recompute-dlqAudience recompute and weekly reconcile pages. Visibility 1800 s, retention 4 d, maxReceiveCount 5, DLQ retention 14 d, SQS-managed encryption
SQS cse-http-be-<stage>-digest-jobs + …-digest-jobs-dlqDigest jobs {orgId, periodKey}. Same settings
NotifyRecomputeFn (handler notify-recompute)Consumes notify-recompute; RECONCILE_PAGE messages are dispatched to the reconcile handler in the same function. 300 s timeout, batch 1, maxConcurrency 2, partial batch failures
DigestFn (handler digest)Consumes digest-jobs; one digest per (org, period), email or push fallback. 300 s, batch 1, maxConcurrency 2
Schedule group cse-http-be-<stage>-digestsOne-time digest schedules created by DigestFn
Schedule cse-http-be-<stage>-notify-reconcile-startcron(0 21 ? * SUN,WED *) UTC (NOTIFY_RECONCILE_CRON; Sunday and Wednesday 21:00 UTC) → notify-recompute with {"kind":"RECONCILE_PAGE","reason":"WEEKLY"}; 3 retries, max event age 1 h
Role cse-http-be-<stage>-notify-schedulerAssumed by scheduler.amazonaws.com (trust policy conditioned on aws:SourceAccount and aws:SourceArn); sqs:SendMessage on the two work queues only

Both functions use ApiFunction (arm64, 256 MB, 14-day logs) and the event source mappings are enabled only when busEnabled is true.

Environment variables: NotifyRecomputeFn — TABLE_NAME, NOTIFY_RECOMPUTE_QUEUE_URL. DigestFn — TABLE_NAME, DIGEST_JOBS_QUEUE_ARN, DIGEST_SCHEDULER_ROLE_ARN, and only when the context keys are set, NOTIFY_EMAIL_FROM (-c notifyEmailFrom=…) and NOTIFY_SES_CONFIGURATION_SET (-c notifySesConfigurationSet=…).

IAM:

  • NotifyRecomputeFn: table read/write, sqs:SendMessage on its own queue (continuation pages), ssm:GetParameter on the notify channel flags.
  • DigestFn: table read/write, ssm:GetParameter on the channel flags, scheduler:CreateSchedule on schedule/cse-http-be-<stage>-digests/*, iam:PassRole on the scheduler role (only to scheduler.amazonaws.com). ses:SendEmail/ses:SendRawEmail on the sender identity (and configuration set) only when -c notifyEmailFrom is set. Email stays off while SES is in sandbox.

Alarms (to the cse-http-be-<stage>-alerts topic):

AlarmCondition
cse-http-be-<stage>-NotifyReconcileStalemetric CseHttpBe/<stage>/ReconcileCompleted (from a log filter on notify_reconcile_completed) Sum < 1 over one 7-day period; the metric filter emits 0 by default; missing data is not breaching

With runs twice a week, a single missed run does not fire NotifyReconcileStale; a full 7-day window with no completed run does. Because missing data is not breaching, the alarm stays quiet right after the first deploy, and it cannot detect a function that never runs at all (no log events → no datapoints).

The notify-recompute queue has no alarm: its oldest-message input to BacklogAge and its DLQ alarm (DlqDepth) were both dropped by owner decision 2026-10-27 to stay within the free tier. NotifyReconcileStale and the synchronous fallback cover a stuck recompute.

Cost (CloudWatch pricing page, read 2026-10-27). Standard alarms bill $0.10 per alarm metric (each metric in a metric-math expression counts) after 10 free; a Metrics Insights query alarm bills $0.10 per metric the query analyses and is outside the free tier. Default synth: 5 alarms = 5 standard alarm metrics = $0. busEnabled: 8 alarms = 10 standard alarm metrics (the 5 above + BacklogAge 3 inputs + ReportsOverdue + NotifyReconcileStale) → exactly the free tier = $0 (the notify-recompute BacklogAge input was dropped by owner decision 2026-10-27). The DependencyUnavailable Metrics Insights alarm was dropped by owner decision 2026-11-10 (Q12) because Insights alarms bill per series outside the free tier; the DependencyUnavailable metric is still emitted and can be graphed or queried. The DlqDepth alarm (8 metrics) was dropped by owner decision 2026-10-27 to stay near the free tier; DLQs are kept but checked by hand (runbook). ADR 0012 phase 3 removed DeviceRemovalStuck and DeviceImportDlqDepth.

Stack outputs: NotifyRecomputeQueueUrl, DigestJobsQueueUrl, DigestScheduleGroupName.

Since Q36 (2026-10-27) the queue also carries USERS recompute requests (≤ 1000 users each) for audience changes affecting more than 25 users; the API recomputes synchronously only when the queue is not configured or an enqueue fails.

API-side grant (lib/route-family.ts, notifyRecompute route flag in lib/routes.ts). With busEnabled, every route family holding a flagged route — members, shares, invitation-accept, service-roster — gets env NOTIFY_RECOMPUTE_QUEUE_URL and sqs:SendMessage on cse-http-be-<stage>-notify-recompute only (ARN built from the deterministic name). Without busEnabled neither is set and those families recompute synchronously. See Notifications architecture.

Reports infrastructure (feature 009)​

ResourceState
S3 bucket cse-http-be-<stage>-reportsExists in DataStack (see table above)
ReportsStack — report-dispatch queue + DLQ, dispatcher, render-status consumer, sweeper, schedule runnerBuilt, not deployed — opt-in with -c busEnabled=true (see Reports stack)
EventBridge Scheduler schedule group for report schedulesBuilt, not deployed — part of ReportsStack
Report/schedule routes (H01–H06)Registered in code (batch 69) in stack cse-http-be-<stage>-api-reports; generating routes answer 503 DEPENDENCY_UNAVAILABLE until ReportsStack is deployed (-c busEnabled=true) and 422 REPORTS_GENERATE_DISABLED until -c reportsGenerateEnabled=true

Report-route IAM and env (lib/route-family.ts). S3 access is limited to reports/*, never s3:*: routes that read report objects (download) get s3:GetObject on arn:…:<reports bucket>/reports/*; the delete route also gets s3:DeleteObject on reports/* and s3:ListBucket on the bucket with condition s3:prefix reports/* (used to delete every attempt prefix of a report). Env vars: REPORTS_BUCKET (routes using the bucket), REPORT_DISPATCH_QUEUE_URL, REPORT_RUNS_QUEUE_URL, REPORT_SCHEDULE_GROUP (pipeline routes, only when ReportsStack exists — absent → 503) and REPORTS_GENERATE_ENABLED (true only with -c reportsGenerateEnabled=true; otherwise false → 422).

See Reports pipeline.

Account settings resources (feature 010) — in code, not deployed yet​

Verified against lib/routes.ts, lib/route-family.ts and lib/auth-stack.ts (2026-10-23).

ResourceStateNotes
Stack cse-http-be-<stage>-api-accountRouteAreaStack, registered in code7 RouteDefs with area: 'account' on ApiStack's shared HttpApi and Cognito authorizer (Q27). Callable after the owner's next deploy
Lambda family me-settings6 routesGET /v1/me/settings, PATCH /v1/me/profile, GET/PATCH /v1/me/preferences, GET /v1/me/sessions, POST /v1/me/sessions/{action}
Lambda family me-security1 routePOST /v1/me/{action} (mfa:disable, password:report-change, sessions:end-all, sessions:end-others (2026-11-12, not deployed), notifications:mark-read)
Cognito PostAuthentication triggerWired (T010-061, Q41)PostAuthenticationFn (packages/api/src/handlers/post-authentication.ts) is attached in lib/auth-stack.ts. Per sign-in: provisions a missing profile, stamps lastSignInAt/previousSignInAt, reconciles the MFA snapshot. Since 2026-11-12 (not deployed) it writes no SESSION item: the record is created on the sign-in's first authenticated request, keyed by origin_jti. Never throws, so it never blocks a sign-in; a ~3.5 s internal deadline (function timeout 5 s) means a slow trigger logs sign_in_record_failed {step: 'deadline'} and lets sign-in proceed, possibly without the sign-in record. Reads the pool id from the event (no USER_POOL_ID env, avoiding a circular dependency)

IAM (pool ARN only, no *). Each family gets the union of its routes' cognitoActions:

Familycognito-idp: actions
me-settingsAdminGetUser, AdminUpdateUserAttributes
me-securityAdminGetUser, AdminSetUserMFAPreference, AdminUpdateUserAttributes, AdminUserGlobalSignOut

No route family is granted sns:Publish for SMS: phone change and phone OTP were removed (OQ-09), and the phoneChangeSmsEnabled flag no longer exists.

Environment variables (all public, non-secret identifiers):

VariableFamiliesUse
USER_POOL_ID, SERVER_CLIENT_IDme-settings, me-securityCognito admin calls
WEB_CLIENT_IDSme-settings, meClassify a token's client as WEB (session label on GET /v1/me, /v1/me/context, settings and sessions)
MOBILE_CLIENT_IDSme-settings, meComma-separated Flutter client ids, classify as MOBILE
TABLE_NAME, ROUTE_CONFIG, WEB_CONSOLE_CLIENT_IDS, MFA_ENFORCEMENTevery familyStandard
SESSION_CLIENTS, SESSION_IP_CLIENT_IDSevery family with an authorized route (2026-11-12)The per-route sign-in guard: client kind + refresh lifetime, and which clients' forwarded IP is trusted

Reports stack (feature 009) — built, opt-in, not deployed​

ReportsStack (lib/reports-stack.ts, stack cse-http-be-<stage>-reports, T009-032…035/099/113) is created only with -c busEnabled=true (STATELESS, no routes of its own; the report routes, registered in batch 69, live in cse-http-be-<stage>-api-reports and read its queue URLs / schedule group). It depends on -data (table, reports bucket) and -observability (alerts topic). It has not been deployed. Names are deterministic so IntegrationStack, DataStack and the route family reference them without cross-stack imports.

ResourceDetails
SQS cse-http-be-<stage>-report-dispatch + …-dlqOutbox report.dispatch.requested and S3 lifecycle-expiry events. Visibility 360 s (6 × dispatcher), retention 4 d, maxReceiveCount 5, DLQ 14 d, SSE-SQS. Queue policy lets s3.amazonaws.com send only from bucket cse-http-be-<stage>-reports in this account
SQS cse-http-be-<stage>-report-runs + …-dlqScheduled fires and fan-out continuations. Visibility 180 s (6 × runner), same retention/DLQ settings
Schedule group cse-http-be-<stage>-reportsPer-schedule EventBridge Scheduler entries, created/updated/deleted by the stream router
Role cse-http-be-<stage>-report-schedulerAssumed by scheduler.amazonaws.com (conditions aws:SourceAccount + aws:SourceArn = the group); sqs:SendMessage on report-runs only
ReportDispatcherFn (report-dispatcher)60 s; SQS batch 5, maxConcurrency 2, partial batch failures, enabled: busEnabled. Env TABLE_NAME, REPORTS_BUCKET, SERVICE_FILES_BUCKET. Table read/write; s3:PutObject/GetObject/DeleteObject on reports/*; s3:GetObject only on the service-files bucket's brand/* (copies the report logo next to the render manifest). Env REPORT_DISPATCH_PER_MINUTE from context reportDispatchPerMinute (-c or stages.<stage>; dev sets 10 at TCP's request; default 30, 0 = off; non-integer fails synth); see dispatch pacing. Renderer grant unchanged (-c tcpRendererRoleArn)
ReportScheduleRunnerFn (report-schedule-runner)30 s; same event-source settings on report-runs. Env TABLE_NAME, REPORTS_BUCKET, REPORT_RUNS_QUEUE_URL, REPORTS_GENERATE_ENABLED (-c reportsGenerateEnabled=true, default false). Table read/write; sqs:SendMessage on its own queue
ReportSweeperFn (report-sweeper)30 s; rule cse-http-be-<stage>-report-sweeper, rate(5 minutes), retryAttempts: 0. Fails in-flight reports past renderDeadline with RENDER_TIMEOUT

Stream router wiring (in IntegrationStack, busEnabled only): env REPORT_DISPATCH_QUEUE_URL, REPORT_SCHEDULE_GROUP, REPORT_RUNS_QUEUE_ARN, REPORT_SCHEDULER_ROLE_ARN; sqs:SendMessage on report-dispatch; scheduler:Create/Update/DeleteSchedule on schedule/cse-http-be-<stage>-reports/*; iam:PassRole on the scheduler role (only to scheduler.amazonaws.com).

Alarms (to the alerts topic, no dimensions):

AlarmCondition
cse-http-be-<stage>-ReportsOverduemetric CseHttpBe/<stage>/ReportsOverdue (log filter on report_sweeper_overdue in the sweeper log) Sum ≥ 1 over 15 min — reports still in flight > 10 min past deadline

Missing data is not breaching. The two report DLQs have no alarm (DlqDepth dropped 2026-10-27; check by hand).

Stack outputs: ReportDispatchQueueArn (feed to the data stack, see Operations), ReportRunsQueueUrl, ReportScheduleGroupName.

Web console additions (N-37 … N-51) — in code, not deployed​

  • New stack cse-http-be-<stage>-api-reports-settings (route area reports-settings) hosts the org-branding family, the brand-asset routes. Its S3 grant is s3:PutObject / s3:GetObject on brand/* (final keys) and, since the KI-40 fix (issue #14, 2026-11-13, not deployed), s3:PutObject / s3:GetObject / s3:DeleteObject on pending/brand/* (uploads, which the existing pending/ lifecycle rule expires after 1 day). No list, no other prefix, no delete on brand/*, see KI-40. It deploys after cse-http-be-<stage>-api, like every area stack.
  • Profile pictures (2026-11-11, not deployed): the four /v1/me/avatar routes are in the me-settings family (-api-account). That family gets SERVICE_FILES_BUCKET and s3:PutObject/GetObject/DeleteObject on avatars/* and avatar-pending/* of the service-files bucket only (no list, no other prefix). Objects: avatar-pending/<sub>/<uploadId> (1-day lifecycle) and avatars/<sub>/<avatarId>. See Profile picture API.
  • Work-order drafts are in -api-service, layouts and session end in -api-account, notification settings in -api-notify, and GET /v1/about (family discovery) in the main -api stack.
  • New CDK context keys (all optional and non-secret, validated at synth): reportSamplesBaseUrl, aboutBuildCommit, aboutBuiltAt, supportEmail, supportUrl, privacyUrl, termsUrl. See Operations.
  • New DynamoDB items: work-order drafts (30-day TTL), USER#<sub>/LAYOUT#<key>, brand assets, the per-customer counters COUNT#plants#customer#<c> and COUNT#WOCUST#OPEN#<c>, and PLATFORM/STATUS.