Skip to content

Region detection uses apiKey.slice(3, 5) which breaks for keys set via TUYA_API_KEY without the sk- prefix #6

Description

@weijietan09

Summary

The prefix used for region/base-URL resolution is computed two different ways in two
different places, and the two disagree whenever the API key does not start with sk-.
This is reachable today because getApiKey() returns process.env.TUYA_API_KEY verbatim,
bypassing the sk- validation that tuya init enforces.

The two implementations

resolveBaseUrl / resolveWsUri in src/config.js:36-58 strip sk- only if it is
present
, then take the first two characters:

let key = apiKey;
if (key.startsWith('sk-')) {
  key = key.slice(3);
}
const prefix = key.slice(0, 2).toUpperCase();

But doctor and init hard-code a fixed offset of 3, assuming sk- is always there:

  • src/commands/doctor.js:37const prefix = apiKey.slice(3, 5).toUpperCase();
  • src/commands/init.js:46const prefix = apiKey.slice(3, 5).toUpperCase();
  • src/commands/init.js:65const prefix = apiKey.slice(3, 5).toUpperCase();

What goes wrong

Set a perfectly valid raw key (no sk-), e.g. export TUYA_API_KEY=AYabc123...:

  • resolveBaseUrl strips nothing, reads slice(0,2) = AY → correctly returns the China base URL.
  • doctor reads slice(3,5) = c1getRegionName('C1') returns 'Unknown'.

So tuya doctor happily connects to the right data center but reports
Base URL: https://openapi.tuyacn.com (Unknown), which looks like a misconfiguration to
the user. The init path has the same skew if a key is pasted without the prefix.

Suggested fix

Export the prefix-extraction logic from config.js (it already exists inside
resolveBaseUrl) and reuse it everywhere instead of re-deriving the offset by hand. A single
getKeyPrefix(apiKey) helper removes the slice(3,5) vs slice(0,2)-after-strip divergence.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions