@camstack/addon-export-alexa 1.2.132 → 1.2.133

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,75 +1,140 @@
1
1
  /**
2
- * CamStack Alexa Smart Home Lambda — Option 2 (single hosted skill).
2
+ * CamStack Alexa Smart Home Lambda — one skill, many hubs, and the skill's
3
+ * token broker (D753).
3
4
  *
4
- * One Lambda + one skill on developer.amazon.com serves ALL camstack
5
- * users. The Lambda is stateless: it inspects an inbound event, decodes
6
- * the bearer JWT payload to extract the operator's hub URL, then proxies
7
- * the request to that hub's core `/api/oauth2/*` endpoints.
5
+ * One Lambda + one skill serves every CamStack hub. Directives are routed by
6
+ * the `hubUrl` claim each hub bakes into the OAuth tokens it mints. Since D753
7
+ * the Lambda is also the ONLY holder of the skill's LWA client secret: it
8
+ * exchanges AcceptGrant codes itself, keeps each user's LWA refresh token in
9
+ * DynamoDB, and hands hubs short-lived Event Gateway access tokens against a
10
+ * per-link credential (see broker.js).
8
11
  *
9
12
  * Invocation shapes:
10
- * 1. Lambda URL HTTP GET /authorize → render hub-URL entry form
11
- * 2. Lambda URL HTTP POST /token → proxy OAuth token exchange to hub
12
- * 3. Smart Home directive (event.directive.header):
13
- * - Alexa.Authorization/AcceptGrant → exchange LWA code at Amazon,
14
- * forward tokens to hub
15
- * - everything else → forward directive to hub
13
+ * 1. Function URL GET /authorize → hub-URL entry form
14
+ * 2. Function URL POST /token → OAuth token exchange, proxied to the hub
15
+ * 3. Function URL POST /broker/* → token broker (broker.js)
16
+ * 4. Smart Home directive:
17
+ * - Alexa.Authorization/AcceptGrant → exchange the LWA code here, store the
18
+ * grant, give the hub a broker credential (legacy: give it the tokens)
19
+ * - everything else → forward to the hub
16
20
  *
17
- * Required environment variables:
18
- * SKILL_CLIENT_ID OAuth client id Alexa sends on /token (skill
19
- * manifest "Client ID"). Free-form; we just
20
- * compare it.
21
- * SKILL_CLIENT_SECRET Paired client secret (skill manifest "Client
22
- * Secret"). Free-form; compared against the
23
- * inbound POST body.
24
- * LWA_CLIENT_ID Login With Amazon client id from the skill's
25
- * "Permissions → Send Alexa Events" panel. Used
26
- * in the AcceptGrant LWA token exchange.
27
- * LWA_CLIENT_SECRET Paired LWA client secret.
28
- * LAMBDA_REDIRECT_URI The Function URL + "/token" (e.g.
29
- * https://abc123.lambda-url.eu-west-1.on.aws/token).
30
- * Passed as `redirect_uri` to api.amazon.com.
21
+ * Configuration (env — none of these is a secret once D753 is deployed):
22
+ * LWA_SECRET_ID Secrets Manager id of {"clientId","clientSecret"} for
23
+ * the skill's "Send Alexa Events" LWA client.
24
+ * SKILL_SECRET_ID Secrets Manager id of {"clientId","clientSecret"
25
+ * [,"previousClientSecret"]} for account linking.
26
+ * TOKENS_TABLE DynamoDB table of broker links. Unset = broker off
27
+ * (pre-D753 behaviour: tokens are handed to the hub).
28
+ * LAMBDA_REDIRECT_URI Function URL + "/token"; the AcceptGrant redirect_uri.
29
+ * BROKER_PUBLIC_URL Optional; defaults to LAMBDA_REDIRECT_URI's origin.
30
+ * LEGACY_HUB_FALLBACK "0" = a hub without the broker route fails AcceptGrant
31
+ * instead of receiving the refresh token. Default on.
32
+ * ALLOW_MIGRATION "0" = refuse /broker/migrate. Default on.
33
+ * HUB_INGRESS_TOKEN Optional defense-in-depth header for hub calls.
34
+ * Legacy (read only when the *_SECRET_ID is unset): LWA_CLIENT_ID,
35
+ * LWA_CLIENT_SECRET, SKILL_CLIENT_ID, SKILL_CLIENT_SECRET.
31
36
  *
32
- * Ships as a single file — no node_modules, no transpile. Targets the
33
- * AWS Lambda Node 20.x runtime which exposes built-in `fetch`.
37
+ * Ships as plain files — no node_modules, no transpile (`zip` the folder's
38
+ * .js files). AWS SDK v3 comes with the nodejs22.x runtime.
34
39
  */
