@huaweidevtools/aishell-dsh-client-credentials 0.0.1-beta.1 → 0.0.1-beta.3
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/LICENSE +1 -1
- package/lib/client.js +323 -541
- package/lib/index.js +463 -122
- package/lib/types/auth-tool.d.ts +98 -0
- package/lib/types/client/AishellAccountHint.d.ts +10 -3
- package/lib/types/client/AishellHeroChip.d.ts +22 -11
- package/lib/types/client/CredentialFormInteraction.d.ts +4 -12
- package/lib/types/client/CredentialRequestForm.d.ts +53 -16
- package/lib/types/client/credential-form-visibility.d.ts +30 -17
- package/lib/types/client/credential-status.d.ts +5 -6
- package/lib/types/client/huawei-mark.d.ts +18 -6
- package/lib/types/client/index.d.ts +9 -5
- package/lib/types/client/locales.d.ts +14 -14
- package/lib/types/client/permission-mode.d.ts +3 -3
- package/lib/types/form-request.d.ts +90 -0
- package/lib/types/index.d.ts +24 -50
- package/lib/types/reconcile.d.ts +80 -0
- package/package.json +17 -14
- package/lib/types/client/AishellCredentialsSection.d.ts +0 -34
- package/lib/types/client/open-settings.d.ts +0 -27
package/lib/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createCredentialsStore } from "@huaweidevtools/aishell-dsh-credentials-store";
|
|
2
|
-
import {
|
|
2
|
+
import { clearCredentials, hasStoredPair, readStoredPair, writeHuaweiCloud } from "@huaweidevtools/aishell-dsh-credentials-store/accounts";
|
|
3
|
+
import { verifyCredentials } from "@huaweidevtools/aishell-dsh-credentials-store/verify";
|
|
3
4
|
|
|
4
5
|
//#region ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.5/node_modules/@deepseek-ai/cosmokit/lib/index.js
|
|
5
6
|
/** Return true when a value is `null` or `undefined`. */
|
|
@@ -893,6 +894,314 @@ defineMethod("transform", [
|
|
|
893
894
|
"preserve"
|
|
894
895
|
], ({ inner }, isInner) => inner.toString(isInner));
|
|
895
896
|
|
|
897
|
+
//#endregion
|
|
898
|
+
//#region src/auth-tool.ts
|
|
899
|
+
/** Model-facing name. Prefixed so it cannot collide with another cloud plugin. */
|
|
900
|
+
const AUTH_TOOL_NAME = "aishell__auth";
|
|
901
|
+
/** Region used to route the verification call; IAM is global, see the module note. */
|
|
902
|
+
const VERIFY_REGION$1 = "cn-north-4";
|
|
903
|
+
/** Per-call budget. IAM answers in well under a second when healthy. */
|
|
904
|
+
const AUTH_TIMEOUT_MS = 3e4;
|
|
905
|
+
/**
|
|
906
|
+
* The JSON Schema for `auth`'s parameters: none.
|
|
907
|
+
*
|
|
908
|
+
* Declared as an empty object rather than omitted so the model reads "takes no
|
|
909
|
+
* arguments" explicitly, instead of inferring it from a missing field.
|
|
910
|
+
*/
|
|
911
|
+
const AUTH_PARAMETERS = {
|
|
912
|
+
type: "object",
|
|
913
|
+
properties: {},
|
|
914
|
+
additionalProperties: false
|
|
915
|
+
};
|
|
916
|
+
/**
|
|
917
|
+
* Register the `auth` tool on the host's tool registry.
|
|
918
|
+
*
|
|
919
|
+
* @param ctx - host context.
|
|
920
|
+
* @param store - the credential store this package owns.
|
|
921
|
+
*/
|
|
922
|
+
function registerAuthTool(ctx, store, deps) {
|
|
923
|
+
ctx.inject(["tools"], (scope) => {
|
|
924
|
+
const dispose = scope.tools.register({
|
|
925
|
+
name: AUTH_TOOL_NAME,
|
|
926
|
+
description: "Verify the stored Huawei Cloud credentials and report the account: its id and name, and every project visible to it (a project's name is a region; its id is what a region-scoped API needs).",
|
|
927
|
+
parameters: AUTH_PARAMETERS,
|
|
928
|
+
output: {
|
|
929
|
+
schema: {
|
|
930
|
+
type: "object",
|
|
931
|
+
properties: {
|
|
932
|
+
authenticated: { type: "boolean" },
|
|
933
|
+
account: {
|
|
934
|
+
type: "object",
|
|
935
|
+
properties: {
|
|
936
|
+
accountId: { type: "string" },
|
|
937
|
+
name: { type: "string" }
|
|
938
|
+
},
|
|
939
|
+
required: ["accountId", "name"]
|
|
940
|
+
},
|
|
941
|
+
projects: {
|
|
942
|
+
type: "array",
|
|
943
|
+
items: {
|
|
944
|
+
type: "object",
|
|
945
|
+
properties: {
|
|
946
|
+
id: { type: "string" },
|
|
947
|
+
name: { type: "string" },
|
|
948
|
+
description: { type: "string" }
|
|
949
|
+
},
|
|
950
|
+
required: ["id", "name"]
|
|
951
|
+
}
|
|
952
|
+
},
|
|
953
|
+
sts: { type: "boolean" }
|
|
954
|
+
},
|
|
955
|
+
required: [
|
|
956
|
+
"authenticated",
|
|
957
|
+
"account",
|
|
958
|
+
"projects",
|
|
959
|
+
"sts"
|
|
960
|
+
]
|
|
961
|
+
},
|
|
962
|
+
render: (_args, value) => renderAuth(value)
|
|
963
|
+
},
|
|
964
|
+
timeoutMs: AUTH_TIMEOUT_MS,
|
|
965
|
+
async execute(_args, exec) {
|
|
966
|
+
return await runAuth(store, deps, sessionOf(exec));
|
|
967
|
+
}
|
|
968
|
+
});
|
|
969
|
+
return dispose;
|
|
970
|
+
});
|
|
971
|
+
}
|
|
972
|
+
/** The session a tool call runs under, from its execution context. */
|
|
973
|
+
function sessionOf(exec) {
|
|
974
|
+
return exec.agent?.session?.id;
|
|
975
|
+
}
|
|
976
|
+
/**
|
|
977
|
+
* Verify and describe the stored account.
|
|
978
|
+
*
|
|
979
|
+
* Four outcomes, and each one is a different instruction to the model:
|
|
980
|
+
*
|
|
981
|
+
* - **Verified.** The account and its projects.
|
|
982
|
+
* - **The person cancelled.** Terminal: stop, and say what the credential was
|
|
983
|
+
* needed for. Without this the model's only signal is the same failure it
|
|
984
|
+
* got before, and it retries until the turn ends — while the person has
|
|
985
|
+
* already said no.
|
|
986
|
+
* - **Nothing stored, or the stored pair was rejected.** Open the form and
|
|
987
|
+
* fail with the reason. The model calls again once the person is done.
|
|
988
|
+
*
|
|
989
|
+
* The last two both open the form, which is deliberate: a rejected credential is
|
|
990
|
+
* the case where the person most needs to see the form again, and Huawei's own
|
|
991
|
+
* reason is what tells them what to correct.
|
|
992
|
+
*
|
|
993
|
+
* @param store - the credential store to read.
|
|
994
|
+
* @param deps - host controls: open the form, take a cancellation.
|
|
995
|
+
* @param sessionId - the conversation to open the form in; `undefined` when the
|
|
996
|
+
* call carries no agent, in which case no form can be shown.
|
|
997
|
+
* @returns the account, its projects, and whether the credentials are temporary.
|
|
998
|
+
* @throws with an actionable message in every other case.
|
|
999
|
+
*/
|
|
1000
|
+
async function runAuth(store, deps, sessionId) {
|
|
1001
|
+
const pair = readStoredPair(store);
|
|
1002
|
+
if (deps.takeCancellation() !== void 0) throw new Error("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.");
|
|
1003
|
+
if (pair === void 0) {
|
|
1004
|
+
openForm(deps, sessionId);
|
|
1005
|
+
throw new Error("Not authenticated with Huawei Cloud IAM. The credential form has been opened — ask the user to enter an access key and secret key there, then call auth again.");
|
|
1006
|
+
}
|
|
1007
|
+
const result = await verifyCredentials(pair, { region: VERIFY_REGION$1 });
|
|
1008
|
+
if (!result.ok) {
|
|
1009
|
+
openForm(deps, sessionId);
|
|
1010
|
+
throw new Error(`The stored credentials were rejected and the credential form has been opened again. Huawei Cloud said: ${result.message}`);
|
|
1011
|
+
}
|
|
1012
|
+
return {
|
|
1013
|
+
authenticated: true,
|
|
1014
|
+
account: {
|
|
1015
|
+
accountId: result.account.accountId,
|
|
1016
|
+
name: result.account.name
|
|
1017
|
+
},
|
|
1018
|
+
projects: result.account.projects.map((project) => ({
|
|
1019
|
+
id: project.id,
|
|
1020
|
+
name: project.name,
|
|
1021
|
+
...project.description === void 0 ? {} : { description: project.description }
|
|
1022
|
+
})),
|
|
1023
|
+
sts: result.sts
|
|
1024
|
+
};
|
|
1025
|
+
}
|
|
1026
|
+
/**
|
|
1027
|
+
* Ask for the form, when there is a conversation to put it in.
|
|
1028
|
+
*
|
|
1029
|
+
* A call with no agent has no session, and `conversation.composer` is
|
|
1030
|
+
* session-scoped — a form without a session has nowhere to render. The failure
|
|
1031
|
+
* message still tells the user what to do, so this is a best-effort improvement
|
|
1032
|
+
* rather than the remedy.
|
|
1033
|
+
*
|
|
1034
|
+
* @param deps - host controls.
|
|
1035
|
+
* @param sessionId - the conversation, or `undefined`.
|
|
1036
|
+
*/
|
|
1037
|
+
function openForm(deps, sessionId) {
|
|
1038
|
+
if (sessionId === void 0 || sessionId === "") return;
|
|
1039
|
+
deps.requestForm({ sessionId });
|
|
1040
|
+
}
|
|
1041
|
+
/**
|
|
1042
|
+
* The text the model reads.
|
|
1043
|
+
*
|
|
1044
|
+
* A short summary then the project table: the summary answers the question the
|
|
1045
|
+
* tool was called with, and the table is what the next call needs. The region
|
|
1046
|
+
* is deliberately absent — IAM does not verify it, so printing it would suggest
|
|
1047
|
+
* it had been checked.
|
|
1048
|
+
*
|
|
1049
|
+
* @param value - the verified account.
|
|
1050
|
+
*/
|
|
1051
|
+
function renderAuth(value) {
|
|
1052
|
+
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");
|
|
1053
|
+
const kind = value.sts ? "temporary (STS)" : "stored";
|
|
1054
|
+
return [{
|
|
1055
|
+
type: "text",
|
|
1056
|
+
text: `Authenticated with Huawei Cloud as ${value.account.name} (account id ${value.account.accountId}); using ${kind} credentials.\n\n` + projects
|
|
1057
|
+
}];
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
//#endregion
|
|
1061
|
+
//#region src/form-request.ts
|
|
1062
|
+
/**
|
|
1063
|
+
* The credential form's Host-side control.
|
|
1064
|
+
*
|
|
1065
|
+
* ## What this is for
|
|
1066
|
+
*
|
|
1067
|
+
* `aishell__auth` needs credentials that are not there. It cannot collect them
|
|
1068
|
+
* — a credential a tool returns is a credential in the transcript — so it asks
|
|
1069
|
+
* for the form to be put on screen, the person fills it, and the model calls
|
|
1070
|
+
* `auth` again.
|
|
1071
|
+
*
|
|
1072
|
+
* ## Why the settings document carries the request
|
|
1073
|
+
*
|
|
1074
|
+
* The two halves live apart: the tool runs on the host, the form is browser
|
|
1075
|
+
* code. The host cannot reach the browser over the fetch channel — that channel
|
|
1076
|
+
* is browser→host only — so the request has to ride something the browser
|
|
1077
|
+
* already watches. The settings document is exactly that: the browser half
|
|
1078
|
+
* subscribes to this entry's config through `configForms`, and a volatile field
|
|
1079
|
+
* written by the host shows up there.
|
|
1080
|
+
*
|
|
1081
|
+
* The document carries **only** a request token and a session id. Never a
|
|
1082
|
+
* credential, never a verdict — those travel the other way, over the
|
|
1083
|
+
* credential route, and the browser never receives a stored secret at all.
|
|
1084
|
+
*
|
|
1085
|
+
* ## Why the token, not a boolean
|
|
1086
|
+
*
|
|
1087
|
+
* The browser has to tell "a new request" from "the request it already opened".
|
|
1088
|
+
* With a boolean, a second `auth` failure while the form is up would look
|
|
1089
|
+
* identical to the first and the form would not re-open after the person
|
|
1090
|
+
* cancelled it. The token changes on every request, and the browser compares it
|
|
1091
|
+
* to the last one it acted on.
|
|
1092
|
+
*
|
|
1093
|
+
* ## Why nothing is awaited
|
|
1094
|
+
*
|
|
1095
|
+
* The tool cannot wait for the person — a tool call has no way to be paused for
|
|
1096
|
+
* a human. So `auth` fails, the form appears, and the model calls again. That
|
|
1097
|
+
* round trip is the whole protocol, and it is why the failure message and the
|
|
1098
|
+
* form are worded as a pair.
|
|
1099
|
+
*
|
|
1100
|
+
* @module @huaweidevtools/aishell-dsh-client-credentials/form-request
|
|
1101
|
+
*/
|
|
1102
|
+
/** Field of this entry's config that carries one pending request. */
|
|
1103
|
+
const FORM_REQUEST_FIELD = "credentialFormRequest";
|
|
1104
|
+
/**
|
|
1105
|
+
* Build a request for one session, minting its token.
|
|
1106
|
+
*
|
|
1107
|
+
* The token is minted here rather than by the caller so a request cannot be
|
|
1108
|
+
* recorded without one — the browser's "is this new?" test would then be
|
|
1109
|
+
* comparing against nothing, and the form would not reopen after a cancel.
|
|
1110
|
+
*
|
|
1111
|
+
* @param sessionId - the conversation the form should render in.
|
|
1112
|
+
* @returns the request, and its encoded form for the settings document.
|
|
1113
|
+
*/
|
|
1114
|
+
function formRequest(sessionId) {
|
|
1115
|
+
nextToken += 1;
|
|
1116
|
+
const request = {
|
|
1117
|
+
token: `${Date.now().toString(36)}-${String(nextToken)}`,
|
|
1118
|
+
sessionId
|
|
1119
|
+
};
|
|
1120
|
+
return {
|
|
1121
|
+
request,
|
|
1122
|
+
encoded: encodeRequest(request)
|
|
1123
|
+
};
|
|
1124
|
+
}
|
|
1125
|
+
/** Source of tokens; module-scoped so it is per-host-process. */
|
|
1126
|
+
let nextToken = 0;
|
|
1127
|
+
/**
|
|
1128
|
+
* Serialize a request for the settings document.
|
|
1129
|
+
*
|
|
1130
|
+
* The document holds strings — a volatile `string` field is what the browser
|
|
1131
|
+
* half reads through `configForms` — so the request is JSON. Encoding rather
|
|
1132
|
+
* than reshaping the config into several fields keeps the request atomic: the
|
|
1133
|
+
* browser cannot observe a new token with an old session.
|
|
1134
|
+
*
|
|
1135
|
+
* @param request - the request to encode.
|
|
1136
|
+
*/
|
|
1137
|
+
function encodeRequest(request) {
|
|
1138
|
+
return JSON.stringify(request);
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
//#endregion
|
|
1142
|
+
//#region src/reconcile.ts
|
|
1143
|
+
/**
|
|
1144
|
+
* Build the reconcile state machine.
|
|
1145
|
+
*
|
|
1146
|
+
* Two facts are reconciled independently, because they are independent:
|
|
1147
|
+
* - `credentialsStored` — are AK/SK in the store right now?
|
|
1148
|
+
* - `accessKeyIdHint` — what account name did IAM verification return?
|
|
1149
|
+
*
|
|
1150
|
+
* The hint is re-derived only when the credential material changed since the
|
|
1151
|
+
* last verification. That single trigger covers both reasons to re-verify — a
|
|
1152
|
+
* first-seen credential (the material has never been fingerprinted) and a
|
|
1153
|
+
* rotation (the material differs from the last verified set) — and it keeps a
|
|
1154
|
+
* failing verification (expired STS, IAM outage) from retrying every tick: the
|
|
1155
|
+
* retry keys on the material changing, not on time alone, and a failed verify
|
|
1156
|
+
* still records the fingerprint. Cleared by `resetVerifyBaseline` so a
|
|
1157
|
+
* clear-then-rotate re-verifies from scratch.
|
|
1158
|
+
*
|
|
1159
|
+
* @param deps - collaborators. `readStored`/`readHint` read this plugin's own
|
|
1160
|
+
* mirror so reconcile never depends on config flow-back timing.
|
|
1161
|
+
*/
|
|
1162
|
+
function createCredentialReconciler(deps) {
|
|
1163
|
+
const { verify, recordStatus, readStored, readHint, readPair } = deps;
|
|
1164
|
+
let lastVerifyFingerprint = "";
|
|
1165
|
+
const materialFingerprint = (ak, sk, token) => `${ak}\n${sk}\n${token ?? ""}`;
|
|
1166
|
+
return {
|
|
1167
|
+
reconcile: () => {
|
|
1168
|
+
const pair = readPair();
|
|
1169
|
+
const haveKeys = pair !== void 0;
|
|
1170
|
+
const stored = readStored();
|
|
1171
|
+
const hint = readHint();
|
|
1172
|
+
if (!haveKeys && (stored || hint !== null)) recordStatus([{
|
|
1173
|
+
op: "set",
|
|
1174
|
+
path: ["credentialsStored"],
|
|
1175
|
+
value: false
|
|
1176
|
+
}, {
|
|
1177
|
+
op: "unset",
|
|
1178
|
+
path: ["accessKeyIdHint"]
|
|
1179
|
+
}]);
|
|
1180
|
+
else if (haveKeys && !stored) recordStatus([{
|
|
1181
|
+
op: "set",
|
|
1182
|
+
path: ["credentialsStored"],
|
|
1183
|
+
value: true
|
|
1184
|
+
}]);
|
|
1185
|
+
if (!haveKeys) return;
|
|
1186
|
+
const fingerprint = materialFingerprint(pair.ak, pair.sk, pair.securityToken);
|
|
1187
|
+
const materialChanged = fingerprint !== lastVerifyFingerprint;
|
|
1188
|
+
if (!materialChanged) return;
|
|
1189
|
+
lastVerifyFingerprint = fingerprint;
|
|
1190
|
+
verify(pair.ak, pair.sk, pair.securityToken).then((accountName) => {
|
|
1191
|
+
if (readPair()?.ak !== pair.ak) return;
|
|
1192
|
+
recordStatus([{
|
|
1193
|
+
op: "set",
|
|
1194
|
+
path: ["accessKeyIdHint"],
|
|
1195
|
+
value: accountName
|
|
1196
|
+
}]);
|
|
1197
|
+
}).catch(() => {});
|
|
1198
|
+
},
|
|
1199
|
+
resetVerifyBaseline: () => {
|
|
1200
|
+
lastVerifyFingerprint = "";
|
|
1201
|
+
}
|
|
1202
|
+
};
|
|
1203
|
+
}
|
|
1204
|
+
|
|
896
1205
|
//#endregion
|
|
897
1206
|
//#region src/index.ts
|
|
898
1207
|
/**
|
|
@@ -904,57 +1213,69 @@ const Config = Schema.object({
|
|
|
904
1213
|
credentialsStored: Schema.boolean().default(false).volatile(),
|
|
905
1214
|
accessKeyIdHint: Schema.string().default("").volatile(),
|
|
906
1215
|
lastError: Schema.string().default("").volatile(),
|
|
907
|
-
|
|
1216
|
+
credentialFormRequest: Schema.string().default("").volatile(),
|
|
1217
|
+
credentialFormCancelled: Schema.string().default("").volatile()
|
|
908
1218
|
});
|
|
909
|
-
/** Credential store account names for Huawei Cloud credentials. */
|
|
910
|
-
const AK_ACCOUNT = "HW_ACCESS_KEY";
|
|
911
|
-
const SK_ACCOUNT = "HW_SECRET_KEY";
|
|
912
|
-
const TOKEN_ACCOUNT = "HW_SECURITY_TOKEN";
|
|
913
|
-
/** IAM endpoint host. */
|
|
914
|
-
const IAM_HOST = "iam.myhuaweicloud.com";
|
|
915
1219
|
/** Route the browser half reads status from and saves credentials to. */
|
|
916
1220
|
const CREDENTIALS_PATH = "/api/aishell/credentials";
|
|
917
1221
|
/** Route the browser half clears credentials through (fetch routes have no DELETE). */
|
|
918
1222
|
const CLEAR_PATH = "/api/aishell/credentials/clear";
|
|
919
1223
|
/**
|
|
920
|
-
* Route the browser calls
|
|
1224
|
+
* Route the browser calls when the person cancels the credential form.
|
|
921
1225
|
*
|
|
922
|
-
* Separate from `clear`:
|
|
923
|
-
*
|
|
924
|
-
*
|
|
925
|
-
* say "not now" without wiping anything.
|
|
1226
|
+
* Separate from `clear`: cancelling says "not now" without touching the store.
|
|
1227
|
+
* What it does record is the cancel itself, so the next `auth` call can tell an
|
|
1228
|
+
* unanswered request from a refused one and stop asking.
|
|
926
1229
|
*/
|
|
927
|
-
const
|
|
1230
|
+
const CANCEL_PATH = "/api/aishell/credentials/cancel";
|
|
928
1231
|
/** Largest credential body accepted; a real payload is well under 1 KiB. */
|
|
929
1232
|
const MAX_BODY_BYTES = 8 * 1024;
|
|
930
1233
|
/**
|
|
931
1234
|
* Verify credentials against Huawei Cloud IAM and return the account name.
|
|
932
1235
|
*
|
|
933
|
-
*
|
|
934
|
-
*
|
|
935
|
-
*
|
|
936
|
-
*
|
|
937
|
-
*
|
|
1236
|
+
* Delegates to the shared `verify` module, so the form, the ops `auth` tool
|
|
1237
|
+
* and anything else that asks "are these credentials valid?" get the same
|
|
1238
|
+
* answer from the same endpoint (profile: `GET /v3/projects`, with the account
|
|
1239
|
+
* name read best-effort from `/v3/auth/domains`).
|
|
1240
|
+
*
|
|
1241
|
+
* ## Why not a local domains-only call
|
|
938
1242
|
*
|
|
939
|
-
*
|
|
1243
|
+
* This used to call `/v3/auth/domains` directly, because the only fact this
|
|
1244
|
+
* route needed was the account name shown in the composer chip. That made it a
|
|
1245
|
+
* second, narrower notion of validity: `/v3/projects` rejects a credential with
|
|
1246
|
+
* no visible project, while `/v3/auth/domains` accepts it — so the form said
|
|
1247
|
+
* "saved" for credentials the tools would then refuse. One verifier removes
|
|
1248
|
+
* that gap, and the project list it returns is exactly what a caller needs
|
|
1249
|
+
* before planning a deployment.
|
|
1250
|
+
*
|
|
1251
|
+
* ## The region
|
|
1252
|
+
*
|
|
1253
|
+
* IAM is global: the region only routes to a regional replica and does not
|
|
1254
|
+
* scope the result. The chip's copy is fixed at `cn-north-4` for routing
|
|
1255
|
+
* purposes rather than configured, because verification must succeed even
|
|
1256
|
+
* before a person has chosen a region — and because a wrong region here would
|
|
1257
|
+
* report "invalid credentials" for what is really a typo'd region setting
|
|
1258
|
+
* elsewhere.
|
|
1259
|
+
*
|
|
1260
|
+
* @returns the account name (domain name), falling back to the account id.
|
|
940
1261
|
* @throws Error with a user-readable message when verification fails.
|
|
941
1262
|
*/
|
|
942
|
-
async function verifyCredentials(ak, sk, securityToken) {
|
|
943
|
-
const
|
|
944
|
-
const signed = sign("GET", IAM_HOST, path, {}, "", {
|
|
1263
|
+
async function verifyCredentials$1(ak, sk, securityToken) {
|
|
1264
|
+
const result = await verifyCredentials({
|
|
945
1265
|
ak,
|
|
946
1266
|
sk,
|
|
947
|
-
...securityToken ? {
|
|
948
|
-
});
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
if (resp.status === 403) throw new Error("凭据验证失败:该凭据无 IAM 读取权限(403)");
|
|
952
|
-
if (!resp.ok) throw new Error(`凭据验证失败:华为云返回 ${resp.status}`);
|
|
953
|
-
const body = await resp.json();
|
|
954
|
-
const name$1 = body.domains?.[0]?.name;
|
|
955
|
-
if (!name$1) throw new Error("验证成功但未返回账号名");
|
|
956
|
-
return name$1;
|
|
1267
|
+
...securityToken === void 0 ? {} : { securityToken }
|
|
1268
|
+
}, { region: VERIFY_REGION });
|
|
1269
|
+
if (!result.ok) throw new Error(result.message);
|
|
1270
|
+
return result.account.name;
|
|
957
1271
|
}
|
|
1272
|
+
/**
|
|
1273
|
+
* Region used to route the verification call.
|
|
1274
|
+
*
|
|
1275
|
+
* Not a setting: see {@link verifyCredentials}. Any region replica answers the
|
|
1276
|
+
* same question.
|
|
1277
|
+
*/
|
|
1278
|
+
const VERIFY_REGION = "cn-north-4";
|
|
958
1279
|
/** One JSON error response the browser half renders verbatim. */
|
|
959
1280
|
function jsonError(status, message) {
|
|
960
1281
|
return Response.json({
|
|
@@ -965,14 +1286,14 @@ function jsonError(status, message) {
|
|
|
965
1286
|
/** Read a bounded JSON object body, or throw a user-readable message. */
|
|
966
1287
|
async function readJsonBody(request) {
|
|
967
1288
|
const text = await request.text();
|
|
968
|
-
if (text.length > MAX_BODY_BYTES) throw new Error("
|
|
1289
|
+
if (text.length > MAX_BODY_BYTES) throw new Error("Request body too large.");
|
|
969
1290
|
let parsed;
|
|
970
1291
|
try {
|
|
971
1292
|
parsed = JSON.parse(text);
|
|
972
1293
|
} catch {
|
|
973
|
-
throw new Error("
|
|
1294
|
+
throw new Error("Request body is not valid JSON.");
|
|
974
1295
|
}
|
|
975
|
-
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("
|
|
1296
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("Request body must be a JSON object.");
|
|
976
1297
|
return parsed;
|
|
977
1298
|
}
|
|
978
1299
|
/** Narrow one optional string field; absent and empty both read as undefined. */
|
|
@@ -991,7 +1312,7 @@ function createCredentialRoutes(deps) {
|
|
|
991
1312
|
const { store, verify, recordStatus, hint, notifyChanged } = deps;
|
|
992
1313
|
return {
|
|
993
1314
|
get: () => Promise.resolve(Response.json({
|
|
994
|
-
configured:
|
|
1315
|
+
configured: hasStoredPair(store),
|
|
995
1316
|
accountName: hint()
|
|
996
1317
|
}, { headers: { "cache-control": "no-store" } })),
|
|
997
1318
|
save: async (request) => {
|
|
@@ -1004,7 +1325,7 @@ function createCredentialRoutes(deps) {
|
|
|
1004
1325
|
const ak = optionalString(body.accessKeyId);
|
|
1005
1326
|
const sk = optionalString(body.secretAccessKey);
|
|
1006
1327
|
const token = optionalString(body.securityToken);
|
|
1007
|
-
if (!ak || !sk) return jsonError(400, "Access Key
|
|
1328
|
+
if (!ak || !sk) return jsonError(400, "Access Key and Secret Key are both required.");
|
|
1008
1329
|
let accountName;
|
|
1009
1330
|
try {
|
|
1010
1331
|
accountName = await verify(ak, sk, token);
|
|
@@ -1021,14 +1342,13 @@ function createCredentialRoutes(deps) {
|
|
|
1021
1342
|
}, { status: 422 });
|
|
1022
1343
|
}
|
|
1023
1344
|
try {
|
|
1024
|
-
store
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
if (token) store.set(TOKEN_ACCOUNT, token);
|
|
1345
|
+
writeHuaweiCloud(store, {
|
|
1346
|
+
ak,
|
|
1347
|
+
sk,
|
|
1348
|
+
...token === void 0 ? {} : { securityToken: token }
|
|
1349
|
+
});
|
|
1030
1350
|
} catch (error) {
|
|
1031
|
-
const message =
|
|
1351
|
+
const message = `Credential verified, but storing it failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
1032
1352
|
recordStatus([{
|
|
1033
1353
|
op: "set",
|
|
1034
1354
|
path: ["lastError"],
|
|
@@ -1059,9 +1379,7 @@ function createCredentialRoutes(deps) {
|
|
|
1059
1379
|
});
|
|
1060
1380
|
},
|
|
1061
1381
|
clear: () => {
|
|
1062
|
-
store
|
|
1063
|
-
store.delete(SK_ACCOUNT);
|
|
1064
|
-
store.delete(TOKEN_ACCOUNT);
|
|
1382
|
+
clearCredentials(store);
|
|
1065
1383
|
recordStatus([
|
|
1066
1384
|
{
|
|
1067
1385
|
op: "set",
|
|
@@ -1087,105 +1405,128 @@ const inject = ["settings", "connection"];
|
|
|
1087
1405
|
function apply(ctx, config) {
|
|
1088
1406
|
const store = createCredentialsStore();
|
|
1089
1407
|
const ns = ctx.fiber.entry?.options.id;
|
|
1090
|
-
|
|
1408
|
+
let recordedStored = config.credentialsStored.get() === true;
|
|
1409
|
+
let recordedHint = config.accessKeyIdHint.get() || null;
|
|
1410
|
+
/**
|
|
1411
|
+
* The token of the last form request the person cancelled.
|
|
1412
|
+
*
|
|
1413
|
+
* Kept here rather than read back from the document: `mutate` is async, so a
|
|
1414
|
+
* read would race the write that recorded the cancel, and a token that
|
|
1415
|
+
* outlived its read would answer a later `auth` call instead of the one that
|
|
1416
|
+
* asked.
|
|
1417
|
+
*/
|
|
1418
|
+
let pendingCancellation;
|
|
1419
|
+
/** Apply one batch of ops to the mirror. */
|
|
1420
|
+
const mirrorOps = (ops) => {
|
|
1421
|
+
for (const op of ops) if (op.path[0] === "credentialsStored") recordedStored = op.op === "set" && op.value === true;
|
|
1422
|
+
else if (op.path[0] === "accessKeyIdHint") recordedHint = op.op === "set" && typeof op.value === "string" && op.value.length > 0 ? op.value : null;
|
|
1423
|
+
};
|
|
1424
|
+
/** Record the non-secret status the browser half reads; a refused write is rolled back. */
|
|
1091
1425
|
const recordStatus = (ops) => {
|
|
1092
|
-
if (ns === void 0)
|
|
1426
|
+
if (ns === void 0) {
|
|
1427
|
+
mirrorOps(ops);
|
|
1428
|
+
return;
|
|
1429
|
+
}
|
|
1430
|
+
const before = {
|
|
1431
|
+
stored: recordedStored,
|
|
1432
|
+
hint: recordedHint
|
|
1433
|
+
};
|
|
1434
|
+
mirrorOps(ops);
|
|
1435
|
+
const after = {
|
|
1436
|
+
stored: recordedStored,
|
|
1437
|
+
hint: recordedHint
|
|
1438
|
+
};
|
|
1093
1439
|
ctx.settings.mutate(ns, ops).catch((error) => {
|
|
1440
|
+
if (recordedStored === after.stored && recordedHint === after.hint) {
|
|
1441
|
+
recordedStored = before.stored;
|
|
1442
|
+
recordedHint = before.hint;
|
|
1443
|
+
}
|
|
1094
1444
|
ctx.logger.warn(error);
|
|
1095
1445
|
});
|
|
1096
1446
|
};
|
|
1097
1447
|
const routes = createCredentialRoutes({
|
|
1098
1448
|
store,
|
|
1099
|
-
verify: verifyCredentials,
|
|
1449
|
+
verify: verifyCredentials$1,
|
|
1100
1450
|
recordStatus,
|
|
1101
|
-
hint: () =>
|
|
1451
|
+
hint: () => recordedHint ?? "",
|
|
1102
1452
|
notifyChanged: () => {
|
|
1103
1453
|
ctx.emit("aishell/credentials-updated");
|
|
1104
1454
|
}
|
|
1105
1455
|
});
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
settlePrompt = void 0;
|
|
1114
|
-
recordStatus([{
|
|
1115
|
-
op: "set",
|
|
1116
|
-
path: ["credentialRequestSession"],
|
|
1117
|
-
value: ""
|
|
1118
|
-
}]);
|
|
1119
|
-
settle?.(credentials);
|
|
1120
|
-
};
|
|
1121
|
-
ctx.effect(() => ctx.on("aishell/credential-request", (request) => {
|
|
1122
|
-
settlePrompt?.(void 0);
|
|
1123
|
-
settlePrompt = request.settle;
|
|
1124
|
-
recordStatus([{
|
|
1125
|
-
op: "set",
|
|
1126
|
-
path: ["credentialRequestSession"],
|
|
1127
|
-
value: request.sessionId ?? ""
|
|
1128
|
-
}]);
|
|
1129
|
-
request.signal?.addEventListener("abort", () => {
|
|
1130
|
-
if (settlePrompt === request.settle) settleCredentialForm(void 0);
|
|
1131
|
-
}, { once: true });
|
|
1132
|
-
}), "aishell-credentials: credential form requests");
|
|
1133
|
-
ctx.effect(() => ctx.on("aishell/credentials-updated", () => {
|
|
1134
|
-
if (settlePrompt === void 0) return;
|
|
1135
|
-
const ak$1 = store.get(AK_ACCOUNT);
|
|
1136
|
-
const sk$1 = store.get(SK_ACCOUNT);
|
|
1137
|
-
if (!ak$1 || !sk$1) return;
|
|
1138
|
-
const securityToken = store.get(TOKEN_ACCOUNT);
|
|
1139
|
-
settleCredentialForm({
|
|
1140
|
-
ak: ak$1,
|
|
1141
|
-
sk: sk$1,
|
|
1142
|
-
...securityToken === void 0 ? {} : { securityToken }
|
|
1143
|
-
});
|
|
1144
|
-
}), "aishell-credentials: resume the waiting call");
|
|
1456
|
+
const reconciler = createCredentialReconciler({
|
|
1457
|
+
verify: verifyCredentials$1,
|
|
1458
|
+
recordStatus,
|
|
1459
|
+
readStored: () => recordedStored,
|
|
1460
|
+
readHint: () => recordedHint,
|
|
1461
|
+
readPair: () => readStoredPair(store)
|
|
1462
|
+
});
|
|
1145
1463
|
ctx.effect(() => ctx.connection.fetch.register({
|
|
1146
1464
|
path: CREDENTIALS_PATH,
|
|
1147
1465
|
methods: ["GET", "POST"],
|
|
1148
1466
|
requestBody: "buffered",
|
|
1149
|
-
fetch: (request) => request.method === "GET" ? routes.get() : routes.save(request)
|
|
1467
|
+
fetch: (request) => request.method === "GET" ? (reconciler.reconcile(), routes.get()) : routes.save(request)
|
|
1150
1468
|
}), "aishell-credentials: credentials route");
|
|
1151
1469
|
ctx.effect(() => ctx.connection.fetch.register({
|
|
1152
|
-
path:
|
|
1470
|
+
path: CANCEL_PATH,
|
|
1153
1471
|
methods: ["POST"],
|
|
1154
1472
|
requestBody: "buffered",
|
|
1155
|
-
fetch:
|
|
1156
|
-
|
|
1473
|
+
fetch: async (request) => {
|
|
1474
|
+
let body;
|
|
1475
|
+
try {
|
|
1476
|
+
body = await request.json();
|
|
1477
|
+
} catch {
|
|
1478
|
+
return Response.json({
|
|
1479
|
+
ok: false,
|
|
1480
|
+
error: "Request body is not valid JSON."
|
|
1481
|
+
}, { status: 400 });
|
|
1482
|
+
}
|
|
1483
|
+
const token = body?.token;
|
|
1484
|
+
if (typeof token !== "string" || token === "") return Response.json({
|
|
1485
|
+
ok: false,
|
|
1486
|
+
error: "token is required."
|
|
1487
|
+
}, { status: 400 });
|
|
1488
|
+
pendingCancellation = token;
|
|
1489
|
+
if (ns === void 0) return Response.json({ ok: true });
|
|
1490
|
+
ctx.settings.mutate(ns, [{
|
|
1491
|
+
op: "set",
|
|
1492
|
+
path: ["credentialFormCancelled"],
|
|
1493
|
+
value: token
|
|
1494
|
+
}]).catch((error) => {
|
|
1495
|
+
ctx.logger.warn(error);
|
|
1496
|
+
});
|
|
1497
|
+
return Response.json({ ok: true });
|
|
1498
|
+
}
|
|
1499
|
+
}), "aishell-credentials: cancel route");
|
|
1157
1500
|
ctx.effect(() => ctx.connection.fetch.register({
|
|
1158
|
-
path:
|
|
1501
|
+
path: CLEAR_PATH,
|
|
1159
1502
|
methods: ["POST"],
|
|
1160
1503
|
requestBody: "buffered",
|
|
1161
1504
|
fetch: () => {
|
|
1162
|
-
|
|
1163
|
-
return
|
|
1505
|
+
reconciler.resetVerifyBaseline();
|
|
1506
|
+
return routes.clear();
|
|
1164
1507
|
}
|
|
1165
|
-
}), "aishell-credentials:
|
|
1166
|
-
|
|
1167
|
-
const
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
}]);
|
|
1188
|
-
}).catch(() => {});
|
|
1508
|
+
}), "aishell-credentials: clear route");
|
|
1509
|
+
reconciler.reconcile();
|
|
1510
|
+
const reconcileTimer = setInterval(reconciler.reconcile, 3e4);
|
|
1511
|
+
ctx.effect(() => () => clearInterval(reconcileTimer), "aishell-credentials: status reconcile timer");
|
|
1512
|
+
registerAuthTool(ctx, store, {
|
|
1513
|
+
requestForm: ({ sessionId }) => {
|
|
1514
|
+
const { encoded } = formRequest(sessionId);
|
|
1515
|
+
if (ns === void 0) return;
|
|
1516
|
+
ctx.settings.mutate(ns, [{
|
|
1517
|
+
op: "set",
|
|
1518
|
+
path: [FORM_REQUEST_FIELD],
|
|
1519
|
+
value: encoded
|
|
1520
|
+
}]).catch((error) => {
|
|
1521
|
+
ctx.logger.warn(error);
|
|
1522
|
+
});
|
|
1523
|
+
},
|
|
1524
|
+
takeCancellation: () => {
|
|
1525
|
+
const token = pendingCancellation;
|
|
1526
|
+
pendingCancellation = void 0;
|
|
1527
|
+
return token;
|
|
1528
|
+
}
|
|
1529
|
+
});
|
|
1189
1530
|
ctx.effect(() => ctx.settings.configure({ auto: false }, ctx.fiber));
|
|
1190
1531
|
}
|
|
1191
1532
|
|