@sinch/functions-runtime 0.4.18 → 0.5.0

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.
package/dist/index.d.ts CHANGED
@@ -2534,6 +2534,26 @@ export declare class DefaultEndpointHandler {
2534
2534
  * TypeScript projects compile to dist/function.js
2535
2535
  */
2536
2536
  export declare function findFunctionPath(): string;
2537
+ /** ICE callback payload as delivered to your handler (`callid` normalized to `callId`). */
2538
+ export type IceCallback = Omit<Voice.IceRequest, "callid"> & {
2539
+ callId?: string;
2540
+ };
2541
+ /** ACE callback payload as delivered to your handler. */
2542
+ export type AceCallback = Omit<Voice.AceRequest, "callid"> & {
2543
+ callId?: string;
2544
+ };
2545
+ /** PIE callback payload as delivered to your handler. */
2546
+ export type PieCallback = Omit<Voice.PieRequest, "callid"> & {
2547
+ callId?: string;
2548
+ };
2549
+ /** DICE callback payload as delivered to your handler. */
2550
+ export type DiceCallback = Omit<Voice.DiceRequest, "callid"> & {
2551
+ callId?: string;
2552
+ };
2553
+ /** NOTIFY callback payload as delivered to your handler. */
2554
+ export type NotifyCallback = Omit<Voice.NotifyRequest, "callid"> & {
2555
+ callId?: string;
2556
+ };
2537
2557
  /** @deprecated Import from '@sinch/voice' instead: `import type { Voice } from '@sinch/voice'` then use `Voice.IceRequest` @internal */
2538
2558
  export type IceCallbackData = Voice.IceRequest;
2539
2559
  /** @deprecated Import from '@sinch/voice' instead @internal */
@@ -2695,7 +2715,23 @@ export declare class SecretsLoader {
2695
2715
  */
2696
2716
  private getFunctionNameFromConfig;
2697
2717
  /**
2698
- * Load custom secrets added via 'sinch functions secrets' command
2718
+ * Read a plaintext credential field from the active CLI profile.
2719
+ * Scoped to the canonical pair (keySecretPlaintext, applicationSecretPlaintext)
2720
+ * that sinch-cli writes when the OS keychain is unreachable. See
2721
+ * sinch-cli/src/lib/credentials.ts store() for the writer side.
2722
+ */
2723
+ private readProfilePlaintext;
2724
+ /**
2725
+ * Active write/read/delete round-trip to verify the OS keychain is reachable.
2726
+ * Used to distinguish "keychain works but no entries stored" from "keychain
2727
+ * unreachable" so error messages can be specific. Cost: 3 secret-tool /
2728
+ * security / PowerShell invocations, only when no secrets were loaded.
2729
+ */
2730
+ private probeKeychain;
2731
+ private platformHint;
2732
+ private warnPlaintext;
2733
+ /**
2734
+ * Load custom secrets added via the 'sinch secrets' command
2699
2735
  */
2700
2736
  loadCustomSecrets(secretNames?: string[]): Promise<Record<string, string>>;
2701
2737
  /**
package/dist/index.js CHANGED
@@ -3260,6 +3260,7 @@ function getTunnelClient(localPort = 3e3) {
3260
3260
  import fs4 from "fs";
3261
3261
  import path5 from "path";
3262
3262
  import os from "os";
3263
+ import crypto2 from "crypto";
3263
3264
 
3264
3265
  // src/secrets/keychain.ts
3265
3266
  import { execFile, spawn } from "child_process";
@@ -3434,6 +3435,14 @@ var macKeychain = {
3434
3435
  }
3435
3436
  }
3436
3437
  };
3438
+ function debugKeychain(op, err) {
3439
+ if (!process.env.DEBUG?.includes("sinch:keychain")) return;
3440
+ const e = err;
3441
+ const stderr = e.stderr?.toString() ?? "";
3442
+ const code = e.code ?? e.exitCode ?? "?";
3443
+ const message = e.message ?? String(err);
3444
+ console.debug(`[keychain] secret-tool ${op} failed (code=${code}): ${stderr || message}`);
3445
+ }
3437
3446
  var linuxKeychain = {
3438
3447
  async getPassword(service, account) {
3439
3448
  try {
@@ -3443,7 +3452,8 @@ var linuxKeychain = {
3443
3452
  { timeout: 15e3 }
3444
3453
  );
3445
3454
  return stdout.trimEnd();
3446
- } catch {
3455
+ } catch (err) {
3456
+ debugKeychain("lookup", err);
3447
3457
  return null;
3448
3458
  }
3449
3459
  },
@@ -3454,14 +3464,31 @@ var linuxKeychain = {
3454
3464
  ["store", "--label", `${service}/${account}`, "service", service, "account", account],
3455
3465
  { stdio: ["pipe", "pipe", "pipe"] }
3456
3466
  );
3467
+ let stderr = "";
3468
+ child.stderr?.on("data", (chunk) => {
3469
+ stderr += chunk.toString();
3470
+ });
3457
3471
  child.stdin.write(password);
3458
3472
  child.stdin.end();
3459
3473
  await new Promise((resolve, reject) => {
3460
- child.on(
3461
- "close",
3462
- (code) => code === 0 ? resolve() : reject(new Error("secret-tool store failed"))
3463
- );
3464
- child.on("error", reject);
3474
+ child.on("close", (code) => {
3475
+ if (code === 0) {
3476
+ resolve();
3477
+ } else {
3478
+ const err = Object.assign(
3479
+ new Error(
3480
+ `secret-tool store failed (exit ${code})${stderr ? ": " + stderr.trim() : ""}`
3481
+ ),
3482
+ { stderr, exitCode: code }
3483
+ );
3484
+ debugKeychain("store", err);
3485
+ reject(err);
3486
+ }
3487
+ });
3488
+ child.on("error", (err) => {
3489
+ debugKeychain("store", err);
3490
+ reject(err);
3491
+ });
3465
3492
  });
3466
3493
  },
3467
3494
  async deletePassword(service, account) {
@@ -3472,7 +3499,8 @@ var linuxKeychain = {
3472
3499
  { timeout: 15e3 }
3473
3500
  );
3474
3501
  return true;
3475
- } catch {
3502
+ } catch (err) {
3503
+ debugKeychain("clear", err);
3476
3504
  return false;
3477
3505
  }
3478
3506
  }
@@ -3491,6 +3519,12 @@ var backend = getBackend();
3491
3519
  async function getPassword(service, account) {
3492
3520
  return backend.getPassword(service, account);
3493
3521
  }
3522
+ async function setPassword(service, account, password) {
3523
+ return backend.setPassword(service, account, password);
3524
+ }
3525
+ async function deletePassword(service, account) {
3526
+ return backend.deletePassword(service, account);
3527
+ }
3494
3528
 
3495
3529
  // src/secrets/index.ts
3496
3530
  var SecretsLoader = class {
@@ -3532,45 +3566,63 @@ var SecretsLoader = class {
3532
3566
  }
3533
3567
  let secretsLoaded = 0;
3534
3568
  if (secretsToLoad.includes("PROJECT_ID_API_SECRET")) {
3535
- const apiSecret = await getPassword(this.SERVICE_NAME, `${this.username}-keySecret`);
3569
+ let apiSecret = await getPassword(this.SERVICE_NAME, `${this.username}-keySecret`);
3570
+ let fromPlaintext = false;
3571
+ if (!apiSecret) {
3572
+ apiSecret = this.readProfilePlaintext("keySecretPlaintext");
3573
+ fromPlaintext = !!apiSecret;
3574
+ }
3536
3575
  if (apiSecret) {
3537
3576
  process.env.PROJECT_ID_API_SECRET = apiSecret;
3538
- console.log("\u2705 Loaded PROJECT_ID_API_SECRET from secure storage");
3577
+ if (fromPlaintext) {
3578
+ this.warnPlaintext("PROJECT_ID_API_SECRET");
3579
+ } else {
3580
+ console.log("\u2705 Loaded PROJECT_ID_API_SECRET from secure storage");
3581
+ }
3539
3582
  secretsLoaded++;
3540
3583
  }
3541
3584
  }
3542
3585
  if (secretsToLoad.includes("VOICE_APPLICATION_SECRET")) {
3543
3586
  const applicationKey = process.env.VOICE_APPLICATION_KEY || this.getApplicationKeyFromConfig();
3587
+ let appSecret = null;
3588
+ let fromPlaintext = false;
3544
3589
  if (applicationKey) {
3545
- const appSecret = await getPassword(this.SERVICE_NAME, applicationKey);
3546
- if (appSecret) {
3547
- process.env.VOICE_APPLICATION_SECRET = appSecret;
3548
- console.log("\u2705 Loaded VOICE_APPLICATION_SECRET from secure storage");
3549
- secretsLoaded++;
3550
- }
3590
+ appSecret = await getPassword(this.SERVICE_NAME, applicationKey);
3551
3591
  }
3552
- }
3553
- const functionName = this.getFunctionNameFromConfig();
3554
- for (const secretName of secretsToLoad) {
3555
- if (secretName === "PROJECT_ID_API_SECRET" || secretName === "VOICE_APPLICATION_SECRET") {
3556
- continue;
3592
+ if (!appSecret) {
3593
+ appSecret = this.readProfilePlaintext("applicationSecretPlaintext");
3594
+ fromPlaintext = !!appSecret;
3557
3595
  }
3558
- if (functionName) {
3559
- const value = await getPassword(
3560
- this.SERVICE_NAME,
3561
- `${functionName}-${secretName}`
3562
- );
3563
- if (value) {
3564
- process.env[secretName] = value;
3565
- console.log(`\u2705 Loaded ${secretName} from secure storage`);
3566
- secretsLoaded++;
3596
+ if (appSecret) {
3597
+ process.env.VOICE_APPLICATION_SECRET = appSecret;
3598
+ if (fromPlaintext) {
3599
+ this.warnPlaintext("VOICE_APPLICATION_SECRET");
3600
+ } else {
3601
+ console.log("\u2705 Loaded VOICE_APPLICATION_SECRET from secure storage");
3567
3602
  }
3603
+ secretsLoaded++;
3568
3604
  }
3569
3605
  }
3606
+ const customSecretNames = secretsToLoad.filter(
3607
+ (secretName) => secretName !== "PROJECT_ID_API_SECRET" && secretName !== "VOICE_APPLICATION_SECRET"
3608
+ );
3609
+ const customSecrets = await this.loadCustomSecrets(customSecretNames);
3610
+ for (const secretName of Object.keys(customSecrets)) {
3611
+ console.log(`\u2705 Loaded ${secretName} from secure storage`);
3612
+ secretsLoaded++;
3613
+ }
3570
3614
  if (secretsLoaded === 0) {
3571
- console.log("\u2139\uFE0F No secrets found in secure storage for declared variables");
3572
- console.log("\u{1F4A1} To configure Sinch auth: sinch auth login");
3573
- console.log("\u{1F4A1} To add custom secrets: sinch secrets add <KEY> <VALUE>");
3615
+ const probe = await this.probeKeychain();
3616
+ if (!probe.ok) {
3617
+ console.warn(`\u26A0\uFE0F Keychain unreachable: ${probe.reason}`);
3618
+ if (probe.hint) console.warn(` ${probe.hint}`);
3619
+ console.warn(" Sinch CLI may have stored credentials in plaintext config instead.");
3620
+ console.warn(" Run `sinch auth status` to verify, or re-run `sinch auth login`.");
3621
+ } else {
3622
+ console.log("\u2139\uFE0F No secrets found in secure storage for declared variables");
3623
+ console.log("\u{1F4A1} To configure Sinch auth: sinch auth login");
3624
+ console.log("\u{1F4A1} To add custom secrets: sinch secrets add <KEY> <VALUE>");
3625
+ }
3574
3626
  }
3575
3627
  return secretsLoaded > 0;
3576
3628
  } catch (error) {
@@ -3610,18 +3662,98 @@ var SecretsLoader = class {
3610
3662
  return null;
3611
3663
  }
3612
3664
  /**
3613
- * Load custom secrets added via 'sinch functions secrets' command
3665
+ * Read a plaintext credential field from the active CLI profile.
3666
+ * Scoped to the canonical pair (keySecretPlaintext, applicationSecretPlaintext)
3667
+ * that sinch-cli writes when the OS keychain is unreachable. See
3668
+ * sinch-cli/src/lib/credentials.ts store() for the writer side.
3669
+ */
3670
+ readProfilePlaintext(field) {
3671
+ try {
3672
+ const home = os.homedir();
3673
+ const metaPath = path5.join(home, ".sinch", "config.json");
3674
+ let activeProfile = "default";
3675
+ if (fs4.existsSync(metaPath)) {
3676
+ const meta = JSON.parse(fs4.readFileSync(metaPath, "utf8"));
3677
+ if (typeof meta.activeProfile === "string" && meta.activeProfile) {
3678
+ activeProfile = meta.activeProfile;
3679
+ }
3680
+ }
3681
+ if (/[\\/]/.test(activeProfile) || activeProfile.includes("..")) {
3682
+ return null;
3683
+ }
3684
+ const profilePath = path5.join(home, ".sinch", "profiles", `${activeProfile}.json`);
3685
+ if (!fs4.existsSync(profilePath)) return null;
3686
+ const profile = JSON.parse(fs4.readFileSync(profilePath, "utf8"));
3687
+ const value = profile[field];
3688
+ return typeof value === "string" && value.length > 0 ? value : null;
3689
+ } catch (err) {
3690
+ console.debug("[Secrets] Could not read plaintext profile fallback:", String(err));
3691
+ return null;
3692
+ }
3693
+ }
3694
+ /**
3695
+ * Active write/read/delete round-trip to verify the OS keychain is reachable.
3696
+ * Used to distinguish "keychain works but no entries stored" from "keychain
3697
+ * unreachable" so error messages can be specific. Cost: 3 secret-tool /
3698
+ * security / PowerShell invocations, only when no secrets were loaded.
3699
+ */
3700
+ async probeKeychain() {
3701
+ const sentinelAccount = `__sinch_probe_${crypto2.randomUUID()}`;
3702
+ const sentinelValue = crypto2.randomUUID();
3703
+ try {
3704
+ await setPassword(this.SERVICE_NAME, sentinelAccount, sentinelValue);
3705
+ } catch (err) {
3706
+ return {
3707
+ ok: false,
3708
+ reason: `write failed (${err instanceof Error ? err.message : String(err)})`,
3709
+ hint: this.platformHint()
3710
+ };
3711
+ }
3712
+ let readBack = null;
3713
+ try {
3714
+ readBack = await getPassword(this.SERVICE_NAME, sentinelAccount);
3715
+ } catch {
3716
+ }
3717
+ try {
3718
+ await deletePassword(this.SERVICE_NAME, sentinelAccount);
3719
+ } catch {
3720
+ }
3721
+ if (readBack !== sentinelValue) {
3722
+ return {
3723
+ ok: false,
3724
+ reason: "write reported success but value cannot be read back",
3725
+ hint: this.platformHint()
3726
+ };
3727
+ }
3728
+ return { ok: true };
3729
+ }
3730
+ platformHint() {
3731
+ if (process.platform === "linux") {
3732
+ return 'On Linux/WSL: sudo apt install libsecret-tools gnome-keyring dbus-x11 && eval "$(gnome-keyring-daemon --start --components=secrets)"';
3733
+ }
3734
+ if (process.platform === "darwin") {
3735
+ return "On macOS: unlock the login keychain (Keychain Access app) and retry";
3736
+ }
3737
+ return "On Windows: ensure Credential Manager is accessible from this user session";
3738
+ }
3739
+ warnPlaintext(envVar) {
3740
+ console.warn(
3741
+ `\u26A0\uFE0F Loaded ${envVar} from plaintext config (~/.sinch/profiles/<active>.json) \u2014 keychain unavailable.`
3742
+ );
3743
+ console.warn(` ${this.platformHint()}`);
3744
+ }
3745
+ /**
3746
+ * Load custom secrets added via the 'sinch secrets' command
3614
3747
  */
3615
3748
  async loadCustomSecrets(secretNames = []) {
3616
3749
  const secrets = {};
3750
+ if (process.env.NODE_ENV === "production") {
3751
+ return secrets;
3752
+ }
3617
3753
  try {
3618
3754
  const functionName = this.getFunctionNameFromConfig();
3619
- if (!functionName) {
3620
- console.debug("[Secrets] Could not determine function name for custom secrets");
3621
- return secrets;
3622
- }
3623
3755
  for (const secretName of secretNames) {
3624
- const value = await getPassword(this.SERVICE_NAME, `${functionName}-${secretName}`);
3756
+ const value = functionName && await getPassword(this.SERVICE_NAME, `${functionName}-${secretName}`) || await getPassword(this.SERVICE_NAME, `custom-${secretName}`);
3625
3757
  if (value) {
3626
3758
  secrets[secretName] = value;
3627
3759
  process.env[secretName] = value;