40
+ 'use strict'
35
41
 
36
- const FETCH_TIMEOUT_MS = 6000
42
+ const crypto = require('node:crypto')
37
43
 
38
- // Use https.request with a no-keep-alive Agent. Node's built-in fetch
39
- // (undici-backed) reuses pooled sockets aggressively; in AWS Lambda the
40
- // invocation-to-invocation gaps can leave pooled sockets stale, and the next
41
- // fetch throws DOMException AbortError in <1s. https.request gives us
42
- // explicit control. undici itself is not require-able in the Node 20 Lambda
43
- // runtime, so we use the standard https module directly.
44
- const https = require('node:https')
45
- const http = require('node:http')
46
- const { URL } = require('node:url')
47
- const NO_KEEPALIVE_AGENT = new https.Agent({ keepAlive: false })
44
+ const { createAwsClients } = require('./aws.js')
45
+ const {
46
+ activateLink,
47
+ createLink,
48
+ exchangeGrantCode,
49
+ handleBrokerRoute,
50
+ isBrokerPath,
51
+ shortId,
52
+ } = require('./broker.js')
53
+ const { timedFetch } = require('./http.js')
54
+ const { createSecretSource } = require('./secrets.js')
55
+ const { createDynamoTokenStore } = require('./token-store.js')
56
+ const {
57
+ decodeBody,
58
+ decodeJwtPayload,
59
+ describe,
60
+ encodeFormUrlEncoded,
61
+ errorEnvelope,
62
+ jsonResponse,
63
+ normaliseHubUrl,
64
+ parseFormUrlEncoded,
65
+ resolveBrokerPublicUrl,
66
+ } = require('./util.js')
48
67
 
