@huaweidevtools/aishell-dsh-client-credentials 0.0.1-beta.6 → 0.0.1-beta.8

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`. */
@@ -1005,9 +1006,17 @@ async function runAuth(store, deps, sessionId, signal) {
1005
1006
  for (let round = 0; round < MAX_FORM_ROUNDS; round += 1) {
1006
1007
  const pending = deps.requestForm(sessionId);
1007
1008
  if (pending === void 0) break;
1008
- const outcome = await raceCancellation(pending, signal);
1009
- if (outcome.kind === "cancelled") throw new CredentialEntryCancelled();
1010
- if (outcome.kind === "aborted") throw new CredentialEntryCancelled();
1009
+ let outcome;
1010
+ try {
1011
+ outcome = await raceCancellation(pending, signal);
1012
+ } catch (error) {
1013
+ deps.releaseForm();
1014
+ throw error;
1015
+ }
1016
+ if (outcome.kind === "cancelled" || outcome.kind === "aborted") {
1017
+ deps.releaseForm();
1018
+ throw new CredentialEntryCancelled();
1019
+ }
1011
1020
  const pair = readStoredPair(store);
1012
1021
  if (pair === void 0) continue;
1013
1022
  const result = await verifyCredentials(pair, { region: VERIFY_REGION$1 });
@@ -1018,15 +1027,28 @@ async function runAuth(store, deps, sessionId, signal) {
1018
1027
  /** How many form rounds one call will wait through before giving up. */
1019
1028
  const MAX_FORM_ROUNDS = 10;
1020
1029
  /**
1021
- * The person said no, and the call must end rather than ask again.
1030
+ * Credential entry ended without a credential.
1022
1031
  *
1023
- * Its own type so the message can be the whole instruction: a model reading a
1024
- * generic failure has every reason to retry, which is exactly wrong once the
1025
- * person has answered.
1032
+ * One message for both ways it ends — the person pressed cancel, or the turn
1033
+ * was stopped while the form was up. From the call's side they are the same
1034
+ * outcome: nothing was entered, so the call cannot continue.
1035
+ *
1036
+ * Bilingual, and stating only the fact. That is the shape `aishell-e2b` uses
1037
+ * for its blocked-call error: the reader is whichever language the session
1038
+ * runs in, and the message says what happened rather than what to do about it.
1039
+ *
1040
+ * ## Why no instruction follows
1041
+ *
1042
+ * An earlier version ended with "Do not call auth again until they say to."
1043
+ * The intent was to stop a model retrying in a loop, but what it produced was
1044
+ * a model that treated every later sentence from the person as a question
1045
+ * about permission — asked to look again, it narrated its uncertainty about
1046
+ * whether that counted as consent, and stalled instead of either retrying or
1047
+ * explaining. The fact is enough; what follows it is the model's judgement.
1026
1048
  */
1027
1049
  var CredentialEntryCancelled = class extends Error {
1028
1050
  constructor() {
1029
- super("The user cancelled credential entry. Stop here and tell them why Huawei Cloud authentication is needed for what they asked. Do not call auth again until they say to.");
1051
+ super("用户取消了认证流程。 / The user cancelled the authentication flow.");
1030
1052
  this.name = "CredentialEntryCancelled";
1031
1053
  }
1032
1054
  };
@@ -1176,6 +1198,813 @@ function encodeRequest(request) {
1176
1198
  return JSON.stringify(request);
1177
1199
  }
1178
1200
 
1201
+ //#endregion
1202
+ //#region src/login-status.ts
1203
+ /**
1204
+ * The vocabulary the two halves share about a browser login in progress.
1205
+ *
1206
+ * ## Why it is its own module
1207
+ *
1208
+ * Both halves need these names and neither owns them: the host writes the
1209
+ * outcome into the settings document, the browser half reads it and drives the
1210
+ * form the login opens in. A module the two import is the only place the
1211
+ * contract can live without one half depending on the other's internals —
1212
+ * the same reasoning `../form-request.ts` follows for the credential form.
1213
+ *
1214
+ * ## What travels, and what does not
1215
+ *
1216
+ * A login's outcome is a kind and, at most, an account name or a message. No
1217
+ * credential ever crosses this channel in either direction: the credential
1218
+ * arrives at a loopback socket the host owns, is verified there, and is stored
1219
+ * there. The browser half learns only that it worked, and as whom.
1220
+ *
1221
+ * @module @huaweidevtools/aishell-dsh-client-credentials/login-status
1222
+ */
1223
+ /** Field of this entry's config carrying the last login's outcome. */
1224
+ const LOGIN_OUTCOME_FIELD = "loginOutcome";
1225
+ /**
1226
+ * Header the reachability probe sends, to force a CORS preflight.
1227
+ *
1228
+ * Any non-safelisted header would do it; this one names why. Declared here
1229
+ * because both halves need the same string and neither owns it: the browser
1230
+ * half sends it, the host's listener must allow it in its preflight answer,
1231
+ * and a mismatch between the two is a probe that fails on a deployment that
1232
+ * would actually work — the entry hidden for no reason.
1233
+ */
1234
+ const PROBE_HEADER = "x-aishell-probe";
1235
+ /**
1236
+ * Serialize an outcome for the settings document.
1237
+ *
1238
+ * @param outcome - the outcome, or `undefined` to clear the field.
1239
+ * @returns the encoded value, or `''` to clear it.
1240
+ */
1241
+ function encodeOutcome(outcome) {
1242
+ return outcome === void 0 ? "" : JSON.stringify(outcome);
1243
+ }
1244
+
1245
+ //#endregion
1246
+ //#region src/out-of-band/contract.ts
1247
+ /**
1248
+ * The aishell-auth contract, as this plugin consumes it.
1249
+ *
1250
+ * ## What this module is
1251
+ *
1252
+ * A client for one stateless service that answers a single question: *where
1253
+ * should the browser go to sign in, and how does the credential come back?*
1254
+ * It stores nothing, holds no credential, and has no user system — the cloud
1255
+ * posts the credential straight to the caller.
1256
+ *
1257
+ * ## Why the contract is read, not hardcoded
1258
+ *
1259
+ * Every quirk of the cloud's callback is in the response: the listen path, the
1260
+ * accepted origins, whether a correlation string exists, what to do with the
1261
+ * payload. The service's own README says the point is that the caller "does
1262
+ * not need to hardcode anything provider-specific" — so this module hardcodes
1263
+ * none of it either. That is what makes a second provider a config change here
1264
+ * rather than a rewrite, and it is why the types below mirror the wire exactly
1265
+ * instead of modelling what Huawei happens to do today.
1266
+ *
1267
+ * ## Why field mapping is schema-driven
1268
+ *
1269
+ * `credential_schema` names the payload fields per provider. Mapping by those
1270
+ * names rather than by literal keys means a provider that calls its fields
1271
+ * something else still lands in the right store slots, and a provider that
1272
+ * renames one is a server-side change the caller follows for free.
1273
+ *
1274
+ * ## No exception, after all
1275
+ *
1276
+ * Private Network Access is in the contract as
1277
+ * `requires_private_network_access`: a browser on a public origin reaching
1278
+ * loopback sends a preflight carrying `Access-Control-Request-Private-Network`,
1279
+ * and a response without the matching allow header makes it drop the real
1280
+ * request — invisibly, in production only, with no error anywhere. The
1281
+ * contract carries that fact now, so this module hardcodes nothing about it.
1282
+ * See `./listener.ts` for how the flag and the browser's own request header
1283
+ * are combined.
1284
+ *
1285
+ * @module @huaweidevtools/aishell-dsh-client-credentials/out-of-band/contract
1286
+ */
1287
+ /**
1288
+ * Base URL of the login-dispatch service.
1289
+ *
1290
+ * A constant rather than a setting: it identifies one deployment of a shared
1291
+ * service, the same way a cloud endpoint would, and every caller of this
1292
+ * plugin in an organisation points at the same one. A deployment that needs a
1293
+ * different address is a code change here, which is the honest representation
1294
+ * — this is not something an end user picks.
1295
+ */
1296
+ const AUTH_SERVICE_BASE = "https://public.aishell.openbuildlab.com";
1297
+ /**
1298
+ * A response this client could not use.
1299
+ *
1300
+ * Its own type so a caller can tell "the service said no" from "the network
1301
+ * failed": both mean the browser-login entry is unavailable, but only the
1302
+ * first is worth logging with the service's own words.
1303
+ */
1304
+ var AuthContractError = class extends Error {
1305
+ constructor(..._args) {
1306
+ super(..._args);
1307
+ this.name = "AuthContractError";
1308
+ }
1309
+ };
1310
+ /**
1311
+ * Read one JSON response, failing with the service's own message.
1312
+ *
1313
+ * The service answers errors as `{ error_code, error_msg }` — a shape shared
1314
+ * across this family of services — and the message is worth surfacing: it
1315
+ * distinguishes "this provider does not exist" from "this redirect_uri is not
1316
+ * acceptable", which are different problems with the same status class.
1317
+ *
1318
+ * @param response - the response to read.
1319
+ * @param what - what was being requested, for the fallback message.
1320
+ * @throws {AuthContractError} on a non-2xx status or an unreadable body.
1321
+ */
1322
+ async function readJson(response, what) {
1323
+ if (!response.ok) {
1324
+ let detail = `HTTP ${String(response.status)}`;
1325
+ try {
1326
+ const body = await response.json();
1327
+ const message = typeof body.error_msg === "string" && body.error_msg !== "" ? body.error_msg : void 0;
1328
+ const code = typeof body.error_code === "string" ? body.error_code : void 0;
1329
+ if (message !== void 0) detail = code === void 0 ? message : `${message} (${code})`;
1330
+ } catch {}
1331
+ throw new AuthContractError(`${what} failed: ${detail}`);
1332
+ }
1333
+ try {
1334
+ return await response.json();
1335
+ } catch {
1336
+ throw new AuthContractError(`${what} returned a body that is not JSON.`);
1337
+ }
1338
+ }
1339
+ /** Narrow the service's answer to the shape this client is willing to act on. */
1340
+ function assertLoginTarget(value) {
1341
+ const callback = value.callback;
1342
+ if (typeof value.login_url !== "string" || value.login_url === "") throw new AuthContractError("The login service returned no login_url.");
1343
+ if (callback === null || typeof callback !== "object") throw new AuthContractError("The login service returned no callback plan.");
1344
+ if (typeof callback.address !== "string" || typeof callback.path !== "string") throw new AuthContractError("The login service returned an incomplete callback plan.");
1345
+ if (value.delivery !== "out_of_band") throw new AuthContractError(`The login service offered delivery "${value.delivery}", which this plugin cannot complete.`);
1346
+ return value;
1347
+ }
1348
+ /**
1349
+ * List the providers the service can dispatch for.
1350
+ *
1351
+ * @param deps - transport overrides.
1352
+ * @returns every provider, in the service's order.
1353
+ * @throws {AuthContractError} when the service is unreachable or answers unusably.
1354
+ */
1355
+ async function listProviders(deps = {}) {
1356
+ const doFetch = deps.fetch ?? fetch;
1357
+ const base = deps.base ?? AUTH_SERVICE_BASE;
1358
+ let response;
1359
+ try {
1360
+ response = await doFetch(`${base}/v1/providers`);
1361
+ } catch (error) {
1362
+ throw new AuthContractError(`Could not reach the login service at ${base}: ${error instanceof Error ? error.message : String(error)}`);
1363
+ }
1364
+ const body = await readJson(response, "Listing login providers");
1365
+ return body.providers ?? [];
1366
+ }
1367
+ /**
1368
+ * Find one provider by id.
1369
+ *
1370
+ * @param providerId - the provider to look for.
1371
+ * @param deps - transport overrides.
1372
+ * @returns the provider, or `undefined` when the service does not offer it.
1373
+ * @throws {AuthContractError} when the service is unreachable or answers unusably.
1374
+ */
1375
+ async function findProvider(providerId, deps = {}) {
1376
+ const providers = await listProviders(deps);
1377
+ return providers.find((provider) => provider.id === providerId);
1378
+ }
1379
+ /**
1380
+ * Ask where the browser should go for one provider.
1381
+ *
1382
+ * @param providerId - the provider to sign in with.
1383
+ * @param redirectUri - the address the caller will listen on. Its host must be
1384
+ * loopback and its port explicit; a provider may reject anything else, and
1385
+ * the service reports that as a `400` rather than silently adjusting it.
1386
+ * @param deps - transport overrides.
1387
+ * @returns the browser URL and the callback plan to honour.
1388
+ * @throws {AuthContractError} when the service is unreachable, rejects the
1389
+ * redirect URI, or answers unusably.
1390
+ */
1391
+ async function requestLogin(providerId, redirectUri, deps = {}) {
1392
+ const doFetch = deps.fetch ?? fetch;
1393
+ const base = deps.base ?? AUTH_SERVICE_BASE;
1394
+ const url = `${base}/v1/login?provider=${encodeURIComponent(providerId)}&redirect_uri=${encodeURIComponent(redirectUri)}`;
1395
+ let response;
1396
+ try {
1397
+ response = await doFetch(url);
1398
+ } catch (error) {
1399
+ throw new AuthContractError(`Could not reach the login service at ${base}: ${error instanceof Error ? error.message : String(error)}`);
1400
+ }
1401
+ return assertLoginTarget(await readJson(response, `Starting a ${providerId} login`));
1402
+ }
1403
+ /**
1404
+ * Apply a provider's `credential_schema` to a callback payload.
1405
+ *
1406
+ * The schema maps a payload key to a type; this pulls the string values out
1407
+ * under the names the store uses. A payload missing a field the schema
1408
+ * promises is a malformed callback, not a credential — returning `undefined`
1409
+ * lets the caller treat it as "nothing arrived" instead of storing half a
1410
+ * pair, which is the failure the store's single-record design exists to
1411
+ * prevent.
1412
+ *
1413
+ * A `securitytoken` absent from both the schema and the payload is ordinary —
1414
+ * a permanent key has none — so it is optional even though the schema lists
1415
+ * it.
1416
+ *
1417
+ * @param schema - the provider's `credential_schema`.
1418
+ * @param payload - the decoded callback body.
1419
+ * @returns the credential under this plugin's names, or `undefined` when the
1420
+ * payload does not satisfy the schema.
1421
+ */
1422
+ function mapCredential(schema, payload) {
1423
+ /** The schema key whose name marks it as each slot; providers differ, the roles do not. */
1424
+ const keyFor = (candidates) => Object.keys(schema).find((key) => candidates.includes(key.replace(/[_-]/g, "").toLowerCase()));
1425
+ const accessKey = keyFor([
1426
+ "access",
1427
+ "accesskey",
1428
+ "accesskeyid",
1429
+ "ak"
1430
+ ]);
1431
+ const secretKey = keyFor([
1432
+ "secret",
1433
+ "secretkey",
1434
+ "secretaccesskey",
1435
+ "sk"
1436
+ ]);
1437
+ const token = keyFor([
1438
+ "securitytoken",
1439
+ "token",
1440
+ "sessiontoken"
1441
+ ]);
1442
+ if (accessKey === void 0 || secretKey === void 0) return void 0;
1443
+ const ak = payload[accessKey];
1444
+ const sk = payload[secretKey];
1445
+ if (typeof ak !== "string" || ak === "" || typeof sk !== "string" || sk === "") return void 0;
1446
+ const rawToken = token === void 0 ? void 0 : payload[token];
1447
+ return {
1448
+ accessKeyId: ak,
1449
+ secretAccessKey: sk,
1450
+ ...typeof rawToken === "string" && rawToken !== "" ? { securityToken: rawToken } : {}
1451
+ };
1452
+ }
1453
+
1454
+ //#endregion
1455
+ //#region src/out-of-band/listener.ts
1456
+ /** Largest callback body accepted. A credential is a few fields; 64 KiB is generous. */
1457
+ const MAX_CALLBACK_BYTES = 64 * 1024;
1458
+ /** Header a browser sends on the preflight that precedes a loopback request. */
1459
+ const PNA_REQUEST_HEADER = "access-control-request-private-network";
1460
+ /** Query parameter carrying the probe nonce. */
1461
+ const PROBE_NONCE_PARAM = "n";
1462
+ /**
1463
+ * Whether an `Origin` matches an allowed origin exactly.
1464
+ *
1465
+ * Exact comparison, deliberately: a suffix or prefix rule would admit
1466
+ * `https://<allowed>.evil.com` and `https://evil-<allowed>`, and a
1467
+ * case-insensitive rule would admit a spelling the browser never sends. The
1468
+ * service's reference client makes the same choice for the same reason.
1469
+ *
1470
+ * @param allowed - the plan's list.
1471
+ * @param origin - the request's `Origin`, if any.
1472
+ * @returns the matched origin to echo, or `undefined` when nothing matched.
1473
+ */
1474
+ function matchOrigin(allowed, origin) {
1475
+ if (origin === void 0) return void 0;
1476
+ return allowed.find((candidate) => candidate === origin);
1477
+ }
1478
+ /**
1479
+ * Read a request's single header value.
1480
+ *
1481
+ * Node delivers a repeated header as an array; a preflight never legitimately
1482
+ * repeats these, so an array is treated as absent rather than joined into
1483
+ * something that would not match.
1484
+ *
1485
+ * @param request - the incoming request.
1486
+ * @param name - lowercase header name.
1487
+ */
1488
+ function header(request, name$1) {
1489
+ const value = request.headers[name$1];
1490
+ return typeof value === "string" ? value : void 0;
1491
+ }
1492
+ /** The path portion of a request target, without its query. */
1493
+ function pathOf(request) {
1494
+ return (request.url ?? "").split("?")[0] ?? "";
1495
+ }
1496
+ /** The value of one query parameter in a request target. */
1497
+ function queryParam(request, name$1) {
1498
+ const query = (request.url ?? "").split("?")[1];
1499
+ if (query === void 0) return void 0;
1500
+ for (const pair of query.split("&")) {
1501
+ const [key, value] = pair.split("=");
1502
+ if (key === name$1) return value === void 0 ? void 0 : decodeURIComponent(value);
1503
+ }
1504
+ return void 0;
1505
+ }
1506
+ /**
1507
+ * Write a CORS preflight answer.
1508
+ *
1509
+ * @param response - the response to write.
1510
+ * @param origin - the matched origin to echo.
1511
+ * @param allowMethods - methods to advertise.
1512
+ * @param allowHeaders - request headers to advertise, when any.
1513
+ * @param allowPrivateNetwork - whether the plan says the cloud's post is a
1514
+ * private-network request. Both this and the browser's own request header
1515
+ * must hold before the allow header is written.
1516
+ * @param request - the preflight, for its PNA request header.
1517
+ */
1518
+ function writePreflight(response, origin, allowMethods, allowHeaders, allowPrivateNetwork, request) {
1519
+ const headers = {
1520
+ "access-control-allow-origin": origin,
1521
+ vary: "Origin",
1522
+ "access-control-allow-methods": allowMethods
1523
+ };
1524
+ if (allowHeaders !== void 0) headers["access-control-allow-headers"] = allowHeaders;
1525
+ if (allowPrivateNetwork && header(request, PNA_REQUEST_HEADER) === "true") headers["access-control-allow-private-network"] = "true";
1526
+ response.writeHead(204, headers);
1527
+ response.end();
1528
+ }
1529
+ /**
1530
+ * Read a request body up to {@link MAX_CALLBACK_BYTES}.
1531
+ *
1532
+ * @param request - the request to drain.
1533
+ * @returns the decoded JSON object.
1534
+ * @throws when the body exceeds the bound, is not JSON, or is not an object.
1535
+ */
1536
+ function readPayload(request) {
1537
+ return new Promise((resolve, reject) => {
1538
+ const chunks = [];
1539
+ let size = 0;
1540
+ let settled = false;
1541
+ const fail = (error) => {
1542
+ if (settled) return;
1543
+ settled = true;
1544
+ reject(error);
1545
+ };
1546
+ request.on("error", fail);
1547
+ request.on("data", (chunk) => {
1548
+ if (settled) return;
1549
+ size += chunk.length;
1550
+ if (size > MAX_CALLBACK_BYTES) {
1551
+ fail(new Error("Callback body exceeded the accepted size."));
1552
+ request.pause();
1553
+ return;
1554
+ }
1555
+ chunks.push(chunk.toString("utf8"));
1556
+ });
1557
+ request.on("end", () => {
1558
+ if (settled) return;
1559
+ settled = true;
1560
+ try {
1561
+ const parsed = JSON.parse(chunks.join(""));
1562
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
1563
+ reject(new Error("Callback body is not a JSON object."));
1564
+ return;
1565
+ }
1566
+ resolve(parsed);
1567
+ } catch {
1568
+ reject(new Error("Callback body is not valid JSON."));
1569
+ }
1570
+ });
1571
+ });
1572
+ }
1573
+ /**
1574
+ * Bind a loopback port, without yet honouring any plan.
1575
+ *
1576
+ * Binds before anything else happens, deliberately: the port appears in the
1577
+ * redirect URI and is therefore not a secret, so a local process could take it
1578
+ * first. Binding early and handing the actual port back is what makes the
1579
+ * ordering correct by construction rather than by care.
1580
+ *
1581
+ * @returns the bound socket.
1582
+ * @throws when the port cannot be bound.
1583
+ */
1584
+ async function bindLoopback() {
1585
+ let handler;
1586
+ const server = createServer((request, response) => {
1587
+ if (handler === void 0) {
1588
+ response.writeHead(503);
1589
+ response.end();
1590
+ return;
1591
+ }
1592
+ handler(request, response);
1593
+ });
1594
+ await new Promise((resolve, reject) => {
1595
+ server.on("listening", () => {
1596
+ resolve();
1597
+ });
1598
+ server.on("error", (error) => {
1599
+ reject(error);
1600
+ });
1601
+ server.listen(0, "127.0.0.1");
1602
+ });
1603
+ const address = server.address();
1604
+ if (address === null || typeof address === "string") {
1605
+ server.close();
1606
+ throw new Error("The callback listener bound without an address.");
1607
+ }
1608
+ const bound = `127.0.0.1:${String(address.port)}`;
1609
+ let closed = false;
1610
+ return {
1611
+ host: "127.0.0.1",
1612
+ port: address.port,
1613
+ address: bound,
1614
+ close: () => {
1615
+ if (closed) return;
1616
+ closed = true;
1617
+ server.close();
1618
+ },
1619
+ serve: (plan, probe) => {
1620
+ const allowed = plan.allow_origins ?? [];
1621
+ const allowPrivateNetwork = plan.requires_private_network_access === true;
1622
+ let settleAccepted;
1623
+ let failAccepted;
1624
+ const accepted = new Promise((resolve, reject) => {
1625
+ settleAccepted = resolve;
1626
+ failAccepted = reject;
1627
+ });
1628
+ accepted.catch(() => {});
1629
+ let received = false;
1630
+ server.on("error", (error) => {
1631
+ failAccepted(error);
1632
+ });
1633
+ const close = () => {
1634
+ if (closed) return;
1635
+ closed = true;
1636
+ server.close();
1637
+ };
1638
+ /** Whether this request is the probe: right path, and the nonce it was given. */
1639
+ const isProbe = (request) => probe !== void 0 && pathOf(request) === probe.path && queryParam(request, PROBE_NONCE_PARAM) === probe.nonce;
1640
+ handler = (request, response) => {
1641
+ const method = request.method ?? "";
1642
+ if (probe !== void 0 && pathOf(request) === probe.path) {
1643
+ if (method === "OPTIONS") {
1644
+ const origin$2 = header(request, "origin");
1645
+ if (origin$2 === void 0 || !isProbe(request)) {
1646
+ response.writeHead(204);
1647
+ response.end();
1648
+ return;
1649
+ }
1650
+ writePreflight(response, origin$2, "GET, OPTIONS", PROBE_HEADER, allowPrivateNetwork, request);
1651
+ return;
1652
+ }
1653
+ if (method !== "GET" || !isProbe(request)) {
1654
+ response.writeHead(404);
1655
+ response.end();
1656
+ return;
1657
+ }
1658
+ const origin$1 = header(request, "origin");
1659
+ response.writeHead(204, origin$1 === void 0 ? {} : {
1660
+ "access-control-allow-origin": origin$1,
1661
+ vary: "Origin"
1662
+ });
1663
+ response.end();
1664
+ return;
1665
+ }
1666
+ if (method === "OPTIONS") {
1667
+ const origin$1 = matchOrigin(allowed, header(request, "origin"));
1668
+ if (origin$1 === void 0) {
1669
+ response.writeHead(204);
1670
+ response.end();
1671
+ return;
1672
+ }
1673
+ writePreflight(response, origin$1, `${plan.method}, OPTIONS`, plan.content_type === void 0 || plan.content_type === "" ? void 0 : "Content-Type", allowPrivateNetwork, request);
1674
+ return;
1675
+ }
1676
+ if (method !== plan.method) {
1677
+ response.writeHead(405);
1678
+ response.end();
1679
+ return;
1680
+ }
1681
+ if (pathOf(request) !== plan.path) {
1682
+ response.writeHead(404);
1683
+ response.end();
1684
+ return;
1685
+ }
1686
+ if (received) {
1687
+ response.writeHead(409);
1688
+ response.end();
1689
+ return;
1690
+ }
1691
+ const origin = matchOrigin(allowed, header(request, "origin"));
1692
+ if (allowed.length > 0 && origin === void 0) {
1693
+ response.writeHead(403);
1694
+ response.end();
1695
+ return;
1696
+ }
1697
+ readPayload(request).then((payload) => {
1698
+ if (closed || received) {
1699
+ response.writeHead(409);
1700
+ response.end();
1701
+ return;
1702
+ }
1703
+ received = true;
1704
+ const headers = {};
1705
+ if (origin !== void 0) {
1706
+ headers["access-control-allow-origin"] = origin;
1707
+ headers.vary = "Origin";
1708
+ }
1709
+ response.writeHead(200, headers);
1710
+ response.end();
1711
+ settleAccepted(payload);
1712
+ close();
1713
+ }, (error) => {
1714
+ if (closed) return;
1715
+ response.writeHead(400);
1716
+ response.end();
1717
+ failAccepted(error instanceof Error ? error : new Error(String(error)));
1718
+ });
1719
+ };
1720
+ return {
1721
+ address: bound,
1722
+ accepted,
1723
+ close
1724
+ };
1725
+ }
1726
+ };
1727
+ }
1728
+
1729
+ //#endregion
1730
+ //#region src/out-of-band/login.ts
1731
+ /** A value that cannot be guessed from the port alone. */
1732
+ function randomNonce() {
1733
+ const bytes = new Uint8Array(16);
1734
+ globalThis.crypto.getRandomValues(bytes);
1735
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
1736
+ }
1737
+ /**
1738
+ * How long to wait when the service does not say.
1739
+ *
1740
+ * The service's own contract states ten minutes; this matches it rather than
1741
+ * inventing a different number, so a response omitting the field behaves the
1742
+ * same as one carrying the documented value.
1743
+ */
1744
+ const DEFAULT_EXPIRES_SECONDS = 600;
1745
+ /**
1746
+ * Detach a timer from the event loop, when the runtime has that notion.
1747
+ *
1748
+ * Node's timer objects carry `unref`; a browser's are numbers. This package's
1749
+ * tsconfig compiles against the DOM signature (the browser half is most of
1750
+ * it), so the method is reached through a narrow cast rather than declared.
1751
+ *
1752
+ * @param timer - the timer handle, of whichever shape this runtime uses.
1753
+ */
1754
+ function unrefIfPossible(timer) {
1755
+ const candidate = timer;
1756
+ if (typeof candidate?.unref === "function") candidate.unref();
1757
+ }
1758
+ /**
1759
+ * Begin a browser login.
1760
+ *
1761
+ * Everything it returns is settled by the time it returns except `credential`,
1762
+ * which resolves when the person finishes signing in. The bind, the plan fetch
1763
+ * and the plan check all happen first, so a caller that gets a login back
1764
+ * knows there is a listener and somewhere to send the browser — a failure in
1765
+ * any of those throws instead.
1766
+ *
1767
+ * @param options - provider, verifier, and the probe path.
1768
+ * @returns the running login.
1769
+ * @throws {AuthContractError} when the port cannot be bound, the service
1770
+ * cannot be reached, or the plan names an address this machine is not on.
1771
+ */
1772
+ async function startBrowserLogin(options) {
1773
+ const { provider, verify, probePath, contract } = options;
1774
+ const bound = await bindLoopback();
1775
+ let cancelled = false;
1776
+ try {
1777
+ const target = await requestLogin(provider.id, `http://${bound.address}/`, contract);
1778
+ 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.`);
1779
+ const nonce = randomNonce();
1780
+ const listener = bound.serve(target.callback, {
1781
+ path: probePath,
1782
+ nonce
1783
+ });
1784
+ const probeUrl = `http://${bound.address}${probePath}?n=${nonce}`;
1785
+ const expiresInSeconds = target.expires_in > 0 ? target.expires_in : DEFAULT_EXPIRES_SECONDS;
1786
+ let settleCredential;
1787
+ let failCredential;
1788
+ const completion = Promise.withResolvers();
1789
+ settleCredential = completion.resolve;
1790
+ failCredential = completion.reject;
1791
+ const credential = completion.promise;
1792
+ credential.catch(() => {});
1793
+ (async () => {
1794
+ const expirySeconds = expiresInSeconds;
1795
+ let expiry;
1796
+ const expired = new Promise((resolve) => {
1797
+ expiry = setTimeout(() => {
1798
+ resolve("expired");
1799
+ }, expirySeconds * 1e3);
1800
+ unrefIfPossible(expiry);
1801
+ });
1802
+ let payload;
1803
+ try {
1804
+ const outcome = await Promise.race([listener.accepted.then((value) => ({
1805
+ kind: "accepted",
1806
+ value
1807
+ })), expired.then(() => ({ kind: "expired" }))]);
1808
+ if (outcome.kind === "expired") {
1809
+ bound.close();
1810
+ failCredential(new AuthContractError(`The browser sign-in was not completed within ${String(Math.round(expirySeconds / 60))} minutes. Open the credential form again to retry.`));
1811
+ return;
1812
+ }
1813
+ payload = outcome.value;
1814
+ } catch (error) {
1815
+ if (cancelled) return;
1816
+ failCredential(error instanceof Error ? error : new Error(String(error)));
1817
+ return;
1818
+ } finally {
1819
+ if (expiry !== void 0) clearTimeout(expiry);
1820
+ }
1821
+ if (cancelled) return;
1822
+ const mapped = mapCredential(provider.credential_schema, payload);
1823
+ if (mapped === void 0) {
1824
+ failCredential(new AuthContractError("The callback arrived but did not carry the fields the provider declared."));
1825
+ return;
1826
+ }
1827
+ let accountName;
1828
+ try {
1829
+ accountName = await verify(mapped);
1830
+ } catch (error) {
1831
+ failCredential(error instanceof Error ? error : new Error(String(error)));
1832
+ return;
1833
+ }
1834
+ if (cancelled) return;
1835
+ settleCredential({
1836
+ credential: mapped,
1837
+ accountName: typeof accountName === "string" ? accountName : ""
1838
+ });
1839
+ })();
1840
+ return {
1841
+ address: bound.address,
1842
+ probeUrl,
1843
+ loginUrl: target.login_url,
1844
+ expiresInSeconds,
1845
+ credential,
1846
+ cancel: () => {
1847
+ if (cancelled) return;
1848
+ cancelled = true;
1849
+ bound.close();
1850
+ failCredential(new AuthContractError("The browser login was cancelled."));
1851
+ }
1852
+ };
1853
+ } catch (error) {
1854
+ bound.close();
1855
+ throw error;
1856
+ }
1857
+ }
1858
+
1859
+ //#endregion
1860
+ //#region src/out-of-band/routes.ts
1861
+ /** Path the browser half posts to, to begin a login. */
1862
+ const LOGIN_START_PATH = "/api/aishell/credentials/login/start";
1863
+ /** Path the browser half posts to, to abandon a login. */
1864
+ const LOGIN_CANCEL_PATH = "/api/aishell/credentials/login/cancel";
1865
+ /**
1866
+ * Path the probe is served on, on the callback listener.
1867
+ *
1868
+ * On the listener rather than the host's `/api` route deliberately: the
1869
+ * question is whether the browser can reach *that* socket, so the probe has to
1870
+ * be answered there. Under a name no provider will use as a callback path —
1871
+ * the shipped provider posts to the root, so anything else is free.
1872
+ */
1873
+ const LOGIN_PROBE_PATH = "/__aishell_probe";
1874
+ /** One JSON response the browser half reads. */
1875
+ function json(body, status = 200) {
1876
+ return Response.json(body, {
1877
+ status,
1878
+ headers: { "cache-control": "no-store" }
1879
+ });
1880
+ }
1881
+ /** Read a JSON object body, or `{}` when it is absent or unreadable. */
1882
+ async function readBody(request) {
1883
+ try {
1884
+ const parsed = JSON.parse(await request.text());
1885
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
1886
+ } catch {
1887
+ return {};
1888
+ }
1889
+ }
1890
+ /** The login routes, bound to their collaborators. */
1891
+ function createLoginRoutes(deps) {
1892
+ const { findProvider: findProvider$1, begin, cancel, inProgress } = deps;
1893
+ return {
1894
+ start: async (request) => {
1895
+ if (inProgress()) return json({
1896
+ ok: false,
1897
+ error: "A browser login is already in progress."
1898
+ }, 409);
1899
+ const body = await readBody(request);
1900
+ const providerId = typeof body.provider === "string" && body.provider !== "" ? body.provider : "huaweicloud";
1901
+ let provider;
1902
+ try {
1903
+ provider = await findProvider$1(providerId);
1904
+ } catch (error) {
1905
+ return json({
1906
+ ok: false,
1907
+ error: error instanceof Error ? error.message : String(error)
1908
+ }, 503);
1909
+ }
1910
+ if (provider === void 0) return json({
1911
+ ok: false,
1912
+ error: `No login provider named ${providerId}.`
1913
+ }, 404);
1914
+ if (provider.delivery !== "out_of_band") return json({
1915
+ ok: false,
1916
+ error: `Provider ${providerId} uses "${provider.delivery}", which this plugin cannot complete.`
1917
+ }, 501);
1918
+ try {
1919
+ return json(await begin(provider));
1920
+ } catch (error) {
1921
+ return json({
1922
+ ok: false,
1923
+ error: error instanceof Error ? error.message : String(error)
1924
+ }, 502);
1925
+ }
1926
+ },
1927
+ cancel: () => {
1928
+ cancel();
1929
+ return Promise.resolve(json({ ok: true }));
1930
+ }
1931
+ };
1932
+ }
1933
+
1934
+ //#endregion
1935
+ //#region src/out-of-band/flow.ts
1936
+ /**
1937
+ * Build the flow.
1938
+ *
1939
+ * @param deps - the collaborators above.
1940
+ */
1941
+ function createLoginFlow(deps) {
1942
+ const { verify, store, recordError, recordOutcome, contract } = deps;
1943
+ /** The login in progress, if any. */
1944
+ let active;
1945
+ const finish = () => {
1946
+ active = void 0;
1947
+ };
1948
+ return {
1949
+ findProvider: (providerId) => findProvider(providerId, contract),
1950
+ inProgress: () => active !== void 0,
1951
+ cancel: () => {
1952
+ const login = active;
1953
+ finish();
1954
+ login?.cancel();
1955
+ recordOutcome(void 0);
1956
+ },
1957
+ begin: async (provider) => {
1958
+ if (active !== void 0) throw new AuthContractError("A browser login is already in progress.");
1959
+ const login = await startBrowserLogin({
1960
+ provider,
1961
+ probePath: LOGIN_PROBE_PATH,
1962
+ contract,
1963
+ verify
1964
+ });
1965
+ active = login;
1966
+ login.credential.then(async (result) => {
1967
+ if (active !== login) return;
1968
+ try {
1969
+ await store(result.credential);
1970
+ if (active !== login) return;
1971
+ finish();
1972
+ recordError("");
1973
+ recordOutcome({
1974
+ kind: "succeeded",
1975
+ accountName: result.accountName
1976
+ });
1977
+ } catch (error) {
1978
+ if (active !== login) return;
1979
+ finish();
1980
+ const message = `The credential verified, but storing it failed: ${error instanceof Error ? error.message : String(error)}`;
1981
+ recordError(message);
1982
+ recordOutcome({
1983
+ kind: "failed",
1984
+ error: message
1985
+ });
1986
+ }
1987
+ }, (error) => {
1988
+ if (active !== login) return;
1989
+ finish();
1990
+ const message = error instanceof Error ? error.message : String(error);
1991
+ recordError(message);
1992
+ recordOutcome({
1993
+ kind: "failed",
1994
+ error: message
1995
+ });
1996
+ });
1997
+ return {
1998
+ ok: true,
1999
+ loginUrl: login.loginUrl,
2000
+ probeUrl: login.probeUrl,
2001
+ providerName: provider.display_name,
2002
+ expiresInSeconds: login.expiresInSeconds
2003
+ };
2004
+ }
2005
+ };
2006
+ }
2007
+
1179
2008
  //#endregion
