@huaweidevtools/aishell-dsh-client-credentials 0.0.1-beta.5 → 0.0.1-beta.7

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/lib/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { createCredentialsStore } from "@huaweidevtools/aishell-dsh-credentials-store";
2
2
  import { clearCredentials, hasStoredPair, readStoredPair, writeHuaweiCloud } from "@huaweidevtools/aishell-dsh-credentials-store/accounts";
3
3
  import { verifyCredentials } from "@huaweidevtools/aishell-dsh-credentials-store/verify";
4
+ import { createServer } from "node:http";
4
5
 
5
6
  //#region ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.5/node_modules/@deepseek-ai/cosmokit/lib/index.js
6
7
  /** Return true when a value is `null` or `undefined`. */
@@ -900,8 +901,6 @@ defineMethod("transform", [
900
901
  const AUTH_TOOL_NAME = "aishell__auth";
901
902
  /** Region used to route the verification call; IAM is global, see the module note. */
902
903
  const VERIFY_REGION$1 = "cn-north-4";
903
- /** Per-call budget. IAM answers in well under a second when healthy. */
904
- const AUTH_TIMEOUT_MS = 3e4;
905
904
  /**
906
905
  * The JSON Schema for `auth`'s parameters: none.
907
906
  *
@@ -923,7 +922,7 @@ function registerAuthTool(ctx, store, deps) {
923
922
  ctx.inject(["tools"], (scope) => {
924
923
  const dispose = scope.tools.register({
925
924
  name: AUTH_TOOL_NAME,
926
- description: "Verify the stored Huawei Cloud credentials and report the account: its id and name, and every project visible to it (a project's name is a region; its id is what a region-scoped API needs).",
925
+ description: "Authenticate with Huawei Cloud IAM, then report the account: its id and name, and every project visible to it (a project's name is a region; its id is what a region-scoped API needs). Opens the credential form and waits for the user to finish — it does not return until they have authenticated or cancelled.",
927
926
  parameters: AUTH_PARAMETERS,
928
927
  output: {
929
928
  schema: {
@@ -961,7 +960,6 @@ function registerAuthTool(ctx, store, deps) {
961
960
  },
962
961
  render: (_args, value) => renderAuth(value)
963
962
  },
964
- timeoutMs: AUTH_TIMEOUT_MS,
965
963
  async execute(_args, exec) {
966
964
  return await runAuth(store, deps, sessionOf(exec), exec.signal);
967
965
  }
@@ -1179,6 +1177,893 @@ function encodeRequest(request) {
1179
1177
  return JSON.stringify(request);
1180
1178
  }
1181
1179
 
1180
+ //#endregion
1181
+ //#region src/login-status.ts
1182
+ /**
1183
+ * The vocabulary the two halves share about a browser login in progress.
1184
+ *
1185
+ * ## Why it is its own module
1186
+ *
1187
+ * Both halves need these names and neither owns them: the host writes the
1188
+ * outcome into the settings document, the browser half reads it and drives the
1189
+ * form the login opens in. A module the two import is the only place the
1190
+ * contract can live without one half depending on the other's internals —
1191
+ * the same reasoning `../form-request.ts` follows for the credential form.
1192
+ *
1193
+ * ## What travels, and what does not
1194
+ *
1195
+ * A login's outcome is a kind and, at most, an account name or a message. No
1196
+ * credential ever crosses this channel in either direction: the credential
1197
+ * arrives at a loopback socket the host owns, is verified there, and is stored
1198
+ * there. The browser half learns only that it worked, and as whom.
1199
+ *
1200
+ * @module @huaweidevtools/aishell-dsh-client-credentials/login-status
1201
+ */
1202
+ /** Field of this entry's config carrying the last login's outcome. */
1203
+ const LOGIN_OUTCOME_FIELD = "loginOutcome";
1204
+ /**
1205
+ * Header the reachability probe sends, to force a CORS preflight.
1206
+ *
1207
+ * Any non-safelisted header would do it; this one names why. Declared here
1208
+ * because both halves need the same string and neither owns it: the browser
1209
+ * half sends it, the host's listener must allow it in its preflight answer,
1210
+ * and a mismatch between the two is a probe that fails on a deployment that
1211
+ * would actually work — the entry hidden for no reason.
1212
+ */
1213
+ const PROBE_HEADER = "x-aishell-probe";
1214
+ /**
1215
+ * Serialize an outcome for the settings document.
1216
+ *
1217
+ * @param outcome - the outcome, or `undefined` to clear the field.
1218
+ * @returns the encoded value, or `''` to clear it.
1219
+ */
1220
+ function encodeOutcome(outcome) {
1221
+ return outcome === void 0 ? "" : JSON.stringify(outcome);
1222
+ }
1223
+
1224
+ //#endregion
1225
+ //#region src/out-of-band/contract.ts
1226
+ /**
1227
+ * The aishell-auth contract, as this plugin consumes it.
1228
+ *
1229
+ * ## What this module is
1230
+ *
1231
+ * A client for one stateless service that answers a single question: *where
1232
+ * should the browser go to sign in, and how does the credential come back?*
1233
+ * It stores nothing, holds no credential, and has no user system — the cloud
1234
+ * posts the credential straight to the caller.
1235
+ *
1236
+ * ## Why the contract is read, not hardcoded
1237
+ *
1238
+ * Every quirk of the cloud's callback is in the response: the listen path, the
1239
+ * accepted origins, whether a correlation string exists, what to do with the
1240
+ * payload. The service's own README says the point is that the caller "does
1241
+ * not need to hardcode anything provider-specific" — so this module hardcodes
1242
+ * none of it either. That is what makes a second provider a config change here
1243
+ * rather than a rewrite, and it is why the types below mirror the wire exactly
1244
+ * instead of modelling what Huawei happens to do today.
1245
+ *
1246
+ * ## Why field mapping is schema-driven
1247
+ *
1248
+ * `credential_schema` names the payload fields per provider. Mapping by those
1249
+ * names rather than by literal keys means a provider that calls its fields
1250
+ * something else still lands in the right store slots, and a provider that
1251
+ * renames one is a server-side change the caller follows for free.
1252
+ *
1253
+ * ## No exception, after all
1254
+ *
1255
+ * Private Network Access is in the contract as
1256
+ * `requires_private_network_access`: a browser on a public origin reaching
1257
+ * loopback sends a preflight carrying `Access-Control-Request-Private-Network`,
1258
+ * and a response without the matching allow header makes it drop the real
1259
+ * request — invisibly, in production only, with no error anywhere. The
1260
+ * contract carries that fact now, so this module hardcodes nothing about it.
1261
+ * See `./listener.ts` for how the flag and the browser's own request header
1262
+ * are combined.
1263
+ *
1264
+ * @module @huaweidevtools/aishell-dsh-client-credentials/out-of-band/contract
1265
+ */
1266
+ /**
1267
+ * Base URL of the login-dispatch service.
1268
+ *
1269
+ * A constant rather than a setting: it identifies one deployment of a shared
1270
+ * service, the same way a cloud endpoint would, and every caller of this
1271
+ * plugin in an organisation points at the same one. A deployment that needs a
1272
+ * different address is a code change here, which is the honest representation
1273
+ * — this is not something an end user picks.
1274
+ */
1275
+ const AUTH_SERVICE_BASE = "https://public.aishell.openbuildlab.com";
1276
+ /**
1277
+ * A response this client could not use.
1278
+ *
1279
+ * Its own type so a caller can tell "the service said no" from "the network
1280
+ * failed": both mean the browser-login entry is unavailable, but only the
1281
+ * first is worth logging with the service's own words.
1282
+ */
1283
+ var AuthContractError = class extends Error {
1284
+ constructor(..._args) {
1285
+ super(..._args);
1286
+ this.name = "AuthContractError";
1287
+ }
1288
+ };
1289
+ /**
1290
+ * Read one JSON response, failing with the service's own message.
1291
+ *
1292
+ * The service answers errors as `{ error_code, error_msg }` — a shape shared
1293
+ * across this family of services — and the message is worth surfacing: it
1294
+ * distinguishes "this provider does not exist" from "this redirect_uri is not
1295
+ * acceptable", which are different problems with the same status class.
1296
+ *
1297
+ * @param response - the response to read.
1298
+ * @param what - what was being requested, for the fallback message.
1299
+ * @throws {AuthContractError} on a non-2xx status or an unreadable body.
1300
+ */
1301
+ async function readJson(response, what) {
1302
+ if (!response.ok) {
1303
+ let detail = `HTTP ${String(response.status)}`;
1304
+ try {
1305
+ const body = await response.json();
1306
+ const message = typeof body.error_msg === "string" && body.error_msg !== "" ? body.error_msg : void 0;
1307
+ const code = typeof body.error_code === "string" ? body.error_code : void 0;
1308
+ if (message !== void 0) detail = code === void 0 ? message : `${message} (${code})`;
1309
+ } catch {}
1310
+ throw new AuthContractError(`${what} failed: ${detail}`);
1311
+ }
1312
+ try {
1313
+ return await response.json();
1314
+ } catch {
1315
+ throw new AuthContractError(`${what} returned a body that is not JSON.`);
1316
+ }
1317
+ }
1318
+ /** Narrow the service's answer to the shape this client is willing to act on. */
1319
+ function assertLoginTarget(value) {
1320
+ const callback = value.callback;
1321
+ if (typeof value.login_url !== "string" || value.login_url === "") throw new AuthContractError("The login service returned no login_url.");
1322
+ if (callback === null || typeof callback !== "object") throw new AuthContractError("The login service returned no callback plan.");
1323
+ if (typeof callback.address !== "string" || typeof callback.path !== "string") throw new AuthContractError("The login service returned an incomplete callback plan.");
1324
+ if (value.delivery !== "out_of_band") throw new AuthContractError(`The login service offered delivery "${value.delivery}", which this plugin cannot complete.`);
1325
+ return value;
1326
+ }
1327
+ /**
1328
+ * List the providers the service can dispatch for.
1329
+ *
1330
+ * @param deps - transport overrides.
1331
+ * @returns every provider, in the service's order.
1332
+ * @throws {AuthContractError} when the service is unreachable or answers unusably.
1333
+ */
1334
+ async function listProviders(deps = {}) {
1335
+ const doFetch = deps.fetch ?? fetch;
1336
+ const base = deps.base ?? AUTH_SERVICE_BASE;
1337
+ let response;
1338
+ try {
1339
+ response = await doFetch(`${base}/v1/providers`);
1340
+ } catch (error) {
1341
+ throw new AuthContractError(`Could not reach the login service at ${base}: ${error instanceof Error ? error.message : String(error)}`);
1342
+ }
1343
+ const body = await readJson(response, "Listing login providers");
1344
+ return body.providers ?? [];
1345
+ }
1346
+ /**
1347
+ * Find one provider by id.
1348
+ *
1349
+ * @param providerId - the provider to look for.
1350
+ * @param deps - transport overrides.
1351
+ * @returns the provider, or `undefined` when the service does not offer it.
1352
+ * @throws {AuthContractError} when the service is unreachable or answers unusably.
1353
+ */
1354
+ async function findProvider(providerId, deps = {}) {
1355
+ const providers = await listProviders(deps);
1356
+ return providers.find((provider) => provider.id === providerId);
1357
+ }
1358
+ /**
1359
+ * Ask where the browser should go for one provider.
1360
+ *
1361
+ * @param providerId - the provider to sign in with.
1362
+ * @param redirectUri - the address the caller will listen on. Its host must be
1363
+ * loopback and its port explicit; a provider may reject anything else, and
1364
+ * the service reports that as a `400` rather than silently adjusting it.
1365
+ * @param deps - transport overrides.
1366
+ * @returns the browser URL and the callback plan to honour.
1367
+ * @throws {AuthContractError} when the service is unreachable, rejects the
1368
+ * redirect URI, or answers unusably.
1369
+ */
1370
+ async function requestLogin(providerId, redirectUri, deps = {}) {
1371
+ const doFetch = deps.fetch ?? fetch;
1372
+ const base = deps.base ?? AUTH_SERVICE_BASE;
1373
+ const url = `${base}/v1/login?provider=${encodeURIComponent(providerId)}&redirect_uri=${encodeURIComponent(redirectUri)}`;
1374
+ let response;
1375
+ try {
1376
+ response = await doFetch(url);
1377
+ } catch (error) {
1378
+ throw new AuthContractError(`Could not reach the login service at ${base}: ${error instanceof Error ? error.message : String(error)}`);
1379
+ }
1380
+ return assertLoginTarget(await readJson(response, `Starting a ${providerId} login`));
1381
+ }
1382
+ /**
1383
+ * Apply a provider's `credential_schema` to a callback payload.
1384
+ *
1385
+ * The schema maps a payload key to a type; this pulls the string values out
1386
+ * under the names the store uses. A payload missing a field the schema
1387
+ * promises is a malformed callback, not a credential — returning `undefined`
1388
+ * lets the caller treat it as "nothing arrived" instead of storing half a
1389
+ * pair, which is the failure the store's single-record design exists to
1390
+ * prevent.
1391
+ *
1392
+ * A `securitytoken` absent from both the schema and the payload is ordinary —
1393
+ * a permanent key has none — so it is optional even though the schema lists
1394
+ * it.
1395
+ *
1396
+ * @param schema - the provider's `credential_schema`.
1397
+ * @param payload - the decoded callback body.
1398
+ * @returns the credential under this plugin's names, or `undefined` when the
1399
+ * payload does not satisfy the schema.
1400
+ */
1401
+ function mapCredential(schema, payload) {
1402
+ /** The schema key whose name marks it as each slot; providers differ, the roles do not. */
1403
+ const keyFor = (candidates) => Object.keys(schema).find((key) => candidates.includes(key.replace(/[_-]/g, "").toLowerCase()));
1404
+ const accessKey = keyFor([
1405
+ "access",
1406
+ "accesskey",
1407
+ "accesskeyid",
1408
+ "ak"
1409
+ ]);
1410
+ const secretKey = keyFor([
1411
+ "secret",
1412
+ "secretkey",
1413
+ "secretaccesskey",
1414
+ "sk"
1415
+ ]);
1416
+ const token = keyFor([
1417
+ "securitytoken",
1418
+ "token",
1419
+ "sessiontoken"
1420
+ ]);
1421
+ if (accessKey === void 0 || secretKey === void 0) return void 0;
1422
+ const ak = payload[accessKey];
1423
+ const sk = payload[secretKey];
1424
+ if (typeof ak !== "string" || ak === "" || typeof sk !== "string" || sk === "") return void 0;
1425
+ const rawToken = token === void 0 ? void 0 : payload[token];
1426
+ return {
1427
+ accessKeyId: ak,
1428
+ secretAccessKey: sk,
1429
+ ...typeof rawToken === "string" && rawToken !== "" ? { securityToken: rawToken } : {}
1430
+ };
1431
+ }
1432
+
1433
+ //#endregion
1434
+ //#region src/out-of-band/listener.ts
1435
+ /** Largest callback body accepted. A credential is a few fields; 64 KiB is generous. */
1436
+ const MAX_CALLBACK_BYTES = 64 * 1024;
1437
+ /** Header a browser sends on the preflight that precedes a loopback request. */
1438
+ const PNA_REQUEST_HEADER = "access-control-request-private-network";
1439
+ /** Query parameter carrying the probe nonce. */
1440
+ const PROBE_NONCE_PARAM = "n";
1441
+ /**
1442
+ * Whether an `Origin` matches an allowed origin exactly.
1443
+ *
1444
+ * Exact comparison, deliberately: a suffix or prefix rule would admit
1445
+ * `https://<allowed>.evil.com` and `https://evil-<allowed>`, and a
1446
+ * case-insensitive rule would admit a spelling the browser never sends. The
1447
+ * service's reference client makes the same choice for the same reason.
1448
+ *
1449
+ * @param allowed - the plan's list.
1450
+ * @param origin - the request's `Origin`, if any.
1451
+ * @returns the matched origin to echo, or `undefined` when nothing matched.
1452
+ */
1453
+ function matchOrigin(allowed, origin) {
1454
+ if (origin === void 0) return void 0;
1455
+ return allowed.find((candidate) => candidate === origin);
1456
+ }
1457
+ /**
1458
+ * Read a request's single header value.
1459
+ *
1460
+ * Node delivers a repeated header as an array; a preflight never legitimately
1461
+ * repeats these, so an array is treated as absent rather than joined into
1462
+ * something that would not match.
1463
+ *
1464
+ * @param request - the incoming request.
1465
+ * @param name - lowercase header name.
1466
+ */
1467
+ function header(request, name$1) {
1468
+ const value = request.headers[name$1];
1469
+ return typeof value === "string" ? value : void 0;
1470
+ }
1471
+ /** The path portion of a request target, without its query. */
1472
+ function pathOf(request) {
1473
+ return (request.url ?? "").split("?")[0] ?? "";
1474
+ }
1475
+ /** The value of one query parameter in a request target. */
1476
+ function queryParam(request, name$1) {
1477
+ const query = (request.url ?? "").split("?")[1];
1478
+ if (query === void 0) return void 0;
1479
+ for (const pair of query.split("&")) {
1480
+ const [key, value] = pair.split("=");
1481
+ if (key === name$1) return value === void 0 ? void 0 : decodeURIComponent(value);
1482
+ }
1483
+ return void 0;
1484
+ }
1485
+ /**
1486
+ * Write a CORS preflight answer.
1487
+ *
1488
+ * @param response - the response to write.
1489
+ * @param origin - the matched origin to echo.
1490
+ * @param allowMethods - methods to advertise.
1491
+ * @param allowHeaders - request headers to advertise, when any.
1492
+ * @param allowPrivateNetwork - whether the plan says the cloud's post is a
1493
+ * private-network request. Both this and the browser's own request header
1494
+ * must hold before the allow header is written.
1495
+ * @param request - the preflight, for its PNA request header.
1496
+ */
1497
+ function writePreflight(response, origin, allowMethods, allowHeaders, allowPrivateNetwork, request) {
1498
+ const headers = {
1499
+ "access-control-allow-origin": origin,
1500
+ vary: "Origin",
1501
+ "access-control-allow-methods": allowMethods
1502
+ };
1503
+ if (allowHeaders !== void 0) headers["access-control-allow-headers"] = allowHeaders;
1504
+ if (allowPrivateNetwork && header(request, PNA_REQUEST_HEADER) === "true") headers["access-control-allow-private-network"] = "true";
1505
+ response.writeHead(204, headers);
1506
+ response.end();
1507
+ }
1508
+ /**
1509
+ * Read a request body up to {@link MAX_CALLBACK_BYTES}.
1510
+ *
1511
+ * @param request - the request to drain.
1512
+ * @returns the decoded JSON object.
1513
+ * @throws when the body exceeds the bound, is not JSON, or is not an object.
1514
+ */
1515
+ function readPayload(request) {
1516
+ return new Promise((resolve, reject) => {
1517
+ const chunks = [];
1518
+ let size = 0;
1519
+ let settled = false;
1520
+ const fail = (error) => {
1521
+ if (settled) return;
1522
+ settled = true;
1523
+ reject(error);
1524
+ };
1525
+ request.on("error", fail);
1526
+ request.on("data", (chunk) => {
1527
+ if (settled) return;
1528
+ size += chunk.length;
1529
+ if (size > MAX_CALLBACK_BYTES) {
1530
+ fail(new Error("Callback body exceeded the accepted size."));
1531
+ request.pause();
1532
+ return;
1533
+ }
1534
+ chunks.push(chunk.toString("utf8"));
1535
+ });
1536
+ request.on("end", () => {
1537
+ if (settled) return;
1538
+ settled = true;
1539
+ try {
1540
+ const parsed = JSON.parse(chunks.join(""));
1541
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
1542
+ reject(new Error("Callback body is not a JSON object."));
1543
+ return;
1544
+ }
1545
+ resolve(parsed);
1546
+ } catch {
1547
+ reject(new Error("Callback body is not valid JSON."));
1548
+ }
1549
+ });
1550
+ });
1551
+ }
1552
+ /**
1553
+ * Bind a loopback port, without yet honouring any plan.
1554
+ *
1555
+ * Binds before anything else happens, deliberately: the port appears in the
1556
+ * redirect URI and is therefore not a secret, so a local process could take it
1557
+ * first. Binding early and handing the actual port back is what makes the
1558
+ * ordering correct by construction rather than by care.
1559
+ *
1560
+ * @returns the bound socket.
1561
+ * @throws when the port cannot be bound.
1562
+ */
1563
+ async function bindLoopback() {
1564
+ let handler;
1565
+ const server = createServer((request, response) => {
1566
+ if (handler === void 0) {
1567
+ response.writeHead(503);
1568
+ response.end();
1569
+ return;
1570
+ }
1571
+ handler(request, response);
1572
+ });
1573
+ await new Promise((resolve, reject) => {
1574
+ server.on("listening", () => {
1575
+ resolve();
1576
+ });
1577
+ server.on("error", (error) => {
1578
+ reject(error);
1579
+ });
1580
+ server.listen(0, "127.0.0.1");
1581
+ });
1582
+ const address = server.address();
1583
+ if (address === null || typeof address === "string") {
1584
+ server.close();
1585
+ throw new Error("The callback listener bound without an address.");
1586
+ }
1587
+ const bound = `127.0.0.1:${String(address.port)}`;
1588
+ let closed = false;
1589
+ return {
1590
+ host: "127.0.0.1",
1591
+ port: address.port,
1592
+ address: bound,
1593
+ close: () => {
1594
+ if (closed) return;
1595
+ closed = true;
1596
+ server.close();
1597
+ },
1598
+ serve: (plan, probe) => {
1599
+ const allowed = plan.allow_origins ?? [];
1600
+ const allowPrivateNetwork = plan.requires_private_network_access === true;
1601
+ let settleAccepted;
1602
+ let failAccepted;
1603
+ const accepted = new Promise((resolve, reject) => {
1604
+ settleAccepted = resolve;
1605
+ failAccepted = reject;
1606
+ });
1607
+ accepted.catch(() => {});
1608
+ let received = false;
1609
+ server.on("error", (error) => {
1610
+ failAccepted(error);
1611
+ });
1612
+ const close = () => {
1613
+ if (closed) return;
1614
+ closed = true;
1615
+ server.close();
1616
+ };
1617
+ /** Whether this request is the probe: right path, and the nonce it was given. */
1618
+ const isProbe = (request) => probe !== void 0 && pathOf(request) === probe.path && queryParam(request, PROBE_NONCE_PARAM) === probe.nonce;
1619
+ handler = (request, response) => {
1620
+ const method = request.method ?? "";
1621
+ if (probe !== void 0 && pathOf(request) === probe.path) {
1622
+ if (method === "OPTIONS") {
1623
+ const origin$2 = header(request, "origin");
1624
+ if (origin$2 === void 0 || !isProbe(request)) {
1625
+ response.writeHead(204);
1626
+ response.end();
1627
+ return;
1628
+ }
1629
+ writePreflight(response, origin$2, "GET, OPTIONS", PROBE_HEADER, allowPrivateNetwork, request);
1630
+ return;
1631
+ }
1632
+ if (method !== "GET" || !isProbe(request)) {
1633
+ response.writeHead(404);
1634
+ response.end();
1635
+ return;
1636
+ }
1637
+ const origin$1 = header(request, "origin");
1638
+ response.writeHead(204, origin$1 === void 0 ? {} : {
1639
+ "access-control-allow-origin": origin$1,
1640
+ vary: "Origin"
1641
+ });
1642
+ response.end();
1643
+ return;
1644
+ }
1645
+ if (method === "OPTIONS") {
1646
+ const origin$1 = matchOrigin(allowed, header(request, "origin"));
1647
+ if (origin$1 === void 0) {
1648
+ response.writeHead(204);
1649
+ response.end();
1650
+ return;
1651
+ }
1652
+ writePreflight(response, origin$1, `${plan.method}, OPTIONS`, plan.content_type === void 0 || plan.content_type === "" ? void 0 : "Content-Type", allowPrivateNetwork, request);
1653
+ return;
1654
+ }
1655
+ if (method !== plan.method) {
1656
+ response.writeHead(405);
1657
+ response.end();
1658
+ return;
1659
+ }
1660
+ if (pathOf(request) !== plan.path) {
1661
+ response.writeHead(404);
1662
+ response.end();
1663
+ return;
1664
+ }
1665
+ if (received) {
1666
+ response.writeHead(409);
1667
+ response.end();
1668
+ return;
1669
+ }
1670
+ const origin = matchOrigin(allowed, header(request, "origin"));
1671
+ if (allowed.length > 0 && origin === void 0) {
1672
+ response.writeHead(403);
1673
+ response.end();
1674
+ return;
1675
+ }
1676
+ readPayload(request).then((payload) => {
1677
+ if (closed || received) {
1678
+ response.writeHead(409);
1679
+ response.end();
1680
+ return;
1681
+ }
1682
+ received = true;
1683
+ const headers = {};
1684
+ if (origin !== void 0) {
1685
+ headers["access-control-allow-origin"] = origin;
1686
+ headers.vary = "Origin";
1687
+ }
1688
+ response.writeHead(200, headers);
1689
+ response.end();
1690
+ settleAccepted(payload);
1691
+ close();
1692
+ }, (error) => {
1693
+ if (closed) return;
1694
+ response.writeHead(400);
1695
+ response.end();
1696
+ failAccepted(error instanceof Error ? error : new Error(String(error)));
1697
+ });
1698
+ };
1699
+ return {
1700
+ address: bound,
1701
+ accepted,
1702
+ close
1703
+ };
1704
+ }
1705
+ };
1706
+ }
1707
+
1708
+ //#endregion
1709
+ //#region src/out-of-band/login.ts
1710
+ /** A value that cannot be guessed from the port alone. */
1711
+ function randomNonce() {
1712
+ const bytes = new Uint8Array(16);
1713
+ globalThis.crypto.getRandomValues(bytes);
1714
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
1715
+ }
1716
+ /**
1717
+ * How long to wait when the service does not say.
1718
+ *
1719
+ * The service's own contract states ten minutes; this matches it rather than
1720
+ * inventing a different number, so a response omitting the field behaves the
1721
+ * same as one carrying the documented value.
1722
+ */
1723
+ const DEFAULT_EXPIRES_SECONDS = 600;
1724
+ /**
1725
+ * Detach a timer from the event loop, when the runtime has that notion.
1726
+ *
1727
+ * Node's timer objects carry `unref`; a browser's are numbers. This package's
1728
+ * tsconfig compiles against the DOM signature (the browser half is most of
1729
+ * it), so the method is reached through a narrow cast rather than declared.
1730
+ *
1731
+ * @param timer - the timer handle, of whichever shape this runtime uses.
1732
+ */
1733
+ function unrefIfPossible(timer) {
1734
+ const candidate = timer;
1735
+ if (typeof candidate?.unref === "function") candidate.unref();
1736
+ }
1737
+ /**
1738
+ * Begin a browser login.
1739
+ *
1740
+ * Everything it returns is settled by the time it returns except `credential`,
1741
+ * which resolves when the person finishes signing in. The bind, the plan fetch
1742
+ * and the plan check all happen first, so a caller that gets a login back
1743
+ * knows there is a listener and somewhere to send the browser — a failure in
1744
+ * any of those throws instead.
1745
+ *
1746
+ * @param options - provider, verifier, and the probe path.
1747
+ * @returns the running login.
1748
+ * @throws {AuthContractError} when the port cannot be bound, the service
1749
+ * cannot be reached, or the plan names an address this machine is not on.
1750
+ */
1751
+ async function startBrowserLogin(options) {
1752
+ const { provider, verify, probePath, contract } = options;
1753
+ const bound = await bindLoopback();
1754
+ let cancelled = false;
1755
+ try {
1756
+ const target = await requestLogin(provider.id, `http://${bound.address}/`, contract);
1757
+ if (target.callback.address !== "" && target.callback.address !== bound.address) throw new AuthContractError(`The login service expects the callback at ${target.callback.address}, but this machine is listening on ${bound.address}. Refusing to wait for a callback that cannot arrive.`);
1758
+ const nonce = randomNonce();
1759
+ const listener = bound.serve(target.callback, {
1760
+ path: probePath,
1761
+ nonce
1762
+ });
1763
+ const probeUrl = `http://${bound.address}${probePath}?n=${nonce}`;
1764
+ const expiresInSeconds = target.expires_in > 0 ? target.expires_in : DEFAULT_EXPIRES_SECONDS;
1765
+ let settleCredential;
1766
+ let failCredential;
1767
+ const completion = Promise.withResolvers();
1768
+ settleCredential = completion.resolve;
1769
+ failCredential = completion.reject;
1770
+ const credential = completion.promise;
1771
+ credential.catch(() => {});
1772
+ (async () => {
1773
+ const expirySeconds = expiresInSeconds;
1774
+ let expiry;
1775
+ const expired = new Promise((resolve) => {
1776
+ expiry = setTimeout(() => {
1777
+ resolve("expired");
1778
+ }, expirySeconds * 1e3);
1779
+ unrefIfPossible(expiry);
1780
+ });
1781
+ let payload;
1782
+ try {
1783
+ const outcome = await Promise.race([listener.accepted.then((value) => ({
1784
+ kind: "accepted",
1785
+ value
1786
+ })), expired.then(() => ({ kind: "expired" }))]);
1787
+ if (outcome.kind === "expired") {
1788
+ bound.close();
1789
+ failCredential(new AuthContractError(`The browser sign-in was not completed within ${String(Math.round(expirySeconds / 60))} minutes. Open the credential form again to retry.`));
1790
+ return;
1791
+ }
1792
+ payload = outcome.value;
1793
+ } catch (error) {
1794
+ if (cancelled) return;
1795
+ failCredential(error instanceof Error ? error : new Error(String(error)));
1796
+ return;
1797
+ } finally {
1798
+ if (expiry !== void 0) clearTimeout(expiry);
1799
+ }
1800
+ if (cancelled) return;
1801
+ const mapped = mapCredential(provider.credential_schema, payload);
1802
+ if (mapped === void 0) {
1803
+ failCredential(new AuthContractError("The callback arrived but did not carry the fields the provider declared."));
1804
+ return;
1805
+ }
1806
+ let accountName;
1807
+ try {
1808
+ accountName = await verify(mapped);
1809
+ } catch (error) {
1810
+ failCredential(error instanceof Error ? error : new Error(String(error)));
1811
+ return;
1812
+ }
1813
+ if (cancelled) return;
1814
+ settleCredential({
1815
+ credential: mapped,
1816
+ accountName: typeof accountName === "string" ? accountName : ""
1817
+ });
1818
+ })();
1819
+ return {
1820
+ address: bound.address,
1821
+ probeUrl,
1822
+ loginUrl: target.login_url,
1823
+ expiresInSeconds,
1824
+ credential,
1825
+ cancel: () => {
1826
+ if (cancelled) return;
1827
+ cancelled = true;
1828
+ bound.close();
1829
+ failCredential(new AuthContractError("The browser login was cancelled."));
1830
+ }
1831
+ };
1832
+ } catch (error) {
1833
+ bound.close();
1834
+ throw error;
1835
+ }
1836
+ }
1837
+
1838
+ //#endregion
1839
+ //#region src/out-of-band/routes.ts
1840
+ /** Path the browser half posts to, to begin a login. */
1841
+ const LOGIN_START_PATH = "/api/aishell/credentials/login/start";
1842
+ /** Path the browser half posts to, to abandon a login. */
1843
+ const LOGIN_CANCEL_PATH = "/api/aishell/credentials/login/cancel";
1844
+ /**
1845
+ * Path the probe is served on, on the callback listener.
1846
+ *
1847
+ * On the listener rather than the host's `/api` route deliberately: the
1848
+ * question is whether the browser can reach *that* socket, so the probe has to
1849
+ * be answered there. Under a name no provider will use as a callback path —
1850
+ * the shipped provider posts to the root, so anything else is free.
1851
+ */
1852
+ const LOGIN_PROBE_PATH = "/__aishell_probe";
1853
+ /** One JSON response the browser half reads. */
1854
+ function json(body, status = 200) {
1855
+ return Response.json(body, {
1856
+ status,
1857
+ headers: { "cache-control": "no-store" }
1858
+ });
1859
+ }
1860
+ /** Read a JSON object body, or `{}` when it is absent or unreadable. */
1861
+ async function readBody(request) {
1862
+ try {
1863
+ const parsed = JSON.parse(await request.text());
1864
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
1865
+ } catch {
1866
+ return {};
1867
+ }
1868
+ }
1869
+ /** The login routes, bound to their collaborators. */
1870
+ function createLoginRoutes(deps) {
1871
+ const { findProvider: findProvider$1, begin, cancel, inProgress } = deps;
1872
+ return {
1873
+ start: async (request) => {
1874
+ if (inProgress()) return json({
1875
+ ok: false,
1876
+ error: "A browser login is already in progress."
1877
+ }, 409);
1878
+ const body = await readBody(request);
1879
+ const providerId = typeof body.provider === "string" && body.provider !== "" ? body.provider : "huaweicloud";
1880
+ let provider;
1881
+ try {
1882
+ provider = await findProvider$1(providerId);
1883
+ } catch (error) {
1884
+ return json({
1885
+ ok: false,
1886
+ error: error instanceof Error ? error.message : String(error)
1887
+ }, 503);
1888
+ }
1889
+ if (provider === void 0) return json({
1890
+ ok: false,
1891
+ error: `No login provider named ${providerId}.`
1892
+ }, 404);
1893
+ if (provider.delivery !== "out_of_band") return json({
1894
+ ok: false,
1895
+ error: `Provider ${providerId} uses "${provider.delivery}", which this plugin cannot complete.`
1896
+ }, 501);
1897
+ try {
1898
+ return json(await begin(provider));
1899
+ } catch (error) {
1900
+ return json({
1901
+ ok: false,
1902
+ error: error instanceof Error ? error.message : String(error)
1903
+ }, 502);
1904
+ }
1905
+ },
1906
+ cancel: () => {
1907
+ cancel();
1908
+ return Promise.resolve(json({ ok: true }));
1909
+ }
1910
+ };
1911
+ }
1912
+
1913
+ //#endregion
1914
+ //#region src/out-of-band/flow.ts
1915
+ /**
1916
+ * Build the flow.
1917
+ *
1918
+ * @param deps - the collaborators above.
1919
+ */
1920
+ function createLoginFlow(deps) {
1921
+ const { verify, store, recordError, recordOutcome, contract } = deps;
1922
+ /** The login in progress, if any. */
1923
+ let active;
1924
+ const finish = () => {
1925
+ active = void 0;
1926
+ };
1927
+ return {
1928
+ findProvider: (providerId) => findProvider(providerId, contract),
1929
+ inProgress: () => active !== void 0,
1930
+ cancel: () => {
1931
+ const login = active;
1932
+ finish();
1933
+ login?.cancel();
1934
+ recordOutcome(void 0);
1935
+ },
1936
+ begin: async (provider) => {
1937
+ if (active !== void 0) throw new AuthContractError("A browser login is already in progress.");
1938
+ const login = await startBrowserLogin({
1939
+ provider,
1940
+ probePath: LOGIN_PROBE_PATH,
1941
+ contract,
1942
+ verify
1943
+ });
1944
+ active = login;
1945
+ login.credential.then(async (result) => {
1946
+ if (active !== login) return;
1947
+ try {
1948
+ await store(result.credential);
1949
+ if (active !== login) return;
1950
+ finish();
1951
+ recordError("");
1952
+ recordOutcome({
1953
+ kind: "succeeded",
1954
+ accountName: result.accountName
1955
+ });
1956
+ } catch (error) {
1957
+ if (active !== login) return;
1958
+ finish();
1959
+ const message = `The credential verified, but storing it failed: ${error instanceof Error ? error.message : String(error)}`;
1960
+ recordError(message);
1961
+ recordOutcome({
1962
+ kind: "failed",
1963
+ error: message
1964
+ });
1965
+ }
1966
+ }, (error) => {
1967
+ if (active !== login) return;
1968
+ finish();
1969
+ const message = error instanceof Error ? error.message : String(error);
1970
+ recordError(message);
1971
+ recordOutcome({
1972
+ kind: "failed",
1973
+ error: message
1974
+ });
1975
+ });
1976
+ return {
1977
+ ok: true,
1978
+ loginUrl: login.loginUrl,
1979
+ probeUrl: login.probeUrl,
1980
+ providerName: provider.display_name,
1981
+ expiresInSeconds: login.expiresInSeconds
1982
+ };
1983
+ }
1984
+ };
1985
+ }
1986
+
1987
+ //#endregion
1988
+ //#region src/prefill.ts
1989
+ /**
1990
+ * Credential prefill from the environment.
1991
+ *
1992
+ * ## What this is for
1993
+ *
1994
+ * A machine that already carries `HW_ACCESS_KEY`, `HW_SECRET_KEY` and
1995
+ * `HW_SECURITY_TOKEN` in its environment has the credentials; the person just
1996
+ * has to move them into the store. Typing three values that are already on the
1997
+ * machine is work nobody should do, so the form opens with them filled in.
1998
+ *
1999
+ * ## Why the values come from the host
2000
+ *
2001
+ * The browser half cannot read `process.env` — it is browser code, and the
2002
+ * environment it would see is not the host's. So the host reads the variables
2003
+ * and serves them over a route the form calls before it renders its fields.
2004
+ *
2005
+ * ## Why that is acceptable here
2006
+ *
2007
+ * The values travel from the host to the page it is serving, over the same
2008
+ * authenticated channel and the same origin as the credential route the form
2009
+ * already posts to. Nothing new is exposed: a page that could read this route
2010
+ * could also submit that form.
2011
+ *
2012
+ * They are **not** written to the settings document, the session, or a log —
2013
+ * the route is the whole journey, and it is called once per form open.
2014
+ *
2015
+ * ## Why it returns nothing rather than a partial set
2016
+ *
2017
+ * A form filled with an access key and no secret key looks broken. Either the
2018
+ * environment carries a usable pair, or the form starts empty and the person
2019
+ * enters what they have. The token is separate: it is optional, and a lone
2020
+ * token with no pair is dropped for the same reason.
2021
+ *
2022
+ * ## Why the form says so
2023
+ *
2024
+ * The person did not type these values. Saying where they came from is what
2025
+ * lets them decide whether to trust them — a credential silently appearing in
2026
+ * a field is worse than an empty one.
2027
+ *
2028
+ * @module @huaweidevtools/aishell-dsh-client-credentials/prefill
2029
+ */
2030
+ /** Route the form reads prefills from. */
2031
+ const PREFILL_PATH = "/api/aishell/credentials/prefill";
2032
+ /** Variables read, in the order the form's fields appear. */
2033
+ const ACCESS_KEY_ENV = "HW_ACCESS_KEY";
2034
+ const SECRET_KEY_ENV = "HW_SECRET_KEY";
2035
+ const SECURITY_TOKEN_ENV = "HW_SECURITY_TOKEN";
2036
+ /**
2037
+ * Read an environment for a usable credential set.
2038
+ *
2039
+ * Pure, and the environment is a parameter: this package compiles without Node
2040
+ * type definitions (the browser half is most of it), so `process` is not in
2041
+ * scope and the caller supplies what to read.
2042
+ *
2043
+ * ## What these values do, and do not, do
2044
+ *
2045
+ * They fill the form's fields. The form still opens, every field is still
2046
+ * editable, and submitting or cancelling still works the way it always did —
2047
+ * the person saves the step of copying three values out of their shell, and
2048
+ * nothing else. In particular nothing is stored on their behalf: a prefill is a
2049
+ * starting point, not a credential.
2050
+ *
2051
+ * @param env - the environment to read.
2052
+ * @returns the pair (and token, when present), or `undefined` when either half
2053
+ * of the pair is missing.
2054
+ */
2055
+ function readEnvPrefill(env) {
2056
+ const ak = env[ACCESS_KEY_ENV];
2057
+ const sk = env[SECRET_KEY_ENV];
2058
+ if (ak === void 0 || ak === "" || sk === void 0 || sk === "") return void 0;
2059
+ const token = env[SECURITY_TOKEN_ENV];
2060
+ return {
2061
+ accessKeyId: ak,
2062
+ secretAccessKey: sk,
2063
+ ...token === void 0 || token === "" ? {} : { securityToken: token }
2064
+ };
2065
+ }
2066
+
1182
2067
  //#endregion
1183
2068
  //#region src/reconcile.ts
1184
2069
  /**
@@ -1265,6 +2150,20 @@ function readRequestToken(body) {
1265
2150
  }
1266
2151
  }
1267
2152
  /**
2153
+ * The host process's environment.
2154
+ *
2155
+ * Reached through a narrow cast rather than a typed `process`: this package
2156
+ * compiles without Node type definitions, so `process` is not in scope. The
2157
+ * host always has it; `{}` is the shape a build without one falls back to, and
2158
+ * an empty environment simply yields no prefill.
2159
+ *
2160
+ * @returns the environment, or an empty object when there is none.
2161
+ */
2162
+ function runtimeEnv() {
2163
+ const holder = globalThis;
2164
+ return holder.process?.env ?? {};
2165
+ }
2166
+ /**
1268
2167
  * Settings schema for this entry. Secrets are deliberately absent: they travel
1269
2168
  * over the credential route into the credential store, never through a
1270
2169
  * settings document.
@@ -1273,7 +2172,8 @@ const Config = Schema.object({
1273
2172
  credentialsStored: Schema.boolean().default(false).volatile(),
1274
2173
  accessKeyIdHint: Schema.string().default("").volatile(),
1275
2174
  lastError: Schema.string().default("").volatile(),
1276
- credentialFormRequest: Schema.string().default("").volatile()
2175
+ credentialFormRequest: Schema.string().default("").volatile(),
2176
+ loginOutcome: Schema.string().default("").volatile()
1277
2177
  });
1278
2178
  /** Route the browser half reads status from and saves credentials to. */
1279
2179
  const CREDENTIALS_PATH = "/api/aishell/credentials";
@@ -1566,6 +2466,78 @@ function apply(ctx, config) {
1566
2466
  return Response.json({ ok: true });
1567
2467
  }
1568
2468
  }), "aishell-credentials: cancel route");
2469
+ ctx.effect(() => ctx.connection.fetch.register({
2470
+ path: PREFILL_PATH,
2471
+ methods: ["GET"],
2472
+ requestBody: "buffered",
2473
+ fetch: () => Promise.resolve(Response.json(readEnvPrefill(runtimeEnv()) ?? {}, { headers: { "cache-control": "no-store" } }))
2474
+ }), "aishell-credentials: prefill route");
2475
+ /**
2476
+ * Announces that the stored credentials changed, so consumers that cached
2477
+ * something derived from them drop it.
2478
+ *
2479
+ * Declared before the flow because `recordOutcome` is where a successful
2480
+ * login is known, and that is the point at which the store has just changed.
2481
+ */
2482
+ const announceCredentialsChanged = () => {
2483
+ ctx.emit("aishell/credentials-updated");
2484
+ };
2485
+ const loginFlow = createLoginFlow({
2486
+ verify: async (credential) => {
2487
+ return await verifyCredentials$1(credential.accessKeyId, credential.secretAccessKey, credential.securityToken);
2488
+ },
2489
+ store: (credential) => {
2490
+ writeHuaweiCloud(store, {
2491
+ ak: credential.accessKeyId,
2492
+ sk: credential.secretAccessKey,
2493
+ ...credential.securityToken === void 0 ? {} : { securityToken: credential.securityToken }
2494
+ });
2495
+ return Promise.resolve();
2496
+ },
2497
+ recordError: (error) => {
2498
+ recordStatus([{
2499
+ op: "set",
2500
+ path: ["lastError"],
2501
+ value: error
2502
+ }]);
2503
+ },
2504
+ recordOutcome: (outcome) => {
2505
+ recordStatus([{
2506
+ op: "set",
2507
+ path: [LOGIN_OUTCOME_FIELD],
2508
+ value: encodeOutcome(outcome)
2509
+ }]);
2510
+ if (outcome?.kind === "succeeded") {
2511
+ announceCredentialsChanged();
2512
+ const pending = pendingForm;
2513
+ if (pending !== void 0) {
2514
+ pendingForm = void 0;
2515
+ pending.settle({ kind: "submitted" });
2516
+ }
2517
+ }
2518
+ }
2519
+ });
2520
+ const loginRoutes = createLoginRoutes({
2521
+ findProvider: loginFlow.findProvider,
2522
+ begin: loginFlow.begin,
2523
+ cancel: loginFlow.cancel,
2524
+ inProgress: loginFlow.inProgress
2525
+ });
2526
+ ctx.effect(() => ctx.connection.fetch.register({
2527
+ path: LOGIN_START_PATH,
2528
+ methods: ["POST"],
2529
+ requestBody: "buffered",
2530
+ fetch: loginRoutes.start
2531
+ }), "aishell-credentials: browser login start route");
2532
+ ctx.effect(() => ctx.connection.fetch.register({
2533
+ path: LOGIN_CANCEL_PATH,
2534
+ methods: ["POST"],
2535
+ requestBody: "buffered",
2536
+ fetch: loginRoutes.cancel
2537
+ }), "aishell-credentials: browser login cancel route");
2538
+ ctx.effect(() => () => {
2539
+ loginFlow.cancel();
2540
+ }, "aishell-credentials: browser login teardown");
1569
2541
  ctx.effect(() => ctx.connection.fetch.register({
1570
2542
  path: CLEAR_PATH,
1571
2543
  methods: ["POST"],