@huaweidevtools/aishell-dsh-client-credentials 0.0.7 → 0.0.9

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,5 +1,7 @@
1
1
  import { createCredentialsStore } from "@huaweidevtools/aishell-dsh-credentials-store";
2
- import { sign } from "@huaweidevtools/aishell-dsh-credentials-store/signer";
2
+ import { clearCredentials, hasStoredPair, readStoredPair, writeHuaweiCloud } from "@huaweidevtools/aishell-dsh-credentials-store/accounts";
3
+ import { verifyCredentials } from "@huaweidevtools/aishell-dsh-credentials-store/verify";
4
+ import { createServer } from "node:http";
3
5
 
4
6
  //#region ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.5/node_modules/@deepseek-ai/cosmokit/lib/index.js
5
7
  /** Return true when a value is `null` or `undefined`. */
@@ -893,6 +895,1296 @@ defineMethod("transform", [
893
895
  "preserve"
894
896
  ], ({ inner }, isInner) => inner.toString(isInner));
895
897
 
898
+ //#endregion
899
+ //#region src/auth-tool.ts
900
+ /** Model-facing name. Prefixed so it cannot collide with another cloud plugin. */
901
+ const AUTH_TOOL_NAME = "aishell__auth";
902
+ /** Region used to route the verification call; IAM is global, see the module note. */
903
+ const VERIFY_REGION$1 = "cn-north-4";
904
+ /**
905
+ * The JSON Schema for `auth`'s parameters: none.
906
+ *
907
+ * Declared as an empty object rather than omitted so the model reads "takes no
908
+ * arguments" explicitly, instead of inferring it from a missing field.
909
+ */
910
+ const AUTH_PARAMETERS = {
911
+ type: "object",
912
+ properties: {},
913
+ additionalProperties: false
914
+ };
915
+ /**
916
+ * Register the `auth` tool on the host's tool registry.
917
+ *
918
+ * @param ctx - host context.
919
+ * @param store - the credential store this package owns.
920
+ */
921
+ function registerAuthTool(ctx, store, deps) {
922
+ ctx.inject(["tools"], (scope) => {
923
+ const dispose = scope.tools.register({
924
+ name: AUTH_TOOL_NAME,
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.",
926
+ parameters: AUTH_PARAMETERS,
927
+ output: {
928
+ schema: {
929
+ type: "object",
930
+ properties: {
931
+ authenticated: { type: "boolean" },
932
+ account: {
933
+ type: "object",
934
+ properties: {
935
+ accountId: { type: "string" },
936
+ name: { type: "string" }
937
+ },
938
+ required: ["accountId", "name"]
939
+ },
940
+ projects: {
941
+ type: "array",
942
+ items: {
943
+ type: "object",
944
+ properties: {
945
+ id: { type: "string" },
946
+ name: { type: "string" },
947
+ description: { type: "string" }
948
+ },
949
+ required: ["id", "name"]
950
+ }
951
+ },
952
+ sts: { type: "boolean" }
953
+ },
954
+ required: [
955
+ "authenticated",
956
+ "account",
957
+ "projects",
958
+ "sts"
959
+ ]
960
+ },
961
+ render: (_args, value) => renderAuth(value)
962
+ },
963
+ async execute(_args, exec) {
964
+ return await runAuth(store, deps, sessionOf(exec), exec.signal);
965
+ }
966
+ });
967
+ return dispose;
968
+ });
969
+ }
970
+ /** The session a tool call runs under, from its execution context. */
971
+ function sessionOf(exec) {
972
+ return exec.agent?.session?.id;
973
+ }
974
+ /**
975
+ * Verify and describe the stored account.
976
+ *
977
+ * Four outcomes, and each one is a different instruction to the model:
978
+ *
979
+ * - **Verified.** The account and its projects.
980
+ * - **The person cancelled.** Terminal: stop, and say what the credential was
981
+ * needed for. Without this the model's only signal is the same failure it
982
+ * got before, and it retries until the turn ends — while the person has
983
+ * already said no.
984
+ * - **Nothing stored, or the stored pair was rejected.** Open the form and
985
+ * fail with the reason. The model calls again once the person is done.
986
+ *
987
+ * The last two both open the form, which is deliberate: a rejected credential is
988
+ * the case where the person most needs to see the form again, and Huawei's own
989
+ * reason is what tells them what to correct.
990
+ *
991
+ * @param store - the credential store to read.
992
+ * @param deps - host controls: open the form and wait for its answer.
993
+ * @param sessionId - the conversation to open the form in; `undefined` when the
994
+ * call carries no agent, in which case no form can be shown.
995
+ * @param signal - the call's cancellation; the way out of a form nobody answers.
996
+ * @returns the account, its projects, and whether the credentials are temporary.
997
+ * @throws when the person cancels, or when no form can be shown at all.
998
+ */
999
+ async function runAuth(store, deps, sessionId, signal) {
1000
+ const stored = readStoredPair(store);
1001
+ if (stored !== void 0) {
1002
+ const verified = await verifyCredentials(stored, { region: VERIFY_REGION$1 });
1003
+ if (verified.ok) return describeAccount(verified);
1004
+ }
1005
+ if (sessionId === void 0 || sessionId === "") throw new Error("Not authenticated with Huawei Cloud IAM, and this call is not attached to a conversation, so the credential form cannot be shown. Ask the user to open the credential form themselves, then call auth again.");
1006
+ for (let round = 0; round < MAX_FORM_ROUNDS; round += 1) {
1007
+ const pending = deps.requestForm(sessionId);
1008
+ if (pending === void 0) break;
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
+ }
1020
+ const pair = readStoredPair(store);
1021
+ if (pair === void 0) continue;
1022
+ const result = await verifyCredentials(pair, { region: VERIFY_REGION$1 });
1023
+ if (result.ok) return describeAccount(result);
1024
+ }
1025
+ throw new Error("Not authenticated with Huawei Cloud IAM. The credential form was shown but no usable credential was stored. Ask the user to authenticate, then call auth again.");
1026
+ }
1027
+ /** How many form rounds one call will wait through before giving up. */
1028
+ const MAX_FORM_ROUNDS = 10;
1029
+ /**
1030
+ * Credential entry ended without a credential.
1031
+ *
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.
1048
+ */
1049
+ var CredentialEntryCancelled = class extends Error {
1050
+ constructor() {
1051
+ super("用户取消了认证流程。 / The user cancelled the authentication flow.");
1052
+ this.name = "CredentialEntryCancelled";
1053
+ }
1054
+ };
1055
+ /**
1056
+ * Wait for the form's answer, or for the call to be cancelled.
1057
+ *
1058
+ * An abandoned call must not keep a promise alive: the turn is over, and nobody
1059
+ * is going to answer a prompt for it. `aborted` is a separate outcome from
1060
+ * `cancelled` in shape, and treated the same in effect — either way the person
1061
+ * did not supply a credential and asking again would be wrong.
1062
+ *
1063
+ * @param pending - the open form request.
1064
+ * @param signal - the call's cancellation, if any.
1065
+ */
1066
+ async function raceCancellation(pending, signal) {
1067
+ if (signal === void 0) return pending;
1068
+ if (signal.aborted) return { kind: "aborted" };
1069
+ return await new Promise((resolve) => {
1070
+ const onAbort = () => {
1071
+ resolve({ kind: "aborted" });
1072
+ };
1073
+ signal.addEventListener("abort", onAbort, { once: true });
1074
+ pending.then((outcome) => {
1075
+ signal.removeEventListener("abort", onAbort);
1076
+ resolve(outcome);
1077
+ });
1078
+ });
1079
+ }
1080
+ /** Project a successful verification into the tool's canonical value. */
1081
+ function describeAccount(result) {
1082
+ return {
1083
+ authenticated: true,
1084
+ account: {
1085
+ accountId: result.account.accountId,
1086
+ name: result.account.name
1087
+ },
1088
+ projects: result.account.projects.map((project) => ({
1089
+ id: project.id,
1090
+ name: project.name,
1091
+ ...project.description === void 0 ? {} : { description: project.description }
1092
+ })),
1093
+ sts: result.sts
1094
+ };
1095
+ }
1096
+ /**
1097
+ * The text the model reads.
1098
+ *
1099
+ * A short summary then the project table: the summary answers the question the
1100
+ * tool was called with, and the table is what the next call needs. The region
1101
+ * is deliberately absent — IAM does not verify it, so printing it would suggest
1102
+ * it had been checked.
1103
+ *
1104
+ * @param value - the verified account.
1105
+ */
1106
+ function renderAuth(value) {
1107
+ const projects = value.projects.length === 0 ? "No projects are visible to these credentials." : ["Project id region description", ...value.projects.map((project) => `${project.id.padEnd(36)} ${project.name.padEnd(14)} ${project.description ?? ""}`.trimEnd())].join("\n");
1108
+ const kind = value.sts ? "temporary (STS)" : "stored";
1109
+ return [{
1110
+ type: "text",
1111
+ text: `Authenticated with Huawei Cloud as ${value.account.name} (account id ${value.account.accountId}); using ${kind} credentials.\n\n` + projects
1112
+ }];
1113
+ }
1114
+
1115
+ //#endregion
1116
+ //#region src/form-request.ts
1117
+ /**
1118
+ * The credential form's Host-side control.
1119
+ *
1120
+ * ## What this is for
1121
+ *
1122
+ * `aishell__auth` needs credentials that are not there. It cannot collect them
1123
+ * — a credential a tool returns is a credential in the transcript — so it asks
1124
+ * for the form to be put on screen, the person fills it, and the model calls
1125
+ * `auth` again.
1126
+ *
1127
+ * ## Why the settings document carries the request
1128
+ *
1129
+ * The two halves live apart: the tool runs on the host, the form is browser
1130
+ * code. The host cannot reach the browser over the fetch channel — that channel
1131
+ * is browser→host only — so the request has to ride something the browser
1132
+ * already watches. The settings document is exactly that: the browser half
1133
+ * subscribes to this entry's config through `configForms`, and a volatile field
1134
+ * written by the host shows up there.
1135
+ *
1136
+ * The document carries **only** a request token and a session id. Never a
1137
+ * credential, never a verdict — those travel the other way, over the
1138
+ * credential route, and the browser never receives a stored secret at all.
1139
+ *
1140
+ * ## Why the token, not a boolean
1141
+ *
1142
+ * The browser has to tell "a new request" from "the request it already opened".
1143
+ * With a boolean, a second `auth` failure while the form is up would look
1144
+ * identical to the first and the form would not re-open after the person
1145
+ * cancelled it. The token changes on every request, and the browser compares it
1146
+ * to the last one it acted on.
1147
+ *
1148
+ * ## Why nothing is awaited
1149
+ *
1150
+ * The tool cannot wait for the person — a tool call has no way to be paused for
1151
+ * a human. So `auth` fails, the form appears, and the model calls again. That
1152
+ * round trip is the whole protocol, and it is why the failure message and the
1153
+ * form are worded as a pair.
1154
+ *
1155
+ * @module @huaweidevtools/aishell-dsh-client-credentials/form-request
1156
+ */
1157
+ /** Field of this entry's config that carries one pending request. */
1158
+ const FORM_REQUEST_FIELD = "credentialFormRequest";
1159
+ /**
1160
+ * Build a request for one session, minting its token.
1161
+ *
1162
+ * The token is minted here rather than by the caller so a request cannot be
1163
+ * recorded without one — the browser's "is this new?" test would then be
1164
+ * comparing against nothing, and the form would not reopen after a cancel.
1165
+ *
1166
+ * @param sessionId - the conversation the form should render in.
1167
+ * @returns the request, and its encoded form for the settings document.
1168
+ */
1169
+ function formRequest(sessionId) {
1170
+ nextToken += 1;
1171
+ const request = {
1172
+ token: `${Date.now().toString(36)}-${String(nextToken)}`,
1173
+ sessionId
1174
+ };
1175
+ const completion = Promise.withResolvers();
1176
+ return {
1177
+ request,
1178
+ encoded: encodeRequest(request),
1179
+ outcome: completion.promise,
1180
+ settle: (outcome) => {
1181
+ completion.resolve(outcome);
1182
+ }
1183
+ };
1184
+ }
1185
+ /** Source of tokens; module-scoped so it is per-host-process. */
1186
+ let nextToken = 0;
1187
+ /**
1188
+ * Serialize a request for the settings document.
1189
+ *
1190
+ * The document holds strings — a volatile `string` field is what the browser
1191
+ * half reads through `configForms` — so the request is JSON. Encoding rather
1192
+ * than reshaping the config into several fields keeps the request atomic: the
1193
+ * browser cannot observe a new token with an old session.
1194
+ *
1195
+ * @param request - the request to encode.
1196
+ */
1197
+ function encodeRequest(request) {
1198
+ return JSON.stringify(request);
1199
+ }
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 on the loopback fetch, the host's listener must allow it in
1231
+ * its preflight answer, and a mismatch between the two is a probe that fails
1232
+ * on a route that 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
+ * Borrow a loopback port, answer one probe, and give it back.
1464
+ *
1465
+ * ## What this is for
1466
+ *
1467
+ * The cloud posts a credential to `127.0.0.1` **as the browser's machine
1468
+ * resolves it**, so a browser login works only when that browser can reach a
1469
+ * listener on this host. Neither side can tell by looking — an SSH-forwarded
1470
+ * session makes a distant browser look local to the host and a distant host
1471
+ * look local to the page — so the page fetches a URL and the fetch is the
1472
+ * answer. A fetch that resolves means the page reached a socket here.
1473
+ *
1474
+ * ## How it ends
1475
+ *
1476
+ * Two ways, whichever comes first:
1477
+ *
1478
+ * - **Someone reaches it.** The response is written, and the socket closes
1479
+ * immediately after — the question has been answered, so the port has no
1480
+ * further use.
1481
+ * - **{@link PROBE_WINDOW_MS} passes.** Nobody came, which is itself an
1482
+ * answer (this browser cannot reach loopback), and the socket closes.
1483
+ *
1484
+ * Either way the port is held for seconds at most. A probe borrowed to ask one
1485
+ * question must not outlive the asking — a card left open would otherwise keep
1486
+ * a socket for the life of the page, which is what the earlier design did.
1487
+ *
1488
+ * ## Why the nonce
1489
+ *
1490
+ * The probe answers whatever origin asks, because the page's own origin is by
1491
+ * definition not one of the cloud's. That is only safe with a secret: without
1492
+ * one, any page that swept local ports would get an answer, making this a
1493
+ * fingerprinting beacon for the plugin's presence. A caller without the nonce
1494
+ * is answered exactly as an empty port would be.
1495
+ *
1496
+ * ## What the caller gets, and what it does not
1497
+ *
1498
+ * A URL and nothing else. The caller cannot observe the port closing — it
1499
+ * closes on its own, either on being reached or when the window runs out — and
1500
+ * a promise for that would be a handle no caller has a use for. Awaiting it
1501
+ * would also mean a route waiting up to the whole window before answering,
1502
+ * which is precisely what the page cannot afford.
1503
+ *
1504
+ * @param path - the path the probe is served on.
1505
+ * @returns the URL to hand the page.
1506
+ */
1507
+ async function probeLoopback(path) {
1508
+ const bound = await bindLoopback();
1509
+ const nonce = randomProbeNonce();
1510
+ const reachable = Promise.withResolvers();
1511
+ bound.serve(
1512
+ // A plan that matches nothing: this listener exists only for the probe, so
1513
+ // a callback arriving here is a stray and is refused by the path check.
1514
+ {
1515
+ address: bound.address,
1516
+ path: "\0",
1517
+ method: "POST",
1518
+ correlation: "none"
1519
+ },
1520
+ {
1521
+ path,
1522
+ nonce,
1523
+ onAnswered: () => {
1524
+ reachable.resolve(true);
1525
+ bound.close();
1526
+ }
1527
+ }
1528
+ );
1529
+ const timer = setTimeout(() => {
1530
+ reachable.resolve(false);
1531
+ bound.close();
1532
+ }, PROBE_WINDOW_MS);
1533
+ unrefIfPossible(timer);
1534
+ reachable.promise.then(() => {
1535
+ clearTimeout(timer);
1536
+ });
1537
+ return { probeUrl: `http://${bound.address}${path}?n=${nonce}` };
1538
+ }
1539
+ /**
1540
+ * Detach a timer from the event loop, when the runtime has that notion.
1541
+ *
1542
+ * Node's timer objects carry `unref`; a browser's are numbers. This package's
1543
+ * tsconfig compiles against the DOM signature (the browser half is most of
1544
+ * it), so the method is reached through a narrow cast rather than declared.
1545
+ *
1546
+ * Exported because the login's deadline needs the same treatment, and two
1547
+ * copies of a three-line cast is how they drift.
1548
+ *
1549
+ * @param timer - the timer handle, of whichever shape this runtime uses.
1550
+ */
1551
+ function unrefIfPossible(timer) {
1552
+ const candidate = timer;
1553
+ if (typeof candidate?.unref === "function") candidate.unref();
1554
+ }
1555
+ /**
1556
+ * How long a probe port is held.
1557
+ *
1558
+ * Generous for a request that takes under a millisecond when it works, because
1559
+ * the cost of the wait is a bound port and the cost of being too quick is
1560
+ * calling a working route unsupported. A page that is slow to get going —
1561
+ * a large bundle still parsing — still gets its answer.
1562
+ */
1563
+ const PROBE_WINDOW_MS = 3e4;
1564
+ /** A value that cannot be guessed from the port alone. */
1565
+ function randomProbeNonce() {
1566
+ const bytes = new Uint8Array(16);
1567
+ globalThis.crypto.getRandomValues(bytes);
1568
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
1569
+ }
1570
+ /**
1571
+ * Whether an `Origin` matches an allowed origin exactly.
1572
+ *
1573
+ * Exact comparison, deliberately: a suffix or prefix rule would admit
1574
+ * `https://<allowed>.evil.com` and `https://evil-<allowed>`, and a
1575
+ * case-insensitive rule would admit a spelling the browser never sends. The
1576
+ * service's reference client makes the same choice for the same reason.
1577
+ *
1578
+ * @param allowed - the plan's list.
1579
+ * @param origin - the request's `Origin`, if any.
1580
+ * @returns the matched origin to echo, or `undefined` when nothing matched.
1581
+ */
1582
+ function matchOrigin(allowed, origin) {
1583
+ if (origin === void 0) return void 0;
1584
+ return allowed.find((candidate) => candidate === origin);
1585
+ }
1586
+ /**
1587
+ * Read a request's single header value.
1588
+ *
1589
+ * Node delivers a repeated header as an array; a preflight never legitimately
1590
+ * repeats these, so an array is treated as absent rather than joined into
1591
+ * something that would not match.
1592
+ *
1593
+ * @param request - the incoming request.
1594
+ * @param name - lowercase header name.
1595
+ */
1596
+ function header(request, name$1) {
1597
+ const value = request.headers[name$1];
1598
+ return typeof value === "string" ? value : void 0;
1599
+ }
1600
+ /** The path portion of a request target, without its query. */
1601
+ function pathOf(request) {
1602
+ return (request.url ?? "").split("?")[0] ?? "";
1603
+ }
1604
+ /** The value of one query parameter in a request target. */
1605
+ function queryParam(request, name$1) {
1606
+ const query = (request.url ?? "").split("?")[1];
1607
+ if (query === void 0) return void 0;
1608
+ for (const pair of query.split("&")) {
1609
+ const [key, value] = pair.split("=");
1610
+ if (key === name$1) return value === void 0 ? void 0 : decodeURIComponent(value);
1611
+ }
1612
+ return void 0;
1613
+ }
1614
+ /**
1615
+ * Write a CORS preflight answer.
1616
+ *
1617
+ * @param response - the response to write.
1618
+ * @param origin - the matched origin to echo.
1619
+ * @param allowMethods - methods to advertise.
1620
+ * @param allowHeaders - request headers to advertise, when any.
1621
+ * @param allowPrivateNetwork - whether the plan says the cloud's post is a
1622
+ * private-network request. Both this and the browser's own request header
1623
+ * must hold before the allow header is written.
1624
+ * @param request - the preflight, for its PNA request header.
1625
+ */
1626
+ function writePreflight(response, origin, allowMethods, allowHeaders, allowPrivateNetwork, request) {
1627
+ const headers = {
1628
+ "access-control-allow-origin": origin,
1629
+ vary: "Origin",
1630
+ "access-control-allow-methods": allowMethods
1631
+ };
1632
+ if (allowHeaders !== void 0) headers["access-control-allow-headers"] = allowHeaders;
1633
+ if (allowPrivateNetwork && header(request, PNA_REQUEST_HEADER) === "true") headers["access-control-allow-private-network"] = "true";
1634
+ response.writeHead(204, headers);
1635
+ response.end();
1636
+ }
1637
+ /**
1638
+ * Read a request body up to {@link MAX_CALLBACK_BYTES}.
1639
+ *
1640
+ * @param request - the request to drain.
1641
+ * @returns the decoded JSON object.
1642
+ * @throws when the body exceeds the bound, is not JSON, or is not an object.
1643
+ */
1644
+ function readPayload(request) {
1645
+ return new Promise((resolve, reject) => {
1646
+ const chunks = [];
1647
+ let size = 0;
1648
+ let settled = false;
1649
+ const fail = (error) => {
1650
+ if (settled) return;
1651
+ settled = true;
1652
+ reject(error);
1653
+ };
1654
+ request.on("error", fail);
1655
+ request.on("data", (chunk) => {
1656
+ if (settled) return;
1657
+ size += chunk.length;
1658
+ if (size > MAX_CALLBACK_BYTES) {
1659
+ fail(new Error("Callback body exceeded the accepted size."));
1660
+ request.pause();
1661
+ return;
1662
+ }
1663
+ chunks.push(chunk.toString("utf8"));
1664
+ });
1665
+ request.on("end", () => {
1666
+ if (settled) return;
1667
+ settled = true;
1668
+ try {
1669
+ const parsed = JSON.parse(chunks.join(""));
1670
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
1671
+ reject(new Error("Callback body is not a JSON object."));
1672
+ return;
1673
+ }
1674
+ resolve(parsed);
1675
+ } catch {
1676
+ reject(new Error("Callback body is not valid JSON."));
1677
+ }
1678
+ });
1679
+ });
1680
+ }
1681
+ /**
1682
+ * Bind a loopback port, without yet honouring any plan.
1683
+ *
1684
+ * Binds before anything else happens, deliberately: the port appears in the
1685
+ * redirect URI and is therefore not a secret, so a local process could take it
1686
+ * first. Binding early and handing the actual port back is what makes the
1687
+ * ordering correct by construction rather than by care.
1688
+ *
1689
+ * @returns the bound socket.
1690
+ * @throws when the port cannot be bound.
1691
+ */
1692
+ async function bindLoopback() {
1693
+ let handler;
1694
+ const server = createServer((request, response) => {
1695
+ if (handler === void 0) {
1696
+ response.writeHead(503);
1697
+ response.end();
1698
+ return;
1699
+ }
1700
+ handler(request, response);
1701
+ });
1702
+ await new Promise((resolve, reject) => {
1703
+ server.on("listening", () => {
1704
+ resolve();
1705
+ });
1706
+ server.on("error", (error) => {
1707
+ reject(error);
1708
+ });
1709
+ server.listen(0, "127.0.0.1");
1710
+ });
1711
+ const address = server.address();
1712
+ if (address === null || typeof address === "string") {
1713
+ server.close();
1714
+ throw new Error("The callback listener bound without an address.");
1715
+ }
1716
+ const bound = `127.0.0.1:${String(address.port)}`;
1717
+ let closed = false;
1718
+ return {
1719
+ host: "127.0.0.1",
1720
+ port: address.port,
1721
+ address: bound,
1722
+ close: () => {
1723
+ if (closed) return;
1724
+ closed = true;
1725
+ server.close();
1726
+ },
1727
+ serve: (plan, probe) => {
1728
+ const allowed = plan.allow_origins ?? [];
1729
+ const allowPrivateNetwork = plan.requires_private_network_access === true;
1730
+ let settleAccepted;
1731
+ let failAccepted;
1732
+ const accepted = new Promise((resolve, reject) => {
1733
+ settleAccepted = resolve;
1734
+ failAccepted = reject;
1735
+ });
1736
+ accepted.catch(() => {});
1737
+ let received = false;
1738
+ server.on("error", (error) => {
1739
+ failAccepted(error);
1740
+ });
1741
+ const close = () => {
1742
+ if (closed) return;
1743
+ closed = true;
1744
+ server.close();
1745
+ };
1746
+ /** Whether this request is the probe: right path, and the nonce it was given. */
1747
+ const isProbe = (request) => probe !== void 0 && pathOf(request) === probe.path && queryParam(request, PROBE_NONCE_PARAM) === probe.nonce;
1748
+ handler = (request, response) => {
1749
+ const method = request.method ?? "";
1750
+ if (probe !== void 0 && pathOf(request) === probe.path) {
1751
+ if (method === "OPTIONS") {
1752
+ const origin$2 = header(request, "origin");
1753
+ if (origin$2 === void 0 || !isProbe(request)) {
1754
+ response.writeHead(204);
1755
+ response.end();
1756
+ return;
1757
+ }
1758
+ writePreflight(response, origin$2, "GET, OPTIONS", PROBE_HEADER, allowPrivateNetwork, request);
1759
+ probe.onAnswered?.();
1760
+ return;
1761
+ }
1762
+ if (method !== "GET" || !isProbe(request)) {
1763
+ response.writeHead(404);
1764
+ response.end();
1765
+ return;
1766
+ }
1767
+ const origin$1 = header(request, "origin");
1768
+ response.writeHead(204, origin$1 === void 0 ? {} : {
1769
+ "access-control-allow-origin": origin$1,
1770
+ vary: "Origin"
1771
+ });
1772
+ response.end();
1773
+ probe.onAnswered?.();
1774
+ return;
1775
+ }
1776
+ if (method === "OPTIONS") {
1777
+ const origin$1 = matchOrigin(allowed, header(request, "origin"));
1778
+ if (origin$1 === void 0) {
1779
+ response.writeHead(204);
1780
+ response.end();
1781
+ return;
1782
+ }
1783
+ writePreflight(response, origin$1, `${plan.method}, OPTIONS`, plan.content_type === void 0 || plan.content_type === "" ? void 0 : "Content-Type", allowPrivateNetwork, request);
1784
+ return;
1785
+ }
1786
+ if (method !== plan.method) {
1787
+ response.writeHead(405);
1788
+ response.end();
1789
+ return;
1790
+ }
1791
+ if (pathOf(request) !== plan.path) {
1792
+ response.writeHead(404);
1793
+ response.end();
1794
+ return;
1795
+ }
1796
+ if (received) {
1797
+ response.writeHead(409);
1798
+ response.end();
1799
+ return;
1800
+ }
1801
+ const origin = matchOrigin(allowed, header(request, "origin"));
1802
+ if (allowed.length > 0 && origin === void 0) {
1803
+ response.writeHead(403);
1804
+ response.end();
1805
+ return;
1806
+ }
1807
+ readPayload(request).then((payload) => {
1808
+ if (closed || received) {
1809
+ response.writeHead(409);
1810
+ response.end();
1811
+ return;
1812
+ }
1813
+ received = true;
1814
+ const headers = {};
1815
+ if (origin !== void 0) {
1816
+ headers["access-control-allow-origin"] = origin;
1817
+ headers.vary = "Origin";
1818
+ }
1819
+ response.writeHead(200, headers);
1820
+ response.end();
1821
+ settleAccepted(payload);
1822
+ close();
1823
+ }, (error) => {
1824
+ if (closed) return;
1825
+ response.writeHead(400);
1826
+ response.end();
1827
+ failAccepted(error instanceof Error ? error : new Error(String(error)));
1828
+ });
1829
+ };
1830
+ return {
1831
+ address: bound,
1832
+ accepted,
1833
+ close
1834
+ };
1835
+ }
1836
+ };
1837
+ }
1838
+
1839
+ //#endregion
1840
+ //#region src/out-of-band/login.ts
1841
+ /**
1842
+ * How long to wait when the service does not say.
1843
+ *
1844
+ * The service's own contract states ten minutes; this matches it rather than
1845
+ * inventing a different number, so a response omitting the field behaves the
1846
+ * same as one carrying the documented value.
1847
+ */
1848
+ const DEFAULT_EXPIRES_SECONDS = 600;
1849
+ /**
1850
+ * Begin a browser login.
1851
+ *
1852
+ * Binds its own listener and fetches a login URL projected for it, so both are
1853
+ * as fresh as the moment the person clicked — see the module note for why that
1854
+ * matters. Everything except `credential` is settled by the time this returns;
1855
+ * a failure to bind, reach the service, or match the plan throws instead.
1856
+ *
1857
+ * @param options - the provider and the verifier.
1858
+ * @returns the running login.
1859
+ * @throws {AuthContractError} when the port cannot be bound, the service
1860
+ * cannot be reached, or the plan names an address this machine is not on.
1861
+ */
1862
+ async function startBrowserLogin(options) {
1863
+ const { provider, verify, contract } = options;
1864
+ const bound = await bindLoopback();
1865
+ let cancelled = false;
1866
+ try {
1867
+ const target = await requestLogin(provider.id, `http://${bound.address}/`, contract);
1868
+ 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.`);
1869
+ const listener = bound.serve(target.callback);
1870
+ const expiresInSeconds = target.expires_in > 0 ? target.expires_in : DEFAULT_EXPIRES_SECONDS;
1871
+ let settleCredential;
1872
+ let failCredential;
1873
+ const completion = Promise.withResolvers();
1874
+ settleCredential = completion.resolve;
1875
+ failCredential = completion.reject;
1876
+ const credential = completion.promise;
1877
+ credential.catch(() => {});
1878
+ (async () => {
1879
+ let expiry;
1880
+ const expired = new Promise((resolve) => {
1881
+ expiry = setTimeout(() => {
1882
+ resolve("expired");
1883
+ }, expiresInSeconds * 1e3);
1884
+ unrefIfPossible(expiry);
1885
+ });
1886
+ let payload;
1887
+ try {
1888
+ const outcome = await Promise.race([listener.accepted.then((value) => ({
1889
+ kind: "accepted",
1890
+ value
1891
+ })), expired.then(() => ({ kind: "expired" }))]);
1892
+ if (outcome.kind === "expired") {
1893
+ bound.close();
1894
+ failCredential(new AuthContractError(`The browser sign-in was not completed within ${String(Math.round(expiresInSeconds / 60))} minutes. Start it again when you are ready.`));
1895
+ return;
1896
+ }
1897
+ payload = outcome.value;
1898
+ } catch (error) {
1899
+ if (cancelled) return;
1900
+ failCredential(error instanceof Error ? error : new Error(String(error)));
1901
+ return;
1902
+ } finally {
1903
+ if (expiry !== void 0) clearTimeout(expiry);
1904
+ }
1905
+ if (cancelled) return;
1906
+ const mapped = mapCredential(provider.credential_schema, payload);
1907
+ if (mapped === void 0) {
1908
+ failCredential(new AuthContractError("The callback arrived but did not carry the fields the provider declared."));
1909
+ return;
1910
+ }
1911
+ let accountName;
1912
+ try {
1913
+ accountName = await verify(mapped);
1914
+ } catch (error) {
1915
+ failCredential(error instanceof Error ? error : new Error(String(error)));
1916
+ return;
1917
+ }
1918
+ if (cancelled) return;
1919
+ settleCredential({
1920
+ credential: mapped,
1921
+ accountName: typeof accountName === "string" ? accountName : ""
1922
+ });
1923
+ })();
1924
+ return {
1925
+ address: bound.address,
1926
+ loginUrl: target.login_url,
1927
+ expiresInSeconds,
1928
+ credential,
1929
+ cancel: () => {
1930
+ if (cancelled) return;
1931
+ cancelled = true;
1932
+ bound.close();
1933
+ failCredential(new AuthContractError("The browser login was cancelled."));
1934
+ }
1935
+ };
1936
+ } catch (error) {
1937
+ bound.close();
1938
+ throw error;
1939
+ }
1940
+ }
1941
+
1942
+ //#endregion
1943
+ //#region src/out-of-band/routes.ts
1944
+ /** Path the browser half posts to, to ask whether the browser route works here. */
1945
+ const LOGIN_PROBE_ROUTE = "/api/aishell/credentials/login/probe";
1946
+ /** Path the browser half posts to, to begin a login. */
1947
+ const LOGIN_START_PATH = "/api/aishell/credentials/login/start";
1948
+ /** Path the browser half posts to, to abandon a login. */
1949
+ const LOGIN_CANCEL_PATH = "/api/aishell/credentials/login/cancel";
1950
+ /**
1951
+ * Path the probe is served on.
1952
+ *
1953
+ * On the borrowed listener rather than the host's `/api` route: the question is
1954
+ * whether the browser can reach *that* socket, so the probe has to be answered
1955
+ * there. Under a name no provider will use as a callback path — the shipped
1956
+ * provider posts to the root, so anything else is free.
1957
+ */
1958
+ const LOGIN_PROBE_PATH = "/__aishell_probe";
1959
+ /** One JSON response the browser half reads. */
1960
+ function json(body, status = 200) {
1961
+ return Response.json(body, {
1962
+ status,
1963
+ headers: { "cache-control": "no-store" }
1964
+ });
1965
+ }
1966
+ /** Read a JSON object body, or `{}` when it is absent or unreadable. */
1967
+ async function readBody(request) {
1968
+ try {
1969
+ const parsed = JSON.parse(await request.text());
1970
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
1971
+ } catch {
1972
+ return {};
1973
+ }
1974
+ }
1975
+ /** The login routes, bound to their collaborators. */
1976
+ function createLoginRoutes(deps) {
1977
+ const { findProvider: findProvider$1, probe, begin, cancel, inProgress } = deps;
1978
+ return {
1979
+ probe: async () => {
1980
+ try {
1981
+ return json({
1982
+ ok: true,
1983
+ ...await probe()
1984
+ });
1985
+ } catch (error) {
1986
+ return json({
1987
+ ok: false,
1988
+ error: error instanceof Error ? error.message : String(error)
1989
+ }, 503);
1990
+ }
1991
+ },
1992
+ start: async (request) => {
1993
+ if (inProgress()) return json({
1994
+ ok: false,
1995
+ error: "A browser login is already in progress."
1996
+ }, 409);
1997
+ const body = await readBody(request);
1998
+ const providerId = typeof body.provider === "string" && body.provider !== "" ? body.provider : "huaweicloud";
1999
+ let provider;
2000
+ try {
2001
+ provider = await findProvider$1(providerId);
2002
+ } catch (error) {
2003
+ return json({
2004
+ ok: false,
2005
+ error: error instanceof Error ? error.message : String(error)
2006
+ }, 503);
2007
+ }
2008
+ if (provider === void 0) return json({
2009
+ ok: false,
2010
+ error: `No login provider named ${providerId}.`
2011
+ }, 404);
2012
+ if (provider.delivery !== "out_of_band") return json({
2013
+ ok: false,
2014
+ error: `Provider ${providerId} uses "${provider.delivery}", which this plugin cannot complete.`
2015
+ }, 501);
2016
+ try {
2017
+ return json(await begin(provider));
2018
+ } catch (error) {
2019
+ return json({
2020
+ ok: false,
2021
+ error: error instanceof Error ? error.message : String(error)
2022
+ }, 502);
2023
+ }
2024
+ },
2025
+ cancel: () => {
2026
+ cancel();
2027
+ return Promise.resolve(json({ ok: true }));
2028
+ }
2029
+ };
2030
+ }
2031
+
2032
+ //#endregion
2033
+ //#region src/out-of-band/flow.ts
2034
+ /**
2035
+ * Build the flow.
2036
+ *
2037
+ * @param deps - the collaborators above.
2038
+ */
2039
+ function createLoginFlow(deps) {
2040
+ const { verify, store, recordError, recordOutcome, contract } = deps;
2041
+ /** The login in progress, if any. */
2042
+ let active;
2043
+ const finish = () => {
2044
+ active = void 0;
2045
+ };
2046
+ return {
2047
+ findProvider: (providerId) => findProvider(providerId, contract),
2048
+ probe: async () => {
2049
+ const { probeUrl } = await probeLoopback(LOGIN_PROBE_PATH);
2050
+ return { probeUrl };
2051
+ },
2052
+ inProgress: () => active !== void 0,
2053
+ cancel: () => {
2054
+ const login = active;
2055
+ finish();
2056
+ login?.cancel();
2057
+ recordOutcome(void 0);
2058
+ },
2059
+ begin: async (provider) => {
2060
+ if (active !== void 0) throw new AuthContractError("A browser login is already in progress.");
2061
+ const login = await startBrowserLogin({
2062
+ provider,
2063
+ contract,
2064
+ verify
2065
+ });
2066
+ active = login;
2067
+ login.credential.then(async (result) => {
2068
+ if (active !== login) return;
2069
+ try {
2070
+ await store(result.credential);
2071
+ if (active !== login) return;
2072
+ finish();
2073
+ recordError("");
2074
+ recordOutcome({
2075
+ kind: "succeeded",
2076
+ accountName: result.accountName
2077
+ });
2078
+ } catch (error) {
2079
+ if (active !== login) return;
2080
+ finish();
2081
+ const message = `The credential verified, but storing it failed: ${error instanceof Error ? error.message : String(error)}`;
2082
+ recordError(message);
2083
+ recordOutcome({
2084
+ kind: "failed",
2085
+ error: message
2086
+ });
2087
+ }
2088
+ }, (error) => {
2089
+ if (active !== login) return;
2090
+ finish();
2091
+ const message = error instanceof Error ? error.message : String(error);
2092
+ recordError(message);
2093
+ recordOutcome({
2094
+ kind: "failed",
2095
+ error: message
2096
+ });
2097
+ });
2098
+ return {
2099
+ ok: true,
2100
+ loginUrl: login.loginUrl,
2101
+ providerName: provider.display_name,
2102
+ expiresInSeconds: login.expiresInSeconds
2103
+ };
2104
+ }
2105
+ };
2106
+ }
2107
+
2108
+ //#endregion
2109
+ //#region src/prefill.ts
2110
+ /**
2111
+ * Credential prefill from the environment.
2112
+ *
2113
+ * ## What this is for
2114
+ *
2115
+ * A machine that already carries `HW_ACCESS_KEY`, `HW_SECRET_KEY` and
2116
+ * `HW_SECURITY_TOKEN` in its environment has the credentials; the person just
2117
+ * has to move them into the store. Typing three values that are already on the
2118
+ * machine is work nobody should do, so the form opens with them filled in.
2119
+ *
2120
+ * ## Why the values come from the host
2121
+ *
2122
+ * The browser half cannot read `process.env` — it is browser code, and the
2123
+ * environment it would see is not the host's. So the host reads the variables
2124
+ * and serves them over a route the form calls before it renders its fields.
2125
+ *
2126
+ * ## Why that is acceptable here
2127
+ *
2128
+ * The values travel from the host to the page it is serving, over the same
2129
+ * authenticated channel and the same origin as the credential route the form
2130
+ * already posts to. Nothing new is exposed: a page that could read this route
2131
+ * could also submit that form.
2132
+ *
2133
+ * They are **not** written to the settings document, the session, or a log —
2134
+ * the route is the whole journey, and it is called once per form open.
2135
+ *
2136
+ * ## Why it returns nothing rather than a partial set
2137
+ *
2138
+ * A form filled with an access key and no secret key looks broken. Either the
2139
+ * environment carries a usable pair, or the form starts empty and the person
2140
+ * enters what they have. The token is separate: it is optional, and a lone
2141
+ * token with no pair is dropped for the same reason.
2142
+ *
2143
+ * ## Why the form says so
2144
+ *
2145
+ * The person did not type these values. Saying where they came from is what
2146
+ * lets them decide whether to trust them — a credential silently appearing in
2147
+ * a field is worse than an empty one.
2148
+ *
2149
+ * @module @huaweidevtools/aishell-dsh-client-credentials/prefill
2150
+ */
2151
+ /** Route the form reads prefills from. */
2152
+ const PREFILL_PATH = "/api/aishell/credentials/prefill";
2153
+ /** Variables read, in the order the form's fields appear. */
2154
+ const ACCESS_KEY_ENV = "HW_ACCESS_KEY";
2155
+ const SECRET_KEY_ENV = "HW_SECRET_KEY";
2156
+ const SECURITY_TOKEN_ENV = "HW_SECURITY_TOKEN";
2157
+ /**
2158
+ * Read an environment for a usable credential set.
2159
+ *
2160
+ * Pure, and the environment is a parameter: this package compiles without Node
2161
+ * type definitions (the browser half is most of it), so `process` is not in
2162
+ * scope and the caller supplies what to read.
2163
+ *
2164
+ * ## What these values do, and do not, do
2165
+ *
2166
+ * They fill the form's fields. The form still opens, every field is still
2167
+ * editable, and submitting or cancelling still works the way it always did —
2168
+ * the person saves the step of copying three values out of their shell, and
2169
+ * nothing else. In particular nothing is stored on their behalf: a prefill is a
2170
+ * starting point, not a credential.
2171
+ *
2172
+ * @param env - the environment to read.
2173
+ * @returns the pair (and token, when present), or `undefined` when either half
2174
+ * of the pair is missing.
2175
+ */
2176
+ function readEnvPrefill(env) {
2177
+ const ak = env[ACCESS_KEY_ENV];
2178
+ const sk = env[SECRET_KEY_ENV];
2179
+ if (ak === void 0 || ak === "" || sk === void 0 || sk === "") return void 0;
2180
+ const token = env[SECURITY_TOKEN_ENV];
2181
+ return {
2182
+ accessKeyId: ak,
2183
+ secretAccessKey: sk,
2184
+ ...token === void 0 || token === "" ? {} : { securityToken: token }
2185
+ };
2186
+ }
2187
+
896
2188
  //#endregion
897
2189
  //#region src/reconcile.ts
898
2190
  /**
@@ -915,14 +2207,13 @@ defineMethod("transform", [
915
2207
  * mirror so reconcile never depends on config flow-back timing.
916
2208
  */
917
2209
  function createCredentialReconciler(deps) {
918
- const { store, verify, recordStatus, readStored, readHint, accounts } = deps;
2210
+ const { verify, recordStatus, readStored, readHint, readPair } = deps;
919
2211
  let lastVerifyFingerprint = "";
920
2212
  const materialFingerprint = (ak, sk, token) => `${ak}\n${sk}\n${token ?? ""}`;
921
2213
  return {
922
2214
  reconcile: () => {
923
- const ak = store.get(accounts.accessKey);
924
- const sk = store.get(accounts.secretKey);
925
- const haveKeys = Boolean(ak && sk);
2215
+ const pair = readPair();
2216
+ const haveKeys = pair !== void 0;
926
2217
  const stored = readStored();
927
2218
  const hint = readHint();
928
2219
  if (!haveKeys && (stored || hint !== null)) recordStatus([{
@@ -939,14 +2230,12 @@ function createCredentialReconciler(deps) {
939
2230
  value: true
940
2231
  }]);
941
2232
  if (!haveKeys) return;
942
- const token = store.get(accounts.securityToken);
943
- const fingerprint = materialFingerprint(ak, sk, token);
2233
+ const fingerprint = materialFingerprint(pair.ak, pair.sk, pair.securityToken);
944
2234
  const materialChanged = fingerprint !== lastVerifyFingerprint;
945
2235
  if (!materialChanged) return;
946
2236
  lastVerifyFingerprint = fingerprint;
947
- verify(ak, sk, token).then((accountName) => {
948
- if (store.get(accounts.accessKey) !== ak) return;
949
- if (store.get(accounts.secretKey) !== sk) return;
2237
+ verify(pair.ak, pair.sk, pair.securityToken).then((accountName) => {
2238
+ if (readPair()?.ak !== pair.ak) return;
950
2239
  recordStatus([{
951
2240
  op: "set",
952
2241
  path: ["accessKeyIdHint"],
@@ -963,6 +2252,39 @@ function createCredentialReconciler(deps) {
963
2252
  //#endregion
964
2253
  //#region src/index.ts
965
2254
  /**
2255
+ * Read the request token out of a save body.
2256
+ *
2257
+ * Parsed leniently: the route validates the body itself and answers 400 for a
2258
+ * malformed one, so this only has to avoid throwing on the way past. A missing
2259
+ * or unreadable token means "not an answer to a request", which is the right
2260
+ * behaviour for a chip-opened form.
2261
+ *
2262
+ * @param body - the raw request body.
2263
+ */
2264
+ function readRequestToken(body) {
2265
+ try {
2266
+ const parsed = JSON.parse(body);
2267
+ const token = parsed?.requestToken;
2268
+ return typeof token === "string" && token !== "" ? token : void 0;
2269
+ } catch {
2270
+ return void 0;
2271
+ }
2272
+ }
2273
+ /**
2274
+ * The host process's environment.
2275
+ *
2276
+ * Reached through a narrow cast rather than a typed `process`: this package
2277
+ * compiles without Node type definitions, so `process` is not in scope. The
2278
+ * host always has it; `{}` is the shape a build without one falls back to, and
2279
+ * an empty environment simply yields no prefill.
2280
+ *
2281
+ * @returns the environment, or an empty object when there is none.
2282
+ */
2283
+ function runtimeEnv() {
2284
+ const holder = globalThis;
2285
+ return holder.process?.env ?? {};
2286
+ }
2287
+ /**
966
2288
  * Settings schema for this entry. Secrets are deliberately absent: they travel
967
2289
  * over the credential route into the credential store, never through a
968
2290
  * settings document.
@@ -971,57 +2293,69 @@ const Config = Schema.object({
971
2293
  credentialsStored: Schema.boolean().default(false).volatile(),
972
2294
  accessKeyIdHint: Schema.string().default("").volatile(),
973
2295
  lastError: Schema.string().default("").volatile(),
974
- credentialRequestSession: Schema.string().default("").volatile()
2296
+ credentialFormRequest: Schema.string().default("").volatile(),
2297
+ loginOutcome: Schema.string().default("").volatile()
975
2298
  });
976
- /** Credential store account names for Huawei Cloud credentials. */
977
- const AK_ACCOUNT = "HW_ACCESS_KEY";
978
- const SK_ACCOUNT = "HW_SECRET_KEY";
979
- const TOKEN_ACCOUNT = "HW_SECURITY_TOKEN";
980
- /** IAM endpoint host. */
981
- const IAM_HOST = "iam.myhuaweicloud.com";
982
2299
  /** Route the browser half reads status from and saves credentials to. */
983
2300
  const CREDENTIALS_PATH = "/api/aishell/credentials";
984
2301
  /** Route the browser half clears credentials through (fetch routes have no DELETE). */
985
2302
  const CLEAR_PATH = "/api/aishell/credentials/clear";
986
2303
  /**
987
- * Route the browser calls to decline the credential form.
2304
+ * Route the browser calls when the person cancels the credential form.
988
2305
  *
989
- * Separate from `clear`: clearing removes stored credentials, while this ends a
990
- * request without touching the store — a person who already has credentials for
991
- * something else, or who would rather fill them in later, must be able to
992
- * say "not now" without wiping anything.
2306
+ * Separate from `clear`: cancelling says "not now" without touching the store.
2307
+ * What it does record is the cancel itself, so the next `auth` call can tell an
2308
+ * unanswered request from a refused one and stop asking.
993
2309
  */
994
- const DISMISS_PATH = "/api/aishell/credentials/dismiss";
2310
+ const CANCEL_PATH = "/api/aishell/credentials/cancel";
995
2311
  /** Largest credential body accepted; a real payload is well under 1 KiB. */
996
2312
  const MAX_BODY_BYTES = 8 * 1024;
997
2313
  /**
998
2314
  * Verify credentials against Huawei Cloud IAM and return the account name.
999
2315
  *
1000
- * Calls `GET https://iam.myhuaweicloud.com/v3/auth/domains` signed with the
1001
- * AK/SK (and SecurityToken if present — STS temporary credentials carry the
1002
- * same full IAM scope as the permanent credential that minted them). A 200
1003
- * proves the credentials are valid and returns the domain (account) name;
1004
- * a 401/403 rejects them.
2316
+ * Delegates to the shared `verify` module, so the form, the ops `auth` tool
2317
+ * and anything else that asks "are these credentials valid?" get the same
2318
+ * answer from the same endpoint (profile: `GET /v3/projects`, with the account
2319
+ * name read best-effort from `/v3/auth/domains`).
1005
2320
  *
1006
- * @returns the account name (domain name).
2321
+ * ## Why not a local domains-only call
2322
+ *
2323
+ * This used to call `/v3/auth/domains` directly, because the only fact this
2324
+ * route needed was the account name shown in the composer chip. That made it a
2325
+ * second, narrower notion of validity: `/v3/projects` rejects a credential with
2326
+ * no visible project, while `/v3/auth/domains` accepts it — so the form said
2327
+ * "saved" for credentials the tools would then refuse. One verifier removes
2328
+ * that gap, and the project list it returns is exactly what a caller needs
2329
+ * before planning a deployment.
2330
+ *
2331
+ * ## The region
2332
+ *
2333
+ * IAM is global: the region only routes to a regional replica and does not
2334
+ * scope the result. The chip's copy is fixed at `cn-north-4` for routing
2335
+ * purposes rather than configured, because verification must succeed even
2336
+ * before a person has chosen a region — and because a wrong region here would
2337
+ * report "invalid credentials" for what is really a typo'd region setting
2338
+ * elsewhere.
2339
+ *
2340
+ * @returns the account name (domain name), falling back to the account id.
1007
2341
  * @throws Error with a user-readable message when verification fails.
1008
2342
  */
1009
- async function verifyCredentials(ak, sk, securityToken) {
1010
- const path = "/v3/auth/domains";
1011
- const signed = sign("GET", IAM_HOST, path, {}, "", {
2343
+ async function verifyCredentials$1(ak, sk, securityToken) {
2344
+ const result = await verifyCredentials({
1012
2345
  ak,
1013
2346
  sk,
1014
- ...securityToken ? { securityToken } : {}
1015
- });
1016
- const resp = await fetch(`https://${IAM_HOST}${path}`, { headers: { ...signed } });
1017
- if (resp.status === 401) throw new Error("Credential verification failed: Huawei Cloud returned 401. Check the Access Key, Secret Key, and Security Token.");
1018
- if (resp.status === 403) throw new Error("Credential verification failed: this credential cannot read IAM (403).");
1019
- if (!resp.ok) throw new Error(`Credential verification failed: Huawei Cloud returned ${resp.status}.`);
1020
- const body = await resp.json();
1021
- const name$1 = body.domains?.[0]?.name;
1022
- if (!name$1) throw new Error("Credential verified, but Huawei Cloud returned no account name.");
1023
- return name$1;
2347
+ ...securityToken === void 0 ? {} : { securityToken }
2348
+ }, { region: VERIFY_REGION });
2349
+ if (!result.ok) throw new Error(result.message);
2350
+ return result.account.name;
1024
2351
  }
2352
+ /**
2353
+ * Region used to route the verification call.
2354
+ *
2355
+ * Not a setting: see {@link verifyCredentials}. Any region replica answers the
2356
+ * same question.
2357
+ */
2358
+ const VERIFY_REGION = "cn-north-4";
1025
2359
  /** One JSON error response the browser half renders verbatim. */
1026
2360
  function jsonError(status, message) {
1027
2361
  return Response.json({
@@ -1058,7 +2392,7 @@ function createCredentialRoutes(deps) {
1058
2392
  const { store, verify, recordStatus, hint, notifyChanged } = deps;
1059
2393
  return {
1060
2394
  get: () => Promise.resolve(Response.json({
1061
- configured: Boolean(store.get(AK_ACCOUNT) && store.get(SK_ACCOUNT)),
2395
+ configured: hasStoredPair(store),
1062
2396
  accountName: hint()
1063
2397
  }, { headers: { "cache-control": "no-store" } })),
1064
2398
  save: async (request) => {
@@ -1088,12 +2422,11 @@ function createCredentialRoutes(deps) {
1088
2422
  }, { status: 422 });
1089
2423
  }
1090
2424
  try {
1091
- store.delete(AK_ACCOUNT);
1092
- store.delete(SK_ACCOUNT);
1093
- store.delete(TOKEN_ACCOUNT);
1094
- store.set(AK_ACCOUNT, ak);
1095
- store.set(SK_ACCOUNT, sk);
1096
- if (token) store.set(TOKEN_ACCOUNT, token);
2425
+ writeHuaweiCloud(store, {
2426
+ ak,
2427
+ sk,
2428
+ ...token === void 0 ? {} : { securityToken: token }
2429
+ });
1097
2430
  } catch (error) {
1098
2431
  const message = `Credential verified, but storing it failed: ${error instanceof Error ? error.message : String(error)}`;
1099
2432
  recordStatus([{
@@ -1126,9 +2459,7 @@ function createCredentialRoutes(deps) {
1126
2459
  });
1127
2460
  },
1128
2461
  clear: () => {
1129
- store.delete(AK_ACCOUNT);
1130
- store.delete(SK_ACCOUNT);
1131
- store.delete(TOKEN_ACCOUNT);
2462
+ clearCredentials(store);
1132
2463
  recordStatus([
1133
2464
  {
1134
2465
  op: "set",
@@ -1156,6 +2487,45 @@ function apply(ctx, config) {
1156
2487
  const ns = ctx.fiber.entry?.options.id;
1157
2488
  let recordedStored = config.credentialsStored.get() === true;
1158
2489
  let recordedHint = config.accessKeyIdHint.get() || null;
2490
+ /**
2491
+ * The form request a tool call is currently blocked on.
2492
+ *
2493
+ * Held here rather than read from the document: the answer arrives over the
2494
+ * credential and cancel routes, and those need the same object the tool is
2495
+ * awaiting.
2496
+ */
2497
+ let pendingForm;
2498
+ /**
2499
+ * Settle the pending request and withdraw it from the document.
2500
+ *
2501
+ * One helper on purpose: the field is **persisted** — it is this entry's row
2502
+ * in the profile — so a request left in the document outlives the call that
2503
+ * made it. On the next boot the browser half reads that stale value and opens
2504
+ * the form for a question nobody is asking, which is why a fresh install
2505
+ * showed a credential form unprompted.
2506
+ *
2507
+ * Every path that answers a request goes through here. Writing the clear
2508
+ * beside each settle instead would work until someone added a path and
2509
+ * forgot, and the symptom would be an unexplained form on a later boot.
2510
+ *
2511
+ * @param outcome - what the person did, or `undefined` to abandon without
2512
+ * answering (used for the release path, where nothing is waiting).
2513
+ * @param expected - the request being settled. When given, a settle for a
2514
+ * different request is ignored, so a late answer cannot clear a form
2515
+ * somebody else is looking at.
2516
+ */
2517
+ const settleFormRequest = (outcome, expected) => {
2518
+ if (expected !== void 0 && pendingForm !== expected) return;
2519
+ const pending = pendingForm;
2520
+ pendingForm = void 0;
2521
+ if (pending !== void 0 && outcome !== void 0) pending.settle(outcome);
2522
+ if (ns !== void 0) ctx.settings.mutate(ns, [{
2523
+ op: "unset",
2524
+ path: [FORM_REQUEST_FIELD]
2525
+ }]).catch((error) => {
2526
+ ctx.logger.warn(error);
2527
+ });
2528
+ };
1159
2529
  /** Apply one batch of ops to the mirror. */
1160
2530
  const mirrorOps = (ops) => {
1161
2531
  for (const op of ops) if (op.path[0] === "credentialsStored") recordedStored = op.op === "set" && op.value === true;
@@ -1186,7 +2556,7 @@ function apply(ctx, config) {
1186
2556
  };
1187
2557
  const routes = createCredentialRoutes({
1188
2558
  store,
1189
- verify: verifyCredentials,
2559
+ verify: verifyCredentials$1,
1190
2560
  recordStatus,
1191
2561
  hint: () => recordedHint ?? "",
1192
2562
  notifyChanged: () => {
@@ -1194,83 +2564,181 @@ function apply(ctx, config) {
1194
2564
  }
1195
2565
  });
1196
2566
  const reconciler = createCredentialReconciler({
1197
- store,
1198
- verify: verifyCredentials,
2567
+ verify: verifyCredentials$1,
1199
2568
  recordStatus,
1200
2569
  readStored: () => recordedStored,
1201
2570
  readHint: () => recordedHint,
1202
- accounts: {
1203
- accessKey: AK_ACCOUNT,
1204
- secretKey: SK_ACCOUNT,
1205
- securityToken: TOKEN_ACCOUNT
1206
- }
2571
+ readPair: () => readStoredPair(store)
1207
2572
  });
1208
- let settlePrompt;
1209
- /**
1210
- * End the open form, if any: clear the flag the browser renders from and
1211
- * hand the credential back to the waiting call.
1212
- */
1213
- const settleCredentialForm = (credentials) => {
1214
- const settle = settlePrompt;
1215
- settlePrompt = void 0;
1216
- recordStatus([{
1217
- op: "set",
1218
- path: ["credentialRequestSession"],
1219
- value: ""
1220
- }]);
1221
- settle?.(credentials);
1222
- };
1223
- ctx.effect(() => ctx.on("aishell/credential-request", (request) => {
1224
- settlePrompt?.(void 0);
1225
- settlePrompt = request.settle;
1226
- recordStatus([{
1227
- op: "set",
1228
- path: ["credentialRequestSession"],
1229
- value: request.sessionId ?? ""
1230
- }]);
1231
- request.signal?.addEventListener("abort", () => {
1232
- if (settlePrompt === request.settle) settleCredentialForm(void 0);
1233
- }, { once: true });
1234
- }), "aishell-credentials: credential form requests");
1235
- ctx.effect(() => ctx.on("aishell/credentials-updated", () => {
1236
- if (settlePrompt === void 0) return;
1237
- const ak = store.get(AK_ACCOUNT);
1238
- const sk = store.get(SK_ACCOUNT);
1239
- if (!ak || !sk) return;
1240
- const securityToken = store.get(TOKEN_ACCOUNT);
1241
- settleCredentialForm({
1242
- ak,
1243
- sk,
1244
- ...securityToken === void 0 ? {} : { securityToken }
1245
- });
1246
- }), "aishell-credentials: resume the waiting call");
1247
2573
  ctx.effect(() => ctx.connection.fetch.register({
1248
2574
  path: CREDENTIALS_PATH,
1249
2575
  methods: ["GET", "POST"],
1250
2576
  requestBody: "buffered",
1251
- fetch: (request) => request.method === "GET" ? (reconciler.reconcile(), routes.get()) : routes.save(request)
2577
+ fetch: async (request) => {
2578
+ if (request.method === "GET") return reconciler.reconcile(), routes.get();
2579
+ const body = await request.text();
2580
+ const requestToken = readRequestToken(body);
2581
+ const response = await routes.save(new Request(request.url, {
2582
+ method: "POST",
2583
+ headers: request.headers,
2584
+ body
2585
+ }));
2586
+ if (response.ok && requestToken !== void 0 && pendingForm !== void 0 && pendingForm.request.token === requestToken) settleFormRequest({ kind: "submitted" }, pendingForm);
2587
+ return response;
2588
+ }
1252
2589
  }), "aishell-credentials: credentials route");
1253
2590
  ctx.effect(() => ctx.connection.fetch.register({
1254
- path: CLEAR_PATH,
2591
+ path: CANCEL_PATH,
1255
2592
  methods: ["POST"],
1256
2593
  requestBody: "buffered",
1257
- fetch: () => {
1258
- reconciler.resetVerifyBaseline();
1259
- return routes.clear();
2594
+ fetch: async (request) => {
2595
+ let body;
2596
+ try {
2597
+ body = await request.json();
2598
+ } catch {
2599
+ return Response.json({
2600
+ ok: false,
2601
+ error: "Request body is not valid JSON."
2602
+ }, { status: 400 });
2603
+ }
2604
+ const token = body?.token;
2605
+ if (typeof token !== "string" || token === "") return Response.json({
2606
+ ok: false,
2607
+ error: "token is required."
2608
+ }, { status: 400 });
2609
+ if (pendingForm !== void 0 && pendingForm.request.token === token) settleFormRequest({ kind: "cancelled" }, pendingForm);
2610
+ return Response.json({ ok: true });
1260
2611
  }
1261
- }), "aishell-credentials: clear route");
2612
+ }), "aishell-credentials: cancel route");
1262
2613
  ctx.effect(() => ctx.connection.fetch.register({
1263
- path: DISMISS_PATH,
2614
+ path: PREFILL_PATH,
2615
+ methods: ["GET"],
2616
+ requestBody: "buffered",
2617
+ fetch: () => Promise.resolve(Response.json(readEnvPrefill(runtimeEnv()) ?? {}, { headers: { "cache-control": "no-store" } }))
2618
+ }), "aishell-credentials: prefill route");
2619
+ /**
2620
+ * Announces that the stored credentials changed, so consumers that cached
2621
+ * something derived from them drop it.
2622
+ *
2623
+ * Declared before the flow because `recordOutcome` is where a successful
2624
+ * login is known, and that is the point at which the store has just changed.
2625
+ */
2626
+ const announceCredentialsChanged = () => {
2627
+ ctx.emit("aishell/credentials-updated");
2628
+ };
2629
+ const loginFlow = createLoginFlow({
2630
+ verify: async (credential) => {
2631
+ return await verifyCredentials$1(credential.accessKeyId, credential.secretAccessKey, credential.securityToken);
2632
+ },
2633
+ store: (credential) => {
2634
+ writeHuaweiCloud(store, {
2635
+ ak: credential.accessKeyId,
2636
+ sk: credential.secretAccessKey,
2637
+ ...credential.securityToken === void 0 ? {} : { securityToken: credential.securityToken }
2638
+ });
2639
+ return Promise.resolve();
2640
+ },
2641
+ recordError: (error) => {
2642
+ recordStatus([{
2643
+ op: "set",
2644
+ path: ["lastError"],
2645
+ value: error
2646
+ }]);
2647
+ },
2648
+ recordOutcome: (outcome) => {
2649
+ recordStatus([{
2650
+ op: "set",
2651
+ path: [LOGIN_OUTCOME_FIELD],
2652
+ value: encodeOutcome(outcome)
2653
+ }]);
2654
+ if (outcome?.kind !== "succeeded") return;
2655
+ recordStatus([
2656
+ {
2657
+ op: "set",
2658
+ path: ["credentialsStored"],
2659
+ value: true
2660
+ },
2661
+ {
2662
+ op: "set",
2663
+ path: ["accessKeyIdHint"],
2664
+ value: outcome.accountName
2665
+ },
2666
+ {
2667
+ op: "unset",
2668
+ path: ["lastError"]
2669
+ }
2670
+ ]);
2671
+ announceCredentialsChanged();
2672
+ settleFormRequest({ kind: "submitted" });
2673
+ }
2674
+ });
2675
+ const loginRoutes = createLoginRoutes({
2676
+ findProvider: loginFlow.findProvider,
2677
+ probe: loginFlow.probe,
2678
+ begin: loginFlow.begin,
2679
+ cancel: loginFlow.cancel,
2680
+ inProgress: loginFlow.inProgress
2681
+ });
2682
+ ctx.effect(() => ctx.connection.fetch.register({
2683
+ path: LOGIN_PROBE_ROUTE,
2684
+ methods: ["POST"],
2685
+ requestBody: "buffered",
2686
+ fetch: loginRoutes.probe
2687
+ }), "aishell-credentials: browser login probe route");
2688
+ ctx.effect(() => ctx.connection.fetch.register({
2689
+ path: LOGIN_START_PATH,
2690
+ methods: ["POST"],
2691
+ requestBody: "buffered",
2692
+ fetch: loginRoutes.start
2693
+ }), "aishell-credentials: browser login start route");
2694
+ ctx.effect(() => ctx.connection.fetch.register({
2695
+ path: LOGIN_CANCEL_PATH,
2696
+ methods: ["POST"],
2697
+ requestBody: "buffered",
2698
+ fetch: loginRoutes.cancel
2699
+ }), "aishell-credentials: browser login cancel route");
2700
+ ctx.effect(() => () => {
2701
+ loginFlow.cancel();
2702
+ }, "aishell-credentials: browser login teardown");
2703
+ ctx.effect(() => ctx.connection.fetch.register({
2704
+ path: CLEAR_PATH,
1264
2705
  methods: ["POST"],
1265
2706
  requestBody: "buffered",
1266
2707
  fetch: () => {
1267
- settleCredentialForm(void 0);
1268
- return Promise.resolve(Response.json({ ok: true }));
2708
+ reconciler.resetVerifyBaseline();
2709
+ return routes.clear();
1269
2710
  }
1270
- }), "aishell-credentials: dismiss route");
2711
+ }), "aishell-credentials: clear route");
1271
2712
  reconciler.reconcile();
1272
2713
  const reconcileTimer = setInterval(reconciler.reconcile, 3e4);
1273
2714
  ctx.effect(() => () => clearInterval(reconcileTimer), "aishell-credentials: status reconcile timer");
2715
+ if (ns !== void 0 && config.credentialFormRequest.get() !== "") ctx.settings.mutate(ns, [{
2716
+ op: "unset",
2717
+ path: [FORM_REQUEST_FIELD]
2718
+ }]).catch((error) => {
2719
+ ctx.logger.warn(error);
2720
+ });
2721
+ registerAuthTool(ctx, store, {
2722
+ requestForm: (sessionId) => {
2723
+ if (ns === void 0) return void 0;
2724
+ if (pendingForm !== void 0) return pendingForm.outcome;
2725
+ const pending = formRequest(sessionId);
2726
+ pendingForm = pending;
2727
+ ctx.settings.mutate(ns, [{
2728
+ op: "set",
2729
+ path: [FORM_REQUEST_FIELD],
2730
+ value: pending.encoded
2731
+ }]).catch((error) => {
2732
+ ctx.logger.warn(error);
2733
+ settleFormRequest({ kind: "cancelled" }, pending);
2734
+ });
2735
+ return pending.outcome;
2736
+ },
2737
+ releaseForm: () => {
2738
+ settleFormRequest({ kind: "cancelled" });
2739
+ loginFlow.cancel();
2740
+ }
2741
+ });
1274
2742
  ctx.effect(() => ctx.settings.configure({ auto: false }, ctx.fiber));
1275
2743
  }
1276
2744