@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/README.md CHANGED
@@ -134,16 +134,20 @@ export async function ice(context, event) {
134
134
  | `dice` | Disconnected Call Event - call ended | None |
135
135
  | `notify` | Notification events | None |
136
136
 
137
+ `ace`, `pie`, `dice`, and `notify` are optional — the platform may call them even if your function doesn't implement a handler, and the runtime returns `200` for those unimplemented callbacks (only `ice` is required).
138
+
139
+ Type callback data with `IceCallback` / `AceCallback` / `PieCallback` / `DiceCallback` / `NotifyCallback` — these match what your handler receives (the runtime delivers `callId`, not the raw API's `callid`).
140
+
137
141
  ## TypeScript Support
138
142
 
139
143
  Full TypeScript support with comprehensive types:
140
144
 
141
145
  ```typescript
142
- import type { FunctionContext, IceCallbackData, SvamletResponse } from '@sinch/functions-runtime';
146
+ import type { FunctionContext, IceCallback, SvamletResponse } from '@sinch/functions-runtime';
143
147
 
144
148
  export async function ice(
145
149
  context: FunctionContext,
146
- event: IceCallbackData
150
+ event: IceCallback
147
151
  ): Promise<SvamletResponse> {
148
152
  // Full type safety and IntelliSense!
149
153
  }
@@ -1008,6 +1008,7 @@ function createStorageClient(baseDir) {
1008
1008
  import fs4 from "fs";
1009
1009
  import path5 from "path";
1010
1010
  import os from "os";
1011
+ import crypto2 from "crypto";
1011
1012
 
1012
1013
  // src/secrets/keychain.ts
1013
1014
  import { execFile, spawn } from "child_process";
@@ -1182,6 +1183,14 @@ var macKeychain = {
1182
1183
  }
1183
1184
  }
1184
1185
  };
1186
+ function debugKeychain(op, err) {
1187
+ if (!process.env.DEBUG?.includes("sinch:keychain")) return;
1188
+ const e = err;
1189
+ const stderr = e.stderr?.toString() ?? "";
1190
+ const code = e.code ?? e.exitCode ?? "?";
1191
+ const message = e.message ?? String(err);
1192
+ console.debug(`[keychain] secret-tool ${op} failed (code=${code}): ${stderr || message}`);
1193
+ }
1185
1194
  var linuxKeychain = {
1186
1195
  async getPassword(service, account) {
1187
1196
  try {
@@ -1191,7 +1200,8 @@ var linuxKeychain = {
1191
1200
  { timeout: 15e3 }
1192
1201
  );
1193
1202
  return stdout.trimEnd();
1194
- } catch {
1203
+ } catch (err) {
1204
+ debugKeychain("lookup", err);
1195
1205
  return null;
1196
1206
  }
1197
1207
  },
@@ -1202,14 +1212,31 @@ var linuxKeychain = {
1202
1212
  ["store", "--label", `${service}/${account}`, "service", service, "account", account],
1203
1213
  { stdio: ["pipe", "pipe", "pipe"] }
1204
1214
  );
1215
+ let stderr = "";
1216
+ child.stderr?.on("data", (chunk) => {
1217
+ stderr += chunk.toString();
1218
+ });
1205
1219
  child.stdin.write(password);
1206
1220
  child.stdin.end();
1207
1221
  await new Promise((resolve, reject) => {
1208
- child.on(
1209
- "close",
1210
- (code) => code === 0 ? resolve() : reject(new Error("secret-tool store failed"))
1211
- );
1212
- child.on("error", reject);
1222
+ child.on("close", (code) => {
1223
+ if (code === 0) {
1224
+ resolve();
1225
+ } else {
1226
+ const err = Object.assign(
1227
+ new Error(
1228
+ `secret-tool store failed (exit ${code})${stderr ? ": " + stderr.trim() : ""}`
1229
+ ),
1230
+ { stderr, exitCode: code }
1231
+ );
1232
+ debugKeychain("store", err);
1233
+ reject(err);
1234
+ }
1235
+ });
1236
+ child.on("error", (err) => {
1237
+ debugKeychain("store", err);
1238
+ reject(err);
1239
+ });
1213
1240
  });
1214
1241
  },
1215
1242
  async deletePassword(service, account) {
@@ -1220,7 +1247,8 @@ var linuxKeychain = {
1220
1247
  { timeout: 15e3 }
1221
1248
  );
1222
1249
  return true;
1223
- } catch {
1250
+ } catch (err) {
1251
+ debugKeychain("clear", err);
1224
1252
  return false;
1225
1253
  }
1226
1254
  }
@@ -1239,6 +1267,12 @@ var backend = getBackend();
1239
1267
  async function getPassword(service, account) {
1240
1268
  return backend.getPassword(service, account);
1241
1269
  }
1270
+ async function setPassword(service, account, password) {
1271
+ return backend.setPassword(service, account, password);
1272
+ }
1273
+ async function deletePassword(service, account) {
1274
+ return backend.deletePassword(service, account);
1275
+ }
1242
1276
 
1243
1277
  // src/secrets/index.ts
1244
1278
  var SecretsLoader = class {
@@ -1280,45 +1314,63 @@ var SecretsLoader = class {
1280
1314
  }
1281
1315
  let secretsLoaded = 0;
1282
1316
  if (secretsToLoad.includes("PROJECT_ID_API_SECRET")) {
1283
- const apiSecret = await getPassword(this.SERVICE_NAME, `${this.username}-keySecret`);
1317
+ let apiSecret = await getPassword(this.SERVICE_NAME, `${this.username}-keySecret`);
1318
+ let fromPlaintext = false;
1319
+ if (!apiSecret) {
1320
+ apiSecret = this.readProfilePlaintext("keySecretPlaintext");
1321
+ fromPlaintext = !!apiSecret;
1322
+ }
1284
1323
  if (apiSecret) {
1285
1324
  process.env.PROJECT_ID_API_SECRET = apiSecret;
1286
- console.log("\u2705 Loaded PROJECT_ID_API_SECRET from secure storage");
1325
+ if (fromPlaintext) {
1326
+ this.warnPlaintext("PROJECT_ID_API_SECRET");
1327
+ } else {
1328
+ console.log("\u2705 Loaded PROJECT_ID_API_SECRET from secure storage");
1329
+ }
1287
1330
  secretsLoaded++;
1288
1331
  }
1289
1332
  }
1290
1333
  if (secretsToLoad.includes("VOICE_APPLICATION_SECRET")) {
1291
1334
  const applicationKey = process.env.VOICE_APPLICATION_KEY || this.getApplicationKeyFromConfig();
1335
+ let appSecret = null;
1336
+ let fromPlaintext = false;
1292
1337
  if (applicationKey) {
1293
- const appSecret = await getPassword(this.SERVICE_NAME, applicationKey);
1294
- if (appSecret) {
1295
- process.env.VOICE_APPLICATION_SECRET = appSecret;
1296
- console.log("\u2705 Loaded VOICE_APPLICATION_SECRET from secure storage");
1297
- secretsLoaded++;
1298
- }
1338
+ appSecret = await getPassword(this.SERVICE_NAME, applicationKey);
1299
1339
  }
1300
- }
1301
- const functionName = this.getFunctionNameFromConfig();
1302
- for (const secretName of secretsToLoad) {
1303
- if (secretName === "PROJECT_ID_API_SECRET" || secretName === "VOICE_APPLICATION_SECRET") {
1304
- continue;
1340
+ if (!appSecret) {
1341
+ appSecret = this.readProfilePlaintext("applicationSecretPlaintext");
1342
+ fromPlaintext = !!appSecret;
1305
1343
  }
1306
- if (functionName) {
1307
- const value = await getPassword(
1308
- this.SERVICE_NAME,
1309
- `${functionName}-${secretName}`
1310
- );
1311
- if (value) {
1312
- process.env[secretName] = value;
1313
- console.log(`\u2705 Loaded ${secretName} from secure storage`);
1314
- secretsLoaded++;
1344
+ if (appSecret) {
1345
+ process.env.VOICE_APPLICATION_SECRET = appSecret;
1346
+ if (fromPlaintext) {
1347
+ this.warnPlaintext("VOICE_APPLICATION_SECRET");
1348
+ } else {
1349
+ console.log("\u2705 Loaded VOICE_APPLICATION_SECRET from secure storage");
1315
1350
  }
1351
+ secretsLoaded++;
1316
1352
  }
1317
1353
  }
1354
+ const customSecretNames = secretsToLoad.filter(
1355
+ (secretName) => secretName !== "PROJECT_ID_API_SECRET" && secretName !== "VOICE_APPLICATION_SECRET"
1356
+ );
1357
+ const customSecrets = await this.loadCustomSecrets(customSecretNames);
1358
+ for (const secretName of Object.keys(customSecrets)) {
1359
+ console.log(`\u2705 Loaded ${secretName} from secure storage`);
1360
+ secretsLoaded++;
1361
+ }
1318
1362
  if (secretsLoaded === 0) {
1319
- console.log("\u2139\uFE0F No secrets found in secure storage for declared variables");
1320
- console.log("\u{1F4A1} To configure Sinch auth: sinch auth login");
1321
- console.log("\u{1F4A1} To add custom secrets: sinch secrets add <KEY> <VALUE>");
1363
+ const probe = await this.probeKeychain();
1364
+ if (!probe.ok) {
1365
+ console.warn(`\u26A0\uFE0F Keychain unreachable: ${probe.reason}`);
1366
+ if (probe.hint) console.warn(` ${probe.hint}`);
1367
+ console.warn(" Sinch CLI may have stored credentials in plaintext config instead.");
1368
+ console.warn(" Run `sinch auth status` to verify, or re-run `sinch auth login`.");
1369
+ } else {
1370
+ console.log("\u2139\uFE0F No secrets found in secure storage for declared variables");
1371
+ console.log("\u{1F4A1} To configure Sinch auth: sinch auth login");
1372
+ console.log("\u{1F4A1} To add custom secrets: sinch secrets add <KEY> <VALUE>");
1373
+ }
1322
1374
  }
1323
1375
  return secretsLoaded > 0;
1324
1376
  } catch (error) {
@@ -1358,18 +1410,98 @@ var SecretsLoader = class {
1358
1410
  return null;
1359
1411
  }
1360
1412
  /**
1361
- * Load custom secrets added via 'sinch functions secrets' command
1413
+ * Read a plaintext credential field from the active CLI profile.
1414
+ * Scoped to the canonical pair (keySecretPlaintext, applicationSecretPlaintext)
1415
+ * that sinch-cli writes when the OS keychain is unreachable. See
1416
+ * sinch-cli/src/lib/credentials.ts store() for the writer side.
1417
+ */
1418
+ readProfilePlaintext(field) {
1419
+ try {
1420
+ const home = os.homedir();
1421
+ const metaPath = path5.join(home, ".sinch", "config.json");
1422
+ let activeProfile = "default";
1423
+ if (fs4.existsSync(metaPath)) {
1424
+ const meta = JSON.parse(fs4.readFileSync(metaPath, "utf8"));
1425
+ if (typeof meta.activeProfile === "string" && meta.activeProfile) {
1426
+ activeProfile = meta.activeProfile;
1427
+ }
1428
+ }
1429
+ if (/[\\/]/.test(activeProfile) || activeProfile.includes("..")) {
1430
+ return null;
1431
+ }
1432
+ const profilePath = path5.join(home, ".sinch", "profiles", `${activeProfile}.json`);
1433
+ if (!fs4.existsSync(profilePath)) return null;
1434
+ const profile = JSON.parse(fs4.readFileSync(profilePath, "utf8"));
1435
+ const value = profile[field];
1436
+ return typeof value === "string" && value.length > 0 ? value : null;
1437
+ } catch (err) {
1438
+ console.debug("[Secrets] Could not read plaintext profile fallback:", String(err));
1439
+ return null;
1440
+ }
1441
+ }
1442
+ /**
1443
+ * Active write/read/delete round-trip to verify the OS keychain is reachable.
1444
+ * Used to distinguish "keychain works but no entries stored" from "keychain
1445
+ * unreachable" so error messages can be specific. Cost: 3 secret-tool /
1446
+ * security / PowerShell invocations, only when no secrets were loaded.
1447
+ */
1448
+ async probeKeychain() {
1449
+ const sentinelAccount = `__sinch_probe_${crypto2.randomUUID()}`;
1450
+ const sentinelValue = crypto2.randomUUID();
1451
+ try {
1452
+ await setPassword(this.SERVICE_NAME, sentinelAccount, sentinelValue);
1453
+ } catch (err) {
1454
+ return {
1455
+ ok: false,
1456
+ reason: `write failed (${err instanceof Error ? err.message : String(err)})`,
1457
+ hint: this.platformHint()
1458
+ };
1459
+ }
1460
+ let readBack = null;
1461
+ try {
1462
+ readBack = await getPassword(this.SERVICE_NAME, sentinelAccount);
1463
+ } catch {
1464
+ }
1465
+ try {
1466
+ await deletePassword(this.SERVICE_NAME, sentinelAccount);
1467
+ } catch {
1468
+ }
1469
+ if (readBack !== sentinelValue) {
1470
+ return {
1471
+ ok: false,
1472
+ reason: "write reported success but value cannot be read back",
1473
+ hint: this.platformHint()
1474
+ };
1475
+ }
1476
+ return { ok: true };
1477
+ }
1478
+ platformHint() {
1479
+ if (process.platform === "linux") {
1480
+ return 'On Linux/WSL: sudo apt install libsecret-tools gnome-keyring dbus-x11 && eval "$(gnome-keyring-daemon --start --components=secrets)"';
1481
+ }
1482
+ if (process.platform === "darwin") {
1483
+ return "On macOS: unlock the login keychain (Keychain Access app) and retry";
1484
+ }
1485
+ return "On Windows: ensure Credential Manager is accessible from this user session";
1486
+ }
1487
+ warnPlaintext(envVar) {
1488
+ console.warn(
1489
+ `\u26A0\uFE0F Loaded ${envVar} from plaintext config (~/.sinch/profiles/<active>.json) \u2014 keychain unavailable.`
1490
+ );
1491
+ console.warn(` ${this.platformHint()}`);
1492
+ }
1493
+ /**
1494
+ * Load custom secrets added via the 'sinch secrets' command
1362
1495
  */
1363
1496
  async loadCustomSecrets(secretNames = []) {
1364
1497
  const secrets = {};
1498
+ if (process.env.NODE_ENV === "production") {
1499
+ return secrets;
1500
+ }
1365
1501
  try {
1366
1502
  const functionName = this.getFunctionNameFromConfig();
1367
- if (!functionName) {
1368
- console.debug("[Secrets] Could not determine function name for custom secrets");
1369
- return secrets;
1370
- }
1371
1503
  for (const secretName of secretNames) {
1372
- const value = await getPassword(this.SERVICE_NAME, `${functionName}-${secretName}`);
1504
+ const value = functionName && await getPassword(this.SERVICE_NAME, `${functionName}-${secretName}`) || await getPassword(this.SERVICE_NAME, `custom-${secretName}`);
1373
1505
  if (value) {
1374
1506
  secrets[secretName] = value;
1375
1507
  process.env[secretName] = value;