{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Description": "365 Network signed email sender: company alerts, approved staff recipients and opted-in announcements.",
  "Resources": {
    "Requests": {
      "Type": "AWS::DynamoDB::Table",
      "Properties": {
        "BillingMode": "PAY_PER_REQUEST",
        "AttributeDefinitions": [
          {
            "AttributeName": "id",
            "AttributeType": "S"
          }
        ],
        "KeySchema": [
          {
            "AttributeName": "id",
            "KeyType": "HASH"
          }
        ],
        "TimeToLiveSpecification": {
          "AttributeName": "expires",
          "Enabled": true
        }
      }
    },
    "LogGroup": {
      "Type": "AWS::Logs::LogGroup",
      "Properties": {
        "LogGroupName": {
          "Fn::Sub": "/aws/lambda/${AWS::StackName}-sender"
        },
        "RetentionInDays": 7
      }
    },
    "Role": {
      "Type": "AWS::IAM::Role",
      "Properties": {
        "AssumeRolePolicyDocument": {
          "Version": "2012-10-17",
          "Statement": [
            {
              "Effect": "Allow",
              "Principal": {
                "Service": "lambda.amazonaws.com"
              },
              "Action": "sts:AssumeRole"
            }
          ]
        },
        "Policies": [
          {
            "PolicyName": "Only365InboxEmail",
            "PolicyDocument": {
              "Version": "2012-10-17",
              "Statement": [
                {
                  "Effect": "Allow",
                  "Action": "ses:SendEmail",
                  "Resource": [
                    "arn:aws:ses:us-east-2:253792400215:identity/hotmusic365.com",
                    "arn:aws:ses:us-east-2:253792400215:identity/info@hotmusic365.com"
                  ],
                  "Condition": {
                    "StringEquals": {
                      "ses:FromAddress": "info@hotmusic365.com"
                    }
                  }
                },
                {
                  "Effect": "Allow",
                  "Action": [
                    "dynamodb:PutItem",
                    "dynamodb:GetItem",
                    "dynamodb:UpdateItem",
                    "dynamodb:DeleteItem"
                  ],
                  "Resource": {
                    "Fn::GetAtt": [
                      "Requests",
                      "Arn"
                    ]
                  }
                },
                {
                  "Effect": "Allow",
                  "Action": [
                    "logs:CreateLogStream",
                    "logs:PutLogEvents"
                  ],
                  "Resource": {
                    "Fn::GetAtt": [
                      "LogGroup",
                      "Arn"
                    ]
                  }
                }
              ]
            }
          }
        ]
      }
    },
    "Sender": {
      "Type": "AWS::Lambda::Function",
      "Properties": {
        "FunctionName": {
          "Fn::Sub": "${AWS::StackName}-sender"
        },
        "Runtime": "nodejs22.x",
        "Handler": "index.handler",
        "Role": {
          "Fn::GetAtt": [
            "Role",
            "Arn"
          ]
        },
        "MemorySize": 128,
        "Timeout": 10,
        "Environment": {
          "Variables": {
            "SITE_PUBLIC_KEY": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzxqj/nAVWBz6FAcYiOaG\nYvccqgrIQ1w8kQDdnKDwm6Vzop7z2V/MsIFHneBpOFywPM4THdowP8iXAE5ibLrz\n1dJdyq6uBjX2Sb0cj8kb0eEZUo14003vXmxz8Q30sTuWGZtlmssWOGT2GbrHbMIJ\nn2CEbpfHRSrYFhYF8mcwg+QdaFHN8+/M5I3O2grKxyaFPSQwSlCxkrw8XFsgW5mt\n3Gys76IW/pI/p5bDOosR9I0tBb+RMSvnorq3fjRYfZPuwoEb9nPH4lK8IV/OvZ4P\nRfDfQoSNNHRYs5qqIz21x9Cccgqa60/1lTx0EoJeSx1+vkcZTMOZATxgeeecd/K7\nNQIDAQAB\n-----END PUBLIC KEY-----\n",
            "REQUEST_TABLE": {
              "Ref": "Requests"
            }
          }
        },
        "Code": {
          "ZipFile": "const crypto=require('node:crypto');\nconst reply=(statusCode,body)=>({statusCode,headers:{'content-type':'application/json','cache-control':'no-store'},body:JSON.stringify(body)});\nfunction createHandler({publicKey,reserve,complete,release,lookup,send,now=()=>Math.floor(Date.now()/1000)}){\n return async event=>{\n  if(event.requestContext?.http?.method==='GET'&&event.rawPath==='/capabilities')return reply(200,{recipientRouting:true});\n  if(event.requestContext?.http?.method!=='POST'||event.rawPath!=='/notify')return reply(404,{error:'Not found'});\n  const h=Object.fromEntries(Object.entries(event.headers||{}).map(([k,v])=>[k.toLowerCase(),v]));\n  const timestamp=h['x-365-timestamp'],nonce=h['x-365-nonce'],signature=h['x-365-signature'];\n  const body=event.isBase64Encoded?Buffer.from(event.body||'','base64').toString('utf8'):event.body||'';\n  if(Buffer.byteLength(body)>48000||!/^\\d{10}$/.test(timestamp||'')||Math.abs(now()-Number(timestamp))>60||!/^[-a-zA-Z0-9]{20,80}$/.test(nonce||'')||typeof signature!=='string'||signature.length>600)return reply(401,{error:'Unauthorized'});\n  try{if(!crypto.verify('RSA-SHA256',Buffer.from(`365-network-email-v1\\n${timestamp}\\n${nonce}\\n${body}`),publicKey,Buffer.from(signature,'base64')))return reply(401,{error:'Unauthorized'});}catch{return reply(401,{error:'Unauthorized'});}\n  let data;try{data=JSON.parse(body);}catch{return reply(400,{error:'Invalid message'});}\n  if(!/^(inquiry|upload|artist):[a-f0-9-]{36}(:\\d{1,16})?$/.test(data.id||'')||typeof data.label!=='string'||data.label.length>150||!data.fields||typeof data.fields!=='object'||Array.isArray(data.fields)||Object.entries(data.fields).length>40||Object.entries(data.fields).some(([k,v])=>k.length>60||typeof v!=='string'||v.length>5000))return reply(400,{error:'Invalid notification'});\n  const recipient=data.recipient||'info@hotmusic365.com';if(typeof recipient!=='string'||recipient.length>254||! /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(recipient))return reply(400,{error:'Invalid recipient'});\n  let existing;try{existing=await lookup(data.id);}catch{return reply(503,{error:'Email status is unavailable'});}\n  if(existing)return existing==='accepted'?reply(200,{accepted:true}):reply(409,{uncertain:true});\n  try{await reserve(data.id,now());}catch{return reply(429,{error:'Wait before retrying this notification'});}\n  const lines=Object.entries(data.fields).map(([k,v])=>`${k.replaceAll('_',' ')}: ${v}`).join('\\n\\n');\n  // Recipient overrides are accepted only inside the verified server-signed envelope. One private recipient per message.\n  const input={Source:'365 Network <info@hotmusic365.com>',Destination:{ToAddresses:[recipient]},Message:{Subject:{Data:`365 Network | ${data.label.replace(/[\\r\\n\\u0000-\\u001f]/g,' ')}`,Charset:'UTF-8'},Body:{Text:{Data:`${lines}\\n\\nReference: ${data.id}\\n\\nReview in the private back office:\\nhttps://hotmusic365.com/admin.html\\n\\nFiles are stored privately and are not attached. This notification does not approve a service or booking.`,Charset:'UTF-8'}}}};\n  const email=data.fields.email;if(typeof email==='string'&&/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email)&&email.length<=254)input.ReplyToAddresses=[email];\n  try{await send(input);}catch(error){\n   // Definitive SES refusals can be retried; network/timeout ambiguity must be reviewed.\n   if(error.$metadata?.httpStatusCode>=400&&error.$metadata.httpStatusCode<500){try{await release(data.id);}catch{}return reply(503,{error:'Amazon refused the email. Check SES configuration.'});}\n   console.error('Email result uncertain',error.name);return reply(503,{uncertain:true});\n  }\n  try{await complete(data.id);}catch{return reply(503,{uncertain:true});}\n  return reply(200,{accepted:true});\n };\n}\nexports.createHandler=createHandler;\nif(process.env.AWS_LAMBDA_FUNCTION_NAME){\n const {SESClient,SendEmailCommand}=require('@aws-sdk/client-ses');\n const {DynamoDBClient,GetItemCommand,TransactWriteItemsCommand,UpdateItemCommand,DeleteItemCommand}=require('@aws-sdk/client-dynamodb');\n const ses=new SESClient({region:'us-east-2',maxAttempts:1}),db=new DynamoDBClient({}),table=process.env.REQUEST_TABLE;\n exports.handler=createHandler({publicKey:process.env.SITE_PUBLIC_KEY,\n lookup:async id=>(await db.send(new GetItemCommand({TableName:table,Key:{id:{S:`event:${id}`}},ConsistentRead:true}))).Item?.state?.S,\n reserve:(id,now)=>db.send(new TransactWriteItemsCommand({TransactItems:[\n  {Put:{TableName:table,Item:{id:{S:`event:${id}`},state:{S:'sending'},expires:{N:String(now+2592000)}},ConditionExpression:'attribute_not_exists(id)'}},\n  {Put:{TableName:table,Item:{id:{S:'rate'},expires:{N:String(now+1)}},ConditionExpression:'attribute_not_exists(id) OR expires <= :now',ExpressionAttributeValues:{':now':{N:String(now)}}}},\n  {Update:{TableName:table,Key:{id:{S:`day:${Math.floor(now/86400)}`}},UpdateExpression:'SET expires=:expiry ADD sent :one',ConditionExpression:'attribute_not_exists(sent) OR sent < :cap',ExpressionAttributeValues:{':expiry':{N:String(now+172800)},':one':{N:'1'},':cap':{N:'150'}}}}\n ]})),\n complete:id=>db.send(new UpdateItemCommand({TableName:table,Key:{id:{S:`event:${id}`}},UpdateExpression:'SET #state=:state',ExpressionAttributeNames:{'#state':'state'},ExpressionAttributeValues:{':state':{S:'accepted'}}})),\n release:id=>db.send(new DeleteItemCommand({TableName:table,Key:{id:{S:`event:${id}`}}})),\n send:input=>ses.send(new SendEmailCommand(input))});\n}\n"
        }
      }
    },
    "Url": {
      "Type": "AWS::Lambda::Url",
      "Properties": {
        "TargetFunctionArn": {
          "Fn::GetAtt": [
            "Sender",
            "Arn"
          ]
        },
        "AuthType": "NONE",
        "InvokeMode": "BUFFERED"
      }
    },
    "UrlPermission": {
      "Type": "AWS::Lambda::Permission",
      "Properties": {
        "FunctionName": {
          "Ref": "Sender"
        },
        "Action": "lambda:InvokeFunctionUrl",
        "Principal": "*",
        "FunctionUrlAuthType": "NONE"
      }
    },
    "InvokePermission": {
      "Type": "AWS::Lambda::Permission",
      "Properties": {
        "FunctionName": {
          "Ref": "Sender"
        },
        "Action": "lambda:InvokeFunction",
        "Principal": "*",
        "InvokedViaFunctionUrl": true
      }
    }
  },
  "Outputs": {
    "EmailBackendUrl": {
      "Value": {
        "Fn::GetAtt": [
          "Url",
          "FunctionUrl"
        ]
      }
    }
  }
}
