-
Star
(104)
You must be signed in to star a gist -
Fork
(54)
You must be signed in to fork a gist
-
-
Save matt2005/744b5ef548cc13d88d0569eea65f5e5b to your computer and use it in GitHub Desktop.
""" | |
Copyright 2019 Jason Hu <awaregit at gmail.com> | |
Licensed under the Apache License, Version 2.0 (the "License"); | |
you may not use this file except in compliance with the License. | |
You may obtain a copy of the License at | |
http://www.apache.org/licenses/LICENSE-2.0 | |
Unless required by applicable law or agreed to in writing, software | |
distributed under the License is distributed on an "AS IS" BASIS, | |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
See the License for the specific language governing permissions and | |
limitations under the License. | |
""" | |
import os | |
import json | |
import logging | |
import urllib3 | |
_debug = bool(os.environ.get('DEBUG')) | |
_logger = logging.getLogger('HomeAssistant-SmartHome') | |
_logger.setLevel(logging.DEBUG if _debug else logging.INFO) | |
def lambda_handler(event, context): | |
"""Handle incoming Alexa directive.""" | |
_logger.debug('Event: %s', event) | |
base_url = os.environ.get('BASE_URL') | |
assert base_url is not None, 'Please set BASE_URL environment variable' | |
base_url = base_url.strip("/") | |
directive = event.get('directive') | |
assert directive is not None, 'Malformatted request - missing directive' | |
assert directive.get('header', {}).get('payloadVersion') == '3', \ | |
'Only support payloadVersion == 3' | |
scope = directive.get('endpoint', {}).get('scope') | |
if scope is None: | |
# token is in grantee for Linking directive | |
scope = directive.get('payload', {}).get('grantee') | |
if scope is None: | |
# token is in payload for Discovery directive | |
scope = directive.get('payload', {}).get('scope') | |
assert scope is not None, 'Malformatted request - missing endpoint.scope' | |
assert scope.get('type') == 'BearerToken', 'Only support BearerToken' | |
token = scope.get('token') | |
if token is None and _debug: | |
token = os.environ.get('LONG_LIVED_ACCESS_TOKEN') # only for debug purpose | |
verify_ssl = not bool(os.environ.get('NOT_VERIFY_SSL')) | |
http = urllib3.PoolManager( | |
cert_reqs='CERT_REQUIRED' if verify_ssl else 'CERT_NONE', | |
timeout=urllib3.Timeout(connect=2.0, read=10.0) | |
) | |
response = http.request( | |
'POST', | |
'{}/api/alexa/smart_home'.format(base_url), | |
headers={ | |
'Authorization': 'Bearer {}'.format(token), | |
'Content-Type': 'application/json', | |
}, | |
body=json.dumps(event).encode('utf-8'), | |
) | |
if response.status >= 400: | |
return { | |
'event': { | |
'payload': { | |
'type': 'INVALID_AUTHORIZATION_CREDENTIAL' | |
if response.status in (401, 403) else 'INTERNAL_ERROR', | |
'message': response.data.decode("utf-8"), | |
} | |
} | |
} | |
_logger.debug('Response: %s', response.data.decode("utf-8")) | |
return json.loads(response.data.decode('utf-8')) |
Oh... okay. So I expect, that in my case, I need to set up a separate proxy server for ipv4 requests tunneling everything to my ipv6 address, don't I? My ISP doesn't provide me a public IPV4 due to CG-NAT / Ds lite... It is plausible....
Oh... okay. So I expect, that in my case, I need to set up a separate proxy server for ipv4 requests tunneling everything to my ipv6 address, don't I? My ISP doesn't provide me a public IPV4 due to CG-NAT / Ds lite... It is plausible....
Had the same issue, check my solution a few posts up.
The reading of the SSL configuration is wrong in the script:
https://gist.github.com/matt2005/744b5ef548cc13d88d0569eea65f5e5b#file-lambda_function-py-L55
You can easily verify that in a python interactive shell:
>>> bool("False")
True
The correct line should be:
verify_ssl = "False" == os.environ.get('NOT_VERIFY_SSL')
Hi all, I'm stucked on the following point of the guide:
"Go to Alexa app or web > go to skill list > find your skill in DEV or peroper tab > click the skill you made > 'Enable' > Now login into HA(doesn't matter MFA or not) > TADA! you can see beautiful green 'successfully linked' message."
Alexa App can access to HA, HA recognize a valid userid and password but the link process provides a generic error.
Do you have an idea?
Thanks
I got it working with cloudflared. Unfortunately, if I unset include_entities, no entity gets discovered. I have to manually define them in my alexa.yaml. so how can I get alexa to import ALL my devices T__T? Why is this a whitelist? It shouldn't be, right?
I got it working with cloudflared. Unfortunately, if I unset include_entities, no entity gets discovered. I have to manually define them in my alexa.yaml. so how can I get alexa to import ALL my devices T__T? Why is this a whitelist? It shouldn't be, right?
Believe me when I say: You don't want that. Alexa will find every single Entity, tons if them will be useless and deleting them from the Alexa app is a pita. It's way better to select the entities specifically (and fine tune their names/ categories) or to at least only select certain categories for discovery.
Believe me when I say: You don't want that. Alexa will find every single Entity, tons if them will be useless and deleting them from the Alexa app is a pita.
Not every entity. Just those who were made available for voice assistants already (url home-assistant.xyz/config/voice-assistants/expose)... I am just curious. When I've set up a LONG_LIVED_ACCESS_TOKEN and Debug to true, then started a test discovery, I got everything I wanted... Even scenes were included..
EDIT: you were right. I will make use of the filter. thank you.
For those who are worried about exposing your HA to the world. I have my HA protected with mTLS (nginx reverse proxy), and I install TLS client certs/keys only on trusted devices so I can be sure only those people can get through the proxy. On Chrome it asks what client cert you want to use when you visit the url. It works with the Android Companion App, and on Chrome seamlessly, probably because it harnesses a webkit frame. You have to run your own CA and sign user certs manually, but it should be a one time thing, and devices tend to remember what certs to auth with.
So I signed a new certificate and pkey for use in the Alexa Lambda and ported this code to nodeJS 20. When proxying the POST request, I setup a fetch agent with the client credentials, so now this lambda is authorized through, and not everyone in the world. The lambda is only triggered by Alexa and not by API Gateway, so it's pretty secure unless somebody hacks your AWS account and finds the raw keys in the lambda code.
I also noticed that upon account linking, my phone was calling /auth/authorize (which worked), but the Echo Dot was trying to fetch a token (without the client creds). So I had to make a 2nd proxy lambda for the POST /auth/token call (which does a similar thing), put it on an API Gateway and replace the auth/token URL when linking accounts in the dev portal.
It was a lot of work, but it seems to be a decent setup.
Hi! This code is working very fine to me. I am using the CloudFlare Add-On for Home Assistant. The only concern is that, in the first call, the skill takes almost 10 seconds to run the command but the subsequent calls takes about 1 to 3 seconds. Is it possible to keep, at least, one connection established using the urllib3.PoolManager to speed the first call?
I have the same issue, how do you solved it?
Hi! This code is working very fine to me. I am using the CloudFlare Add-On for Home Assistant. The only concern is that, in the first call, the skill takes almost 10 seconds to run the command but the subsequent calls takes about 1 to 3 seconds. Is it possible to keep, at least, one connection established using the urllib3.PoolManager to speed the first call?
I have the same issue, how do you solved it?
Same
Hi! This code is working very fine to me. I am using the CloudFlare Add-On for Home Assistant. The only concern is that, in the first call, the skill takes almost 10 seconds to run the command but the subsequent calls takes about 1 to 3 seconds. Is it possible to keep, at least, one connection established using the urllib3.PoolManager to speed the first call?
I have the same issue, how do you solved it?
Same
I solved it. In my case I have the firewall which I allow Ireland country where I run my AWS Lambda. But in some cases it uses some ip which is not listed in the country list of Synology firewall, so I added the problematic ranges manually:
54.240.197.0/24
54.239.99.0/24
I checked it in HA by user > security > tokens update list where I can see some of the ips used on login to layla.amazon.com (EU) and check the ranges from AWS https://ip-ranges.amazonaws.com/ip-ranges.json and add them if my Synology Ireland country list didn't take that range into account. After that no problems anymore of trying 2-3 times call Alexa. I also have that problem on activating the skill in Alexa where I always need to disable the firewall to authenticate to my HA.