1180
2009
  //#region src/prefill.ts
1181
2010
  /**
@@ -1364,7 +2193,8 @@ const Config = Schema.object({
1364
2193
  credentialsStored: Schema.boolean().default(false).volatile(),
1365
2194
  accessKeyIdHint: Schema.string().default("").volatile(),
1366
2195
  lastError: Schema.string().default("").volatile(),
1367
- credentialFormRequest: Schema.string().default("").volatile()
2196
+ credentialFormRequest: Schema.string().default("").volatile(),
2197
+ loginOutcome: Schema.string().default("").volatile()
1368
2198
  });
1369
2199
  /** Route the browser half reads status from and saves credentials to. */
1370
2200
  const CREDENTIALS_PATH = "/api/aishell/credentials";
@@ -1663,6 +2493,72 @@ function apply(ctx, config) {
1663
2493
  requestBody: "buffered",
1664
2494
  fetch: () => Promise.resolve(Response.json(readEnvPrefill(runtimeEnv()) ?? {}, { headers: { "cache-control": "no-store" } }))
1665
2495
  }), "aishell-credentials: prefill route");
2496
+ /**
2497
+ * Announces that the stored credentials changed, so consumers that cached
2498
+ * something derived from them drop it.
2499
+ *
2500
+ * Declared before the flow because `recordOutcome` is where a successful
2501
+ * login is known, and that is the point at which the store has just changed.
2502
+ */
2503
+ const announceCredentialsChanged = () => {
2504
+ ctx.emit("aishell/credentials-updated");
2505
+ };
2506
+ const loginFlow = createLoginFlow({
2507
+ verify: async (credential) => {
2508
+ return await verifyCredentials$1(credential.accessKeyId, credential.secretAccessKey, credential.securityToken);
2509
+ },
2510
+ store: (credential) => {
2511
+ writeHuaweiCloud(store, {
2512
+ ak: credential.accessKeyId,
2513
+ sk: credential.secretAccessKey,
2514
+ ...credential.securityToken === void 0 ? {} : { securityToken: credential.securityToken }
2515
+ });
2516
+ return Promise.resolve();
2517
+ },
2518
+ recordError: (error) => {
2519
+ recordStatus([{
2520
+ op: "set",
2521
+ path: ["lastError"],
2522
+ value: error
2523
+ }]);
2524
+ },
2525
+ recordOutcome: (outcome) => {
2526
+ recordStatus([{
2527
+ op: "set",
2528
+ path: [LOGIN_OUTCOME_FIELD],
2529
+ value: encodeOutcome(outcome)
2530
+ }]);
2531
+ if (outcome?.kind === "succeeded") {
2532
+ announceCredentialsChanged();
2533
+ const pending = pendingForm;
2534
+ if (pending !== void 0) {
2535
+ pendingForm = void 0;
2536
+ pending.settle({ kind: "submitted" });
2537
+ }
2538
+ }
2539
+ }
2540
+ });
2541
+ const loginRoutes = createLoginRoutes({
2542
+ findProvider: loginFlow.findProvider,
2543
+ begin: loginFlow.begin,
2544
+ cancel: loginFlow.cancel,
2545
+ inProgress: loginFlow.inProgress
2546
+ });
2547
+ ctx.effect(() => ctx.connection.fetch.register({
2548
+ path: LOGIN_START_PATH,
2549
+ methods: ["POST"],
2550
+ requestBody: "buffered",
2551
+ fetch: loginRoutes.start
2552
+ }), "aishell-credentials: browser login start route");
2553
+ ctx.effect(() => ctx.connection.fetch.register({
2554
+ path: LOGIN_CANCEL_PATH,
2555
+ methods: ["POST"],
2556
+ requestBody: "buffered",
2557
+ fetch: loginRoutes.cancel
2558
+ }), "aishell-credentials: browser login cancel route");
2559
+ ctx.effect(() => () => {
2560
+ loginFlow.cancel();
2561
+ }, "aishell-credentials: browser login teardown");
1666
2562
  ctx.effect(() => ctx.connection.fetch.register({
1667
2563
  path: CLEAR_PATH,
1668
2564
  methods: ["POST"],
@@ -1675,21 +2571,34 @@ function apply(ctx, config) {
1675
2571
  reconciler.reconcile();
1676
2572
  const reconcileTimer = setInterval(reconciler.reconcile, 3e4);
1677
2573
  ctx.effect(() => () => clearInterval(reconcileTimer), "aishell-credentials: status reconcile timer");
1678
- registerAuthTool(ctx, store, { requestForm: (sessionId) => {
1679
- if (ns === void 0) return void 0;
1680
- if (pendingForm !== void 0) return pendingForm.outcome;
1681
- const pending = formRequest(sessionId);
1682
- pendingForm = pending;
1683
- ctx.settings.mutate(ns, [{
1684
- op: "set",
1685
- path: [FORM_REQUEST_FIELD],
1686
- value: pending.encoded
1687
- }]).catch((error) => {
1688
- ctx.logger.warn(error);
1689
- if (pendingForm === pending) pending.settle({ kind: "cancelled" });
1690
- });
1691
- return pending.outcome;
1692
- } });
2574
+ registerAuthTool(ctx, store, {
2575
+ requestForm: (sessionId) => {
2576
+ if (ns === void 0) return void 0;
2577
+ if (pendingForm !== void 0) return pendingForm.outcome;
2578
+ const pending = formRequest(sessionId);
2579
+ pendingForm = pending;
2580
+ ctx.settings.mutate(ns, [{
2581
+ op: "set",
2582
+ path: [FORM_REQUEST_FIELD],
2583
+ value: pending.encoded
2584
+ }]).catch((error) => {
2585
+ ctx.logger.warn(error);
2586
+ if (pendingForm === pending) {
2587
+ pendingForm = void 0;
2588
+ pending.settle({ kind: "cancelled" });
2589
+ }
2590
+ });
2591
+ return pending.outcome;
2592
+ },
2593
+ releaseForm: () => {
2594
+ const pending = pendingForm;
2595
+ if (pending !== void 0) {
2596
+ pendingForm = void 0;
2597
+ pending.settle({ kind: "cancelled" });
2598
+ }
2599
+ loginFlow.cancel();
2600
+ }
2601
+ });
1693
2602
  ctx.effect(() => ctx.settings.configure({ auto: false }, ctx.fiber));
1694
2603
  }
1695
2604