49
- exports.handler = async (event) => {
50
- try {
51
- if (event && event.requestContext && event.requestContext.http) {
52
- return await handleLambdaUrl(event)
53
- }
54
- if (event && event.directive && event.directive.header) {
55
- return await handleDirective(event)
56
- }
57
- return jsonResponse(400, { error: 'unknown_event' })
58
- } catch (err) {
59
- console.error('camstack-alexa: unhandled error', err)
60
- if (event && event.directive && event.directive.header) {
61
- return errorEnvelope(event.directive.header, 'INTERNAL_ERROR', describe(err))
68
+ /** The header that tells a hub where its skill's broker lives (D753). */
69
+ const BROKER_HEADER = 'x-camstack-broker'
70
+
71
+ /**
72
+ * Build the dependency set once per container — the secret cache and the SDK
73
+ * clients must survive across invocations. Anything passed in wins (tests).
74
+ */
75
+ function resolveDeps(overrides) {
76
+ const o = overrides || {}
77
+ const env = o.env || process.env
78
+ let aws = null
79
+ const awsClients = () => {
80
+ if (!aws) aws = createAwsClients()
81
+ return aws
82
+ }
83
+ const store =
84
+ o.store !== undefined
85
+ ? o.store
86
+ : env.TOKENS_TABLE
87
+ ? createDynamoTokenStore({
88
+ send: (name, input) => awsClients().send(name, input),
89
+ tableName: env.TOKENS_TABLE,
90
+ })
91
+ : null
92
+ return {
93
+ env,
94
+ fetch: o.fetch || timedFetch,
95
+ now: o.now || Date.now,
96
+ randomBytes: o.randomBytes || crypto.randomBytes,
97
+ log: o.log || console,
98
+ secrets:
99
+ o.secrets ||
100
+ createSecretSource({
101
+ env,
102
+ fetchSecretString: (id) => awsClients().fetchSecretString(id),
103
+ }),
104
+ store,
105
+ publicUrl: resolveBrokerPublicUrl(env),
106
+ }
107
+ }
108
+
109
+ function createHandler(overrides) {
110
+ let deps = null
111
+ return async (event) => {
112
+ if (!deps) deps = resolveDeps(overrides)
113
+ try {
114
+ if (event && event.requestContext && event.requestContext.http) {
115
+ return await handleLambdaUrl(event, deps)
116
+ }
117
+ if (event && event.directive && event.directive.header) {
118
+ return await handleDirective(event, deps)
119
+ }
120
+ return jsonResponse(400, { error: 'unknown_event' })
121
+ } catch (err) {
122
+ deps.log.error('camstack-alexa: unhandled error', describe(err))
123
+ if (event && event.directive && event.directive.header) {
124
+ return errorEnvelope(event.directive.header, 'INTERNAL_ERROR', describe(err))
125
+ }
126
+ return jsonResponse(500, { error: 'internal_error', message: describe(err) })
62
127
  }
63
- return jsonResponse(500, { error: 'internal_error', message: describe(err) })
64
128
  }
65
129
  }
66
130
 
67
131
  // ── Lambda Function URL (HTTP) routes ────────────────────────────────
68
132
 
69
- async function handleLambdaUrl(event) {
133
+ async function handleLambdaUrl(event, deps) {
70
134
  const path = event.rawPath || '/'
71
135
  if (path === '/authorize') return handleAuthorizePage(event)
72
- if (path === '/token') return handleTokenProxy(event)
136
+ if (path === '/token') return handleTokenProxy(event, deps)
137
+ if (isBrokerPath(path)) return handleBrokerRoute(event, deps)
73
138
  return { statusCode: 404, headers: { 'content-type': 'text/plain' }, body: 'Not found' }
74
139
  }
75
140
 
@@ -131,27 +196,42 @@ function handleAuthorizePage(event) {
131
196
  }
132
197
  }
133
198
 
199
+ /** Constant-time string equality that does not leak length via timing. */
200
+ function safeEqual(a, b) {
201
+ const ab = Buffer.from(String(a), 'utf8')
202
+ const bb = Buffer.from(String(b), 'utf8')
203
+ if (ab.length !== bb.length) {
204
+ crypto.timingSafeEqual(ab, ab)
205
+ return false
206
+ }
207
+ return crypto.timingSafeEqual(ab, bb)
208
+ }
209
+
134
210
  /**
135
- * Proxy the OAuth token exchange. Alexa POSTs form-urlencoded body to
136
- * this Function URL with the client_id/client_secret from the skill
137
- * manifest; we verify those, decode the code/refresh_token JWT payload
138
- * to find the hub URL claim, then forward the same body to the hub's
139
- * own /api/oauth2/token endpoint.
211
+ * Proxy the OAuth token exchange. Alexa POSTs a form-urlencoded body with the
212
+ * account-linking client_id/client_secret; we verify those (current secret, or
213
+ * `previousClientSecret` mid-rotation), decode the code/refresh_token JWT
214
+ * payload to find the hub URL claim, then forward the body to the hub's own
215
+ * /api/oauth2/token endpoint.
140
216
  */
141
- async function handleTokenProxy(event) {
217
+ async function handleTokenProxy(event, deps) {
142
218
  if (event.requestContext.http.method !== 'POST') {
143
219
  return jsonResponse(405, { error: 'method_not_allowed' })
144
220
  }
145
221
  const body = parseFormUrlEncoded(decodeBody(event))
146
- const skillId = process.env.SKILL_CLIENT_ID
147
- const skillSecret = process.env.SKILL_CLIENT_SECRET
148
- if (!skillId || !skillSecret) {
222
+ const skill = await deps.secrets.skill()
223
+ if (!skill) {
149
224
  return jsonResponse(500, {
150
225
  error: 'unconfigured',
151
- message: 'SKILL_CLIENT_ID / SKILL_CLIENT_SECRET not set',
226
+ message: 'account-linking client credentials are not configured',
152
227
  })
153
228
  }
154
- if (body.client_id !== skillId || body.client_secret !== skillSecret) {
229
+ const secretOk =
230
+ typeof body.client_secret === 'string' &&
231
+ (safeEqual(body.client_secret, skill.clientSecret) ||
232
+ (skill.previousClientSecret !== undefined &&
233
+ safeEqual(body.client_secret, skill.previousClientSecret)))
234
+ if (body.client_id !== skill.clientId || !secretOk) {
155
235
  return jsonResponse(401, { error: 'invalid_client', message: 'client credentials mismatch' })
156
236
  }
157
237
 
@@ -171,7 +251,7 @@ async function handleTokenProxy(event) {
171
251
  }
172
252
 
173
253
  const target = `${normaliseHubUrl(claims.hubUrl)}/api/oauth2/token`
174
- const upstream = await timedFetch(target, {
254
+ const upstream = await deps.fetch(target, {
175
255
  method: 'POST',
176
256
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
177
257
  body: encodeFormUrlEncoded(body),
@@ -186,81 +266,128 @@ async function handleTokenProxy(event) {
186
266
 
187
267
  // ── Smart Home directives ────────────────────────────────────────────
188
268
 
189
- async function handleDirective(event) {
269
+ async function handleDirective(event, deps) {
190
270
  const header = event.directive.header
191
271
  const ns = `${header.namespace}/${header.name}`
192
272
  if (ns === 'Alexa.Authorization/AcceptGrant') {
193
- return handleAcceptGrant(event)
273
+ return handleAcceptGrant(event, deps)
274
+ }
275
+ return forwardDirective(event, deps)
276
+ }
277
+
278
+ function hubHeaders(deps, bearer) {
279
+ return {
280
+ 'content-type': 'application/json',
281
+ authorization: `Bearer ${bearer}`,
282
+ // Defense-in-depth shared secret — the export-alexa "Ingress token"
283
+ // setting. Sent only when configured; the hub enforces it when the
284
+ // operator turns on "Require ingress token".
285
+ ...(deps.env.HUB_INGRESS_TOKEN ? { 'x-camstack-ingress': deps.env.HUB_INGRESS_TOKEN } : {}),
194
286
  }
195
- return forwardDirective(event)
196
287
  }
197
288
 
198
- async function handleAcceptGrant(event) {
289
+ function brokerAvailable(deps) {
290
+ return deps.store !== null && typeof deps.publicUrl === 'string'
291
+ }
292
+
293
+ function acceptGrantResponse(header) {
294
+ return {
295
+ event: {
296
+ header: {
297
+ namespace: 'Alexa.Authorization',
298
+ name: 'AcceptGrant.Response',
299
+ messageId: header.messageId,
300
+ payloadVersion: '3',
301
+ },
302
+ payload: {},
303
+ },
304
+ }
305
+ }
306
+
307
+ async function handleAcceptGrant(event, deps) {
199
308
  const header = event.directive.header
200
309
  const payload = event.directive.payload || {}
201
310
  const grantCode = payload.grant && payload.grant.code
202
311
  const granteeToken = payload.grantee && payload.grantee.token
203
312
  if (!grantCode || !granteeToken) {
204
- return errorEnvelope(
205
- header,
206
- 'ACCEPT_GRANT_FAILED',
207
- 'payload missing grant.code or grantee.token',
208
- )
313
+ return errorEnvelope(header, 'ACCEPT_GRANT_FAILED', 'payload missing grant.code or grantee.token')
209
314
  }
210
315
  const claims = decodeJwtPayload(granteeToken)
211
316
  if (!claims || typeof claims.hubUrl !== 'string' || claims.hubUrl.length === 0) {
212
317
  return errorEnvelope(header, 'ACCEPT_GRANT_FAILED', 'grantee token has no hubUrl claim')
213
318
  }
319
+ const redirectUri = deps.env.LAMBDA_REDIRECT_URI
320
+ if (!redirectUri) {
321
+ return errorEnvelope(header, 'ACCEPT_GRANT_FAILED', 'LAMBDA_REDIRECT_URI not set on the Lambda')
322
+ }
214
323
 
215
- const lwaClientId = process.env.LWA_CLIENT_ID
216
- const lwaClientSecret = process.env.LWA_CLIENT_SECRET
217
- const redirectUri = process.env.LAMBDA_REDIRECT_URI
218
- if (!lwaClientId || !lwaClientSecret || !redirectUri) {
219
- return errorEnvelope(
220
- header,
221
- 'ACCEPT_GRANT_FAILED',
222
- 'LWA_CLIENT_ID / LWA_CLIENT_SECRET / LAMBDA_REDIRECT_URI not set on the Lambda',
223
- )
324
+ let tokens
325
+ try {
326
+ tokens = await exchangeGrantCode(deps, grantCode, redirectUri)
327
+ } catch (err) {
328
+ return errorEnvelope(header, 'ACCEPT_GRANT_FAILED', describe(err))
224
329
  }
330
+ const hubUrl = normaliseHubUrl(claims.hubUrl)
225
331
 
226
- // Exchange Amazon's grant code for LWA tokens we can hand to the hub
227
- // so it can hit the Event Gateway later (proactive doorbell push).
228
- const lwaResp = await timedFetch('https://api.amazon.com/auth/o2/token', {
229
- method: 'POST',
230
- headers: { 'content-type': 'application/x-www-form-urlencoded' },
231
- body: encodeFormUrlEncoded({
232
- grant_type: 'authorization_code',
233
- code: grantCode,
234
- client_id: lwaClientId,
235
- client_secret: lwaClientSecret,
236
- redirect_uri: redirectUri,
237
- }),
332
+ if (brokerAvailable(deps)) {
333
+ const outcome = await linkViaBroker(deps, { hubUrl, granteeToken, tokens })
334
+ if (outcome.kind === 'linked') return acceptGrantResponse(header)
335
+ if (outcome.kind !== 'hub-without-broker' || deps.env.LEGACY_HUB_FALLBACK === '0') {
336
+ return errorEnvelope(header, 'ACCEPT_GRANT_FAILED', outcome.message)
337
+ }
338
+ deps.log.warn('accept_grant: hub has no broker route; falling back to the legacy token hand-off')
339
+ }
340
+ return deliverTokensToLegacyHub(deps, header, { hubUrl, granteeToken, tokens })
341
+ }
342
+
343
+ /**
344
+ * The D753 link: store the grant here, give the hub only a credential and a
345
+ * first access token. The item stays `pending` until the hub accepted it, so a
346
+ * hub that refuses (or does not have the route) leaves nothing behind.
347
+ */
348
+ async function linkViaBroker(deps, input) {
349
+ const { item, credential } = await createLink(deps, {
350
+ status: 'pending',
351
+ tokens: input.tokens,
352
+ hubUrl: input.hubUrl,
353
+ origin: 'accept-grant',
238
354
  })
239
- if (!lwaResp.ok) {
240
- const text = await lwaResp.text().catch(() => '')
241
- return errorEnvelope(header, 'ACCEPT_GRANT_FAILED', `LWA exchange ${lwaResp.status}: ${text}`)
355
+ let resp
356
+ try {
357
+ resp = await deps.fetch(`${input.hubUrl}/addon/export-alexa/oauth/broker-link`, {
358
+ method: 'POST',
359
+ headers: hubHeaders(deps, input.granteeToken),
360
+ body: JSON.stringify({
361
+ brokerUrl: deps.publicUrl,
362
+ brokerCredential: credential,
363
+ lwaAccessToken: item.accessToken,
364
+ expiresAt: item.accessExpiresAt,
365
+ }),
366
+ })
367
+ } catch (err) {
368
+ await deps.store.remove(item.linkId)
369
+ return { kind: 'failed', message: `hub broker-link unreachable: ${describe(err)}` }
242
370
  }
243
- const lwa = await lwaResp.json()
244
- const expiresInSec = typeof lwa.expires_in === 'number' ? lwa.expires_in : 3600
371
+ if (resp.ok) {
372
+ await activateLink(deps, item)
373
+ deps.log.info('accept_grant: linked via broker', { link: shortId(item.linkId) })
374
+ return { kind: 'linked' }
375
+ }
376
+ await deps.store.remove(item.linkId)
377
+ if (resp.status === 404) return { kind: 'hub-without-broker', message: 'hub broker-link 404' }
378
+ const text = await resp.text().catch(() => '')
379
+ return { kind: 'failed', message: `hub broker-link ${resp.status}: ${text.slice(0, 200)}` }
380
+ }
245
381
 
246
- // Push the tokens back to the hub. The hub authenticates this request
247
- // via the bearer (= the same grantee token Alexa just gave us), so it
248
- // can attribute the LWA tokens to the right operator user.
249
- const hubUrl = normaliseHubUrl(claims.hubUrl)
250
- const callback = `${hubUrl}/addon/export-alexa/oauth/lwa-tokens`
251
- const callbackResp = await timedFetch(callback, {
382
+ /** Pre-D753 hand-off: the hub receives the refresh token itself. */
383
+ async function deliverTokensToLegacyHub(deps, header, input) {
384
+ const callbackResp = await deps.fetch(`${input.hubUrl}/addon/export-alexa/oauth/lwa-tokens`, {
252
385
  method: 'POST',
253
- headers: {
254
- 'content-type': 'application/json',
255
- authorization: `Bearer ${granteeToken}`,
256
- ...(process.env.HUB_INGRESS_TOKEN
257
- ? { 'x-camstack-ingress': process.env.HUB_INGRESS_TOKEN }
258
- : {}),
259
- },
386
+ headers: hubHeaders(deps, input.granteeToken),
260
387
  body: JSON.stringify({
261
- lwaAccessToken: lwa.access_token,
262
- lwaRefreshToken: lwa.refresh_token,
263
- expiresAt: Date.now() + expiresInSec * 1000,
388
+ lwaAccessToken: input.tokens.accessToken,
389
+ lwaRefreshToken: input.tokens.refreshToken,
390
+ expiresAt: deps.now() + input.tokens.expiresInSec * 1000,
264
391
  }),
265
392
  })
266
393
  if (!callbackResp.ok) {
@@ -268,51 +395,32 @@ async function handleAcceptGrant(event) {
268
395
  return errorEnvelope(
269
396
  header,
270
397
  'ACCEPT_GRANT_FAILED',
271
- `hub callback ${callbackResp.status}: ${text}`,
398
+ `hub callback ${callbackResp.status}: ${text.slice(0, 200)}`,
272
399
  )
273
400
  }
274
-
275
- return {
276
- event: {
277
- header: {
278
- namespace: 'Alexa.Authorization',
279
- name: 'AcceptGrant.Response',
280
- messageId: header.messageId,
281
- payloadVersion: '3',
282
- },
283
- payload: {},
284
- },
285
- }
401
+ return acceptGrantResponse(header)
286
402
  }
287
403
 
288
- async function forwardDirective(event) {
404
+ async function forwardDirective(event, deps) {
289
405
  const header = event.directive.header
290
406
  const bearer = extractBearer(event.directive)
291
407
  if (!bearer) {
292
- return errorEnvelope(
293
- header,
294
- 'INVALID_AUTHORIZATION_CREDENTIAL',
295
- 'directive has no bearer token',
296
- )
408
+ return errorEnvelope(header, 'INVALID_AUTHORIZATION_CREDENTIAL', 'directive has no bearer token')
297
409
  }
298
410
  const claims = decodeJwtPayload(bearer)
299
411
  if (!claims || typeof claims.hubUrl !== 'string' || claims.hubUrl.length === 0) {
300
412
  return errorEnvelope(header, 'INVALID_AUTHORIZATION_CREDENTIAL', 'bearer has no hubUrl claim')
301
413
  }
302
414
  const target = `${normaliseHubUrl(claims.hubUrl)}/addon/export-alexa/directive`
303
- const directiveHeaders = {
304
- 'content-type': 'application/json',
305
- authorization: `Bearer ${bearer}`,
306
- // Defense-in-depth shared secret — the export-alexa "Ingress token"
307
- // setting. Sent only when configured; the hub enforces it when the
308
- // operator turns on "Require ingress token".
309
- ...(process.env.HUB_INGRESS_TOKEN
310
- ? { 'x-camstack-ingress': process.env.HUB_INGRESS_TOKEN }
311
- : {}),
312
- }
313
- const resp = await timedFetch(target, {
415
+ const resp = await deps.fetch(target, {
314
416
  method: 'POST',
315
- headers: directiveHeaders,
417
+ headers: {
418
+ ...hubHeaders(deps, bearer),
419
+ // Where this skill's broker lives. A hub linked before D753 uses it to
420
+ // migrate its refresh token here (zero-touch); the hub only believes it
421
+ // on a directive whose bearer it verified.
422
+ ...(brokerAvailable(deps) ? { [BROKER_HEADER]: deps.publicUrl } : {}),
423
+ },
316
424
  body: JSON.stringify(event),
317
425
  })
318
426
  const text = await resp.text()
@@ -341,227 +449,6 @@ function extractBearer(directive) {
341
449
  return null
342
450
  }
343
451
 
344
- // ── Helpers ──────────────────────────────────────────────────────────
345
-
346
- function decodeJwtPayload(token) {
347
- if (typeof token !== 'string') return null
348
- const parts = token.split('.')
349
- if (parts.length < 2) return null
350
- try {
351
- const padded = parts[1].replace(/-/g, '+').replace(/_/g, '/')
352
- const json = Buffer.from(padded, 'base64').toString('utf8')
353
- return JSON.parse(json)
354
- } catch {
355
- return null
356
- }
357
- }
358
-
359
- function normaliseHubUrl(raw) {
360
- return raw.replace(/\/+$/, '')
361
- }
362
-
363
- function decodeBody(event) {
364
- if (!event.body) return ''
365
- if (event.isBase64Encoded) {
366
- return Buffer.from(event.body, 'base64').toString('utf8')
367
- }
368
- return event.body
369
- }
370
-
371
- function parseFormUrlEncoded(body) {
372
- const out = {}
373
- if (!body) return out
374
- for (const pair of body.split('&')) {
375
- if (!pair) continue
376
- const eq = pair.indexOf('=')
377
- const key = decodeURIComponent(eq >= 0 ? pair.slice(0, eq) : pair).replace(/\+/g, ' ')
378
- const value = decodeURIComponent(eq >= 0 ? pair.slice(eq + 1) : '').replace(/\+/g, ' ')
379
- out[key] = value
380
- }
381
- return out
382
- }
383
-
384
- function encodeFormUrlEncoded(obj) {
385
- return Object.keys(obj)
386
- .filter((k) => obj[k] !== undefined && obj[k] !== null)
387
- .map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(String(obj[k]))}`)
388
- .join('&')
389
- }
390
-
391
- async function timedFetch(url, init = {}) {
392
- // Returns a fetch-compatible response object: { ok, status, statusText,
393
- // text(), json() }. The handler only uses .text() / status.
394
- //
395
- // Emits a single structured timing log line on completion (or failure),
396
- // measuring DNS / TCP / TLS / request-sent / first-byte / last-byte sub-
397
- // timings. Read these from CloudWatch with:
398
- // filter @message like /timedFetch_timing/
399
- // to see end-to-end where the wall-clock seconds go (DNS hang vs TCP RTT
400
- // vs TLS handshake vs hub processing time vs body download).
401
- return new Promise((resolve, reject) => {
402
- let settled = false
403
- const parsed = new URL(url)
404
- const isHttps = parsed.protocol === 'https:'
405
- const lib = isHttps ? https : http
406
- const headers = { ...(init.headers || {}), connection: 'close' }
407
- if (init.body !== undefined && headers['content-length'] === undefined) {
408
- headers['content-length'] = Buffer.byteLength(init.body)
409
- }
410
- const T0 = process.hrtime.bigint()
411
- const marks = {
412
- dns: null,
413
- tcpConnect: null,
414
- tlsHandshake: null,
415
- requestSent: null,
416
- firstByte: null,
417
- lastByte: null,
418
- }
419
- const ms = (a, b) => Number((b - a) / 1_000_000n)
420
- const logTiming = (status, extras = {}) => {
421
- const T_end = process.hrtime.bigint()
422
- const total = ms(T0, T_end)
423
- const stages = {
424
- dns: marks.dns ? ms(T0, marks.dns) : null,
425
- tcp: marks.tcpConnect ? ms(T0, marks.tcpConnect) : null,
426
- tls: marks.tlsHandshake ? ms(T0, marks.tlsHandshake) : null,
427
- reqSent: marks.requestSent ? ms(T0, marks.requestSent) : null,
428
- firstByte: marks.firstByte ? ms(T0, marks.firstByte) : null,
429
- lastByte: marks.lastByte ? ms(T0, marks.lastByte) : null,
430
- }
431
- // Stage durations between marks, easier to read at a glance:
432
- const between = {
433
- dns_ms: stages.dns,
434
- tcp_handshake_ms:
435
- stages.tcp != null && stages.dns != null ? stages.tcp - stages.dns : stages.tcp,
436
- tls_handshake_ms: stages.tls != null && stages.tcp != null ? stages.tls - stages.tcp : null,
437
- request_send_ms:
438
- stages.reqSent != null && (stages.tls ?? stages.tcp) != null
439
- ? stages.reqSent - (stages.tls ?? stages.tcp)
440
- : null,
441
- wait_first_byte_ms:
442
- stages.firstByte != null && stages.reqSent != null
443
- ? stages.firstByte - stages.reqSent
444
- : null,
445
- download_ms:
446
- stages.lastByte != null && stages.firstByte != null
447
- ? stages.lastByte - stages.firstByte
448
- : null,
449
- }
450
- console.log(
451
- 'timedFetch_timing',
452
- JSON.stringify({
453
- url: `${parsed.protocol}//${parsed.hostname}${parsed.pathname}`,
454
- method: (init.method || 'GET').toUpperCase(),
455
- status,
456
- total_ms: total,
457
- stages_cum_ms: stages,
458
- between_ms: between,
459
- ...extras,
460
- }),
461
- )
462
- }
463
- const req = lib.request(
464
- {
465
- protocol: parsed.protocol,
466
- hostname: parsed.hostname,
467
- port: parsed.port || (isHttps ? 443 : 80),
468
- path: `${parsed.pathname}${parsed.search}`,
469
- method: (init.method || 'GET').toUpperCase(),
470
- headers,
471
- agent: isHttps ? NO_KEEPALIVE_AGENT : undefined,
472
- },
473
- (res) => {
474
- marks.firstByte = process.hrtime.bigint()
475
- const chunks = []
476
- res.on('data', (c) => chunks.push(c))
477
- res.on('end', () => {
478
- if (settled) return
479
- settled = true
480
- clearTimeout(timer)
481
- marks.lastByte = process.hrtime.bigint()
482
- const body = Buffer.concat(chunks).toString('utf8')
483
- const headersApi = {
484
- get: (name) => {
485
- const v = res.headers[String(name).toLowerCase()]
486
- if (Array.isArray(v)) return v.join(', ')
487
- return v == null ? null : String(v)
488
- },
489
- }
490
- logTiming(res.statusCode, { responseBodyBytes: body.length })
491
- resolve({
492
- ok: res.statusCode >= 200 && res.statusCode < 300,
493
- status: res.statusCode,
494
- statusText: res.statusMessage || '',
495
- headers: headersApi,
496
- text: async () => body,
497
- json: async () => JSON.parse(body),
498
- })
499
- })
500
- res.on('error', (err) => {
501
- if (settled) return
502
- settled = true
503
- clearTimeout(timer)
504
- logTiming('res_error', { error: err && err.message })
505
- reject(err)
506
- })
507
- },
508
- )
509
- req.on('socket', (socket) => {
510
- socket.on('lookup', () => {
511
- marks.dns = process.hrtime.bigint()
512
- })
513
- socket.on('connect', () => {
514
- marks.tcpConnect = process.hrtime.bigint()
515
- })
516
- socket.on('secureConnect', () => {
517
- marks.tlsHandshake = process.hrtime.bigint()
518
- })
519
- })
520
- req.on('finish', () => {
521
- marks.requestSent = process.hrtime.bigint()
522
- })
523
- req.on('error', (err) => {
524
- if (settled) return
525
- settled = true
526
- clearTimeout(timer)
527
- logTiming('req_error', { error: err && err.message, code: err && err.code })
528
- reject(err)
529
- })
530
- const timer = setTimeout(() => {
531
- if (settled) return
532
- settled = true
533
- req.destroy(new Error(`timedFetch timeout after ${FETCH_TIMEOUT_MS}ms`))
534
- logTiming('timeout', { timeout_ms: FETCH_TIMEOUT_MS })
535
- reject(new Error(`timedFetch timeout after ${FETCH_TIMEOUT_MS}ms`))
536
- }, FETCH_TIMEOUT_MS)
537
- if (init.body !== undefined) req.write(init.body)
538
- req.end()
539
- })
540
- }
541
-
542
- function jsonResponse(statusCode, body) {
543
- return {
544
- statusCode,
545
- headers: { 'content-type': 'application/json' },
546
- body: JSON.stringify(body),
547
- }
548
- }
549
-
550
- function errorEnvelope(header, type, message) {
551
- return {
552
- event: {
553
- header: {
554
- namespace: 'Alexa',
555
- name: 'ErrorResponse',
556
- messageId: header.messageId,
557
- payloadVersion: '3',
558
- },
559
- payload: { type, message },
560
- },
561
- }
562
- }
563
-
564
- function describe(err) {
565
- if (err instanceof Error) return err.message
566
- return String(err)
567
- }
452
+ exports.handler = createHandler()
453
+ exports.createHandler = createHandler
454
+ exports.BROKER_HEADER = BROKER_HEADER