@wolfwander mention
Hi! This code is working very fine to me. I am using the CloudFlare Add-On for Home Assistant. The only concern is that, in the first call, the skill takes almost 10 seconds to run the command but the subsequent calls takes about 1 to 3 seconds. Is it possible to keep, at least, one connection established using the urllib3.PoolManager to speed the first call?
I have the same issue, how do you solved it?
Same
I moved to Matterbridge Add-On. Much faster but a little bit buggy...
I installed two instances of Matterbridge:
- one in the same machine of HASS to expose entities with an specific label
- one in the same machine of Zigbee2MQTT to expose Z2M devices
Hi! This code is working very fine to me. I am using the CloudFlare Add-On for Home Assistant. The only concern is that, in the first call, the skill takes almost 10 seconds to run the command but the subsequent calls takes about 1 to 3 seconds. Is it possible to keep, at least, one connection established using the urllib3.PoolManager to speed the first call?
I have the same issue, how do you solved it?
Same
I moved to Matterbridge Add-On. Much faster but a little bit buggy... I installed two instances of Matterbridge:
- one in the same machine of HASS to expose entities with an specific label
- one in the same machine of Zigbee2MQTT to expose Z2M devices
That's awesome tip!!!!! Thanks!!!!
Hi Guys, i have a little Problem. I have a DS-Lite Connection at home so i'm using AAAA Records to remote-Access my Home-Assistant via IPV6. But unfortunately this Code doesn't work for me for some reasons... I can normally access my HomeAssistant and i even get a "405" when entering https://YOUR-HA-URL:YOUR-PORT/api/alexa/smart_home , wherever i am. But why can't the Lambda function conntect to my HA... error message as follows:
I hope someone can help me... don't know what to do.. or is the Lambda Function just unable to do ipv6 connections? Thanks in advance!
Hi Guys, i have a little Problem. I have a DS-Lite Connection at home so i'm using AAAA Records to remote-Access my Home-Assistant via IPV6. But unfortunately this Code doesn't work for me for some reasons... I can normally access my HomeAssistant and i even get a "405" when entering https://YOUR-HA-URL:YOUR-PORT/api/alexa/smart_home , wherever i am. But why can't the Lambda function conntect to my HA... error message as follows:
I hope someone can help me... don't know what to do.. or is the Lambda Function just unable to do ipv6 connections? Thanks in advance!Did you find any solution?
Hello
Did you find any solution?
@Sonorc The lamba will not hit your IP6 addresss. It will only resolve IP4 addresses. You can use CloudFlare (no cost) to get an IP4 address (on a CloudFlare server) that you then tunnel into your IP6 host.
I finally got the Alexa account to link by:
- setup a cloudflare tunnel (gives me the public IP4 addr) that
- tunnels to a CNAME entry maintained by DDNS (Synology's built-in service supports IP6)
- CNAME IP resolves to my NAS IP directly (router forwards port 443 is to NAS)
- A reverse proxy (Synology Login Portal) translates the incoming address (https://my-cloudflare-domain:443) to http://localhost:8123/.
@stalsma thanks.
Hi everyone,
I´ve tried to follow this guide carefully, but it does not work for me even though I got everything connected. Testing the lambda function with the access token seems to work, but it returns an empty list of endpoints:
{
"event": {
"header": {
"namespace": "Alexa.Discovery",
"name": "Discover.Response",
"messageId": "7be269dc-01b6-4eb8-9184-313063f33557",
"payloadVersion": "3"
},
"payload": {
"endpoints": []
}
}
}
My home assistant lists a few sensors when checking https://{home_assistant_url}/config/voice-assistants/expose and these sensors are visible at the Dashboard and appear online. But still, the list of endpoints is empty, so Alexa is anable to add any devices.
I added this (no filtering) into my configuration.yaml:
`alexa:
smart_home:`
I am quite new to home assistant so this might be a simple configuration mistake by myself.
I am using Home Assistant Supervised version 2024.11.2 running on Ubuntu 24.04 Server
@Pandafuchs
The script itself is IPv6 compatible it's the lambda function that needs to be IPv6 compatible. I managed to do it with a VPC that has IPv4 and IPv6 subnets and can connect to the internet via routing and gateway (VPC specific).
Only thing still not working for me is the account linking process.
@pascal260303, I am also facing issues regarding the account linking... I have tried various combinations of AWS locations, skill languages, client ids, etc. and also moved away from cloudflare proxies. I can see that the Discovery example is working fine, but during the linking process I get a blank page with the URL being external/link-result?success=false
. Would love to know how to debug this
Edit: Just updated the Alexa app. However, instead of a blank page I get "Alexa couldn't find a new device to connect."
With my setup, which has a public static IP address, Nginx add-on, Let's Encrypt ( NO Cloudflare), the integration works only with port 443.
Fortunately, there is another solution that works with a custom SSL port.
https://indomus.it/guide/integrare-gratuitamente-amazon-echo-alexa-con-home-assistant-via-haaska-e-aws/
Personally speaking, I did this way years ago, and it worked until I decided to try the new way according to the official documentation, and I ended up losing some days.
Official documentation should underline that only 443 port MUST be used.
I hope this helps others.
every 4 days I have these log messages with Amazon IPs and I don't know exactly if it's related to that script, but everything it's working fine. I also use the Ireland endpoint for European accounts, I have a geoip blocker for non Ireland ips and these ones seems from USA, I don't know how to figure out if it's comming from AWS, alexa developer console or also can be related to Alexa Media Player which is not related to that but I don't expect.
[homeassistant] 2025-03-31 08:01:44.685 WARNING (MainThread) [homeassistant.components.http.ban] Login attempt or request with invalid authentication from 72.21.217.139 (72.21.217.139). Requested URL: '/auth/token'. (Apache-HttpClient/UNAVAILABLE (Java/1.8.0_432))
[homeassistant] 2025-03-27 06:35:33.106 WARNING (MainThread) [homeassistant.components.http.ban] Login attempt or request with invalid authentication from 72.21.217.98 (72.21.217.98). Requested URL: '/auth/token'. (Apache-HttpClient/UNAVAILABLE (Java/1.8.0_432))
[homeassistant] 2025-03-23 10:56:06.647 WARNING (MainThread) [homeassistant.components.http.ban] Login attempt or request with invalid authentication from 54.239.98.30 (54.239.98.30). Requested URL: '/auth/token'. (Apache-HttpClient/UNAVAILABLE (Java/1.8.0_432))
[homeassistant] 2025-03-19 12:47:52.931 WARNING (MainThread) [homeassistant.components.http.ban] Login attempt or request with invalid authentication from 72.21.217.18 (72.21.217.18). Requested URL: '/auth/token'. (Apache-HttpClient/UNAVAILABLE (Java/1.8.0_432))
[homeassistant] 2025-03-15 11:33:52.312 WARNING (MainThread) [homeassistant.components.http.ban] Login attempt or request with invalid authentication from 72.21.217.143 (72.21.217.143). Requested URL: '/auth/token'. (Apache-HttpClient/UNAVAILABLE (Java/1.8.0_432))
[homeassistant] 2025-03-11 12:38:33.360 WARNING (MainThread) [homeassistant.components.http.ban] Login attempt or request with invalid authentication from 54.239.98.38 (54.239.98.38). Requested URL: '/auth/token'. (Apache-HttpClient/UNAVAILABLE (Java/1.8.0_432))
[homeassistant] 2025-03-07 18:31:23.417 WARNING (MainThread) [homeassistant.components.http.ban] Login attempt or request with invalid authentication from 72.21.217.46 (72.21.217.46). Requested URL: '/auth/token'. (Apache-HttpClient/UNAVAILABLE (Java/1.8.0_432))
It is not possible to use IPv6 inside Amazon Skills. You must use IPv4.