@amaster.ai/client 1.1.72 → 1.1.73
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +57 -0
- package/dist/index.cjs +897 -27
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +13 -4
- package/dist/index.d.ts +13 -4
- package/dist/index.js +897 -30
- package/dist/index.js.map +1 -1
- package/package.json +11 -11
- package/types/auth/index.d.ts +1 -0
- package/types/common.d.ts +3 -0
- package/types/http.d.ts +8 -130
- package/types/index.d.ts +40 -12
package/dist/index.cjs
CHANGED
|
@@ -10,6 +10,7 @@ var functionClient = require('@amaster.ai/function-client');
|
|
|
10
10
|
var ttsClient = require('@amaster.ai/tts-client');
|
|
11
11
|
var s3Client = require('@amaster.ai/s3-client');
|
|
12
12
|
var httpClient = require('@amaster.ai/http-client');
|
|
13
|
+
var tenancy = require('@amaster.ai/auth-client/tenancy');
|
|
13
14
|
|
|
14
15
|
// src/client.ts
|
|
15
16
|
|
|
@@ -561,9 +562,744 @@ function createKnowledgeClient(http) {
|
|
|
561
562
|
}
|
|
562
563
|
};
|
|
563
564
|
}
|
|
564
|
-
|
|
565
|
-
|
|
565
|
+
function failure(code, status, captured) {
|
|
566
|
+
return { data: null, status, error: { code, status, message: code }, scopeCapture: captured };
|
|
567
|
+
}
|
|
568
|
+
function waitForRefresh(operation, scope, captured, signal) {
|
|
569
|
+
return new Promise((resolve, reject) => {
|
|
570
|
+
let remove = () => {
|
|
571
|
+
};
|
|
572
|
+
const clean = () => {
|
|
573
|
+
remove();
|
|
574
|
+
signal?.removeEventListener?.("abort", abort);
|
|
575
|
+
};
|
|
576
|
+
const abort = () => {
|
|
577
|
+
clean();
|
|
578
|
+
reject(new Error("request_cancelled"));
|
|
579
|
+
};
|
|
580
|
+
operation.then(
|
|
581
|
+
(value) => {
|
|
582
|
+
clean();
|
|
583
|
+
resolve(value);
|
|
584
|
+
},
|
|
585
|
+
(error) => {
|
|
586
|
+
clean();
|
|
587
|
+
reject(error);
|
|
588
|
+
}
|
|
589
|
+
);
|
|
590
|
+
try {
|
|
591
|
+
remove = scope.onInvalidate(captured, abort);
|
|
592
|
+
} catch (error) {
|
|
593
|
+
reject(error);
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
if (signal?.aborted) abort();
|
|
597
|
+
else signal?.addEventListener?.("abort", abort, { once: true });
|
|
598
|
+
});
|
|
599
|
+
}
|
|
600
|
+
function createScopedHttpClient(transport, scope, auth, autoRefresh, onUnauthorized) {
|
|
601
|
+
let refreshing = null;
|
|
602
|
+
return {
|
|
603
|
+
async request(config) {
|
|
604
|
+
let captured;
|
|
605
|
+
try {
|
|
606
|
+
const token = auth.getAccessToken();
|
|
607
|
+
const dispatchRevision = auth.getCredentialRevision();
|
|
608
|
+
if (auth.getAccessToken() !== token) return failure("scope_changed", 409);
|
|
609
|
+
captured = config.scopeCapture ?? scope.capture(config.scopeLevel ?? "tenant");
|
|
610
|
+
scope.assertCurrent(captured);
|
|
611
|
+
if (!token) return failure("unauthenticated", 401, captured);
|
|
612
|
+
const headers = Object.fromEntries(
|
|
613
|
+
Object.entries(config.headers ?? {}).filter(
|
|
614
|
+
([name]) => name.toLowerCase() !== "authorization"
|
|
615
|
+
)
|
|
616
|
+
);
|
|
617
|
+
const send = (accessToken) => transport.request({
|
|
618
|
+
...config,
|
|
619
|
+
scopeCapture: captured,
|
|
620
|
+
headers: { ...headers, Authorization: `Bearer ${accessToken}` }
|
|
621
|
+
});
|
|
622
|
+
const assertCurrent = () => {
|
|
623
|
+
auth.getAccessToken();
|
|
624
|
+
scope.assertCurrent(captured);
|
|
625
|
+
};
|
|
626
|
+
let result = await send(token);
|
|
627
|
+
assertCurrent();
|
|
628
|
+
const method = String(config.method ?? "GET").toUpperCase();
|
|
629
|
+
const safeRead = ["GET", "HEAD", "OPTIONS"].includes(method) || method === "POST" && config.url === "/api/tenancy/authorize";
|
|
630
|
+
if (autoRefresh && safeRead && !token.startsWith("amsvc1.") && result.status === 401) {
|
|
631
|
+
const revision = auth.getCredentialRevision();
|
|
632
|
+
assertCurrent();
|
|
633
|
+
const alreadyRenewed = revision !== dispatchRevision ? auth.getAccessToken() : null;
|
|
634
|
+
if (alreadyRenewed && alreadyRenewed !== token) {
|
|
635
|
+
result = await send(alreadyRenewed);
|
|
636
|
+
assertCurrent();
|
|
637
|
+
if (result.status === 401) onUnauthorized?.();
|
|
638
|
+
return result;
|
|
639
|
+
}
|
|
640
|
+
if (!refreshing || refreshing.revision !== revision) {
|
|
641
|
+
const flight = { revision, promise: auth.refreshToken() };
|
|
642
|
+
refreshing = flight;
|
|
643
|
+
void flight.promise.finally(() => {
|
|
644
|
+
if (refreshing === flight) refreshing = null;
|
|
645
|
+
}).catch(() => {
|
|
646
|
+
});
|
|
647
|
+
}
|
|
648
|
+
const refreshed = await waitForRefresh(
|
|
649
|
+
refreshing.promise,
|
|
650
|
+
scope,
|
|
651
|
+
captured,
|
|
652
|
+
config.signal
|
|
653
|
+
);
|
|
654
|
+
assertCurrent();
|
|
655
|
+
if (refreshed.error) return { ...refreshed, data: null, scopeCapture: captured };
|
|
656
|
+
const nextToken = auth.getAccessToken();
|
|
657
|
+
assertCurrent();
|
|
658
|
+
if (!nextToken || nextToken !== refreshed.data?.accessToken)
|
|
659
|
+
return failure("scope_changed", 409, captured);
|
|
660
|
+
result = await send(nextToken);
|
|
661
|
+
assertCurrent();
|
|
662
|
+
}
|
|
663
|
+
if (result.status === 401) onUnauthorized?.();
|
|
664
|
+
return result;
|
|
665
|
+
} catch (error) {
|
|
666
|
+
if (error instanceof httpClient.RequestScopeError)
|
|
667
|
+
return failure(error.code, error.status, captured);
|
|
668
|
+
if (captured && !scope.isCurrent(captured))
|
|
669
|
+
return failure("scope_changed", 409, captured);
|
|
670
|
+
if (config.signal?.aborted) return failure("request_cancelled", 0, captured);
|
|
671
|
+
return failure("dependency_unverifiable", 503, captured);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
async function discoverApplicationScope(options) {
|
|
677
|
+
const asserted = /* @__PURE__ */ new Map();
|
|
678
|
+
const headers = Object.fromEntries(
|
|
679
|
+
Object.entries(options.headers ?? {}).filter(([key]) => {
|
|
680
|
+
if (key.toLowerCase() === "x-app-tenant-id") throw new httpClient.RequestScopeError("invalid_scope");
|
|
681
|
+
return key.toLowerCase() !== "authorization";
|
|
682
|
+
})
|
|
683
|
+
);
|
|
684
|
+
for (const [key, raw] of Object.entries(headers)) {
|
|
685
|
+
const name = key.toLowerCase();
|
|
686
|
+
const field = ["x-tenant-id", "x-app-id", "x-app-code"].includes(name) ? "applicationCode" : ["x-env", "env"].includes(name) ? "environment" : null;
|
|
687
|
+
if (!field) continue;
|
|
688
|
+
const candidate = new httpClient.RequestScopeController({
|
|
689
|
+
applicationCode: field === "applicationCode" ? raw : "context",
|
|
690
|
+
environment: field === "environment" ? raw : "dev",
|
|
691
|
+
storage: null
|
|
692
|
+
});
|
|
693
|
+
const value2 = candidate[field];
|
|
694
|
+
if (asserted.has(field) && asserted.get(field) !== value2)
|
|
695
|
+
throw new httpClient.RequestScopeError("invalid_scope");
|
|
696
|
+
asserted.set(field, value2);
|
|
697
|
+
}
|
|
698
|
+
if (asserted.has("applicationCode")) headers["x-tenant-id"] = asserted.get("applicationCode");
|
|
699
|
+
if (asserted.has("environment")) headers["x-env"] = asserted.get("environment");
|
|
700
|
+
const http = httpClient.createHttpClient({
|
|
701
|
+
baseURL: options.baseURL,
|
|
702
|
+
withCredentials: options.withCredentials,
|
|
703
|
+
runtime: options.runtime,
|
|
704
|
+
headers,
|
|
705
|
+
transformResponse: (body) => {
|
|
706
|
+
if (body && typeof body === "object" && "statusCode" in body && body.statusCode === 200 && "data" in body)
|
|
707
|
+
return body.data;
|
|
708
|
+
return null;
|
|
709
|
+
}
|
|
710
|
+
});
|
|
711
|
+
const result = await http.request({
|
|
712
|
+
url: "/api/auth/context",
|
|
713
|
+
method: "GET",
|
|
714
|
+
maxRedirects: 0,
|
|
715
|
+
timeout: 1e4,
|
|
716
|
+
headers: { "Cache-Control": "no-cache" }
|
|
717
|
+
});
|
|
718
|
+
if (result.error) throw Object.assign(new Error(result.error.message), result.error);
|
|
719
|
+
const data = result.data;
|
|
720
|
+
const unavailable = () => Object.assign(new Error("Cannot verify application context"), {
|
|
721
|
+
status: 503,
|
|
722
|
+
code: "dependency_unverifiable"
|
|
723
|
+
});
|
|
724
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) throw unavailable();
|
|
725
|
+
const value = data;
|
|
726
|
+
if (value.protocolVersion !== "1" || typeof value.applicationCode !== "string" || typeof value.environment !== "string" || typeof value.tenancyEnabled !== "boolean" || value.tenantSelectionEnabled !== void 0 && (value.tenantSelectionEnabled !== false || !value.tenancyEnabled) || value.legacySessionMigration !== void 0 && typeof value.legacySessionMigration !== "boolean" || value.legacySessionMigration === true && !value.tenancyEnabled)
|
|
727
|
+
throw unavailable();
|
|
728
|
+
const scope = { applicationCode: value.applicationCode, environment: value.environment };
|
|
729
|
+
try {
|
|
730
|
+
const validated = new httpClient.RequestScopeController(scope);
|
|
731
|
+
if (validated.environment !== scope.environment) throw unavailable();
|
|
732
|
+
} catch {
|
|
733
|
+
throw unavailable();
|
|
734
|
+
}
|
|
735
|
+
for (const [field, value2] of asserted)
|
|
736
|
+
if (scope[field] !== value2) throw new httpClient.RequestScopeError("invalid_scope");
|
|
737
|
+
return {
|
|
738
|
+
scope,
|
|
739
|
+
tenancyEnabled: value.tenancyEnabled,
|
|
740
|
+
...value.tenantSelectionEnabled === false ? { tenantSelectionEnabled: false } : {},
|
|
741
|
+
...value.legacySessionMigration === true ? { legacySessionMigration: true } : {}
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
function createInitializationFactories(options, http, getToken, getUserUid, wait, check, generation, getAccountScope) {
|
|
745
|
+
function guard(target, asyncMethods, localMethods, cleanup) {
|
|
746
|
+
let epoch = 0;
|
|
747
|
+
let destroyed = false;
|
|
748
|
+
return new Proxy(target, {
|
|
749
|
+
get(owner, property, receiver) {
|
|
750
|
+
const value = Reflect.get(owner, property, receiver);
|
|
751
|
+
if (typeof value !== "function" || typeof property !== "string") return value;
|
|
752
|
+
if (asyncMethods.includes(property))
|
|
753
|
+
return async (...args) => {
|
|
754
|
+
const expected = epoch;
|
|
755
|
+
const scopeGeneration = generation();
|
|
756
|
+
await wait();
|
|
757
|
+
if (destroyed || expected !== epoch || scopeGeneration !== generation())
|
|
758
|
+
throw Object.assign(
|
|
759
|
+
new Error("Instance operation was cancelled during initialization"),
|
|
760
|
+
{ code: "scope_changed", status: 409 }
|
|
761
|
+
);
|
|
762
|
+
return value.apply(owner, args);
|
|
763
|
+
};
|
|
764
|
+
return (...args) => {
|
|
765
|
+
if (cleanup.includes(property)) {
|
|
766
|
+
epoch++;
|
|
767
|
+
if (property === "destroy") destroyed = true;
|
|
768
|
+
} else if (!localMethods.includes(property)) check();
|
|
769
|
+
return value.apply(owner, args);
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
});
|
|
773
|
+
}
|
|
774
|
+
const auth = { getAccessToken: getToken };
|
|
775
|
+
const copilot = copilotClient.createCopilotClient(
|
|
776
|
+
{ request: (config) => http.request({ ...config, scopeLevel: "application", preserveBusinessResponse: true }) },
|
|
777
|
+
options.baseURL,
|
|
778
|
+
getToken,
|
|
779
|
+
getUserUid,
|
|
780
|
+
getAccountScope
|
|
781
|
+
);
|
|
782
|
+
return {
|
|
783
|
+
asr: (config) => guard(
|
|
784
|
+
asrClient.createASRClient(auth)(config),
|
|
785
|
+
["connect", "startRecording", "stopRecording"],
|
|
786
|
+
["isRecording", "isConnected"],
|
|
787
|
+
["close"]
|
|
788
|
+
),
|
|
789
|
+
asrHttp: (config) => guard(
|
|
790
|
+
asrClient.createASRHttpClient({ ...auth, http })(config),
|
|
791
|
+
["startRecording", "stopRecording", "recordAndRecognize", "recognizeFile", "recognizeUrl"],
|
|
792
|
+
[],
|
|
793
|
+
[]
|
|
794
|
+
),
|
|
795
|
+
tts: (config) => guard(
|
|
796
|
+
ttsClient.createTTSClient(auth)(config),
|
|
797
|
+
["connect", "speak"],
|
|
798
|
+
["isConnected", "hasAudio", "isResponseDone", "isPlaying", "isStreamingPlayback"],
|
|
799
|
+
["close", "stop"]
|
|
800
|
+
),
|
|
801
|
+
copilot: {
|
|
802
|
+
createConversationController: (config) => guard(
|
|
803
|
+
copilot.createConversationController(config),
|
|
804
|
+
[
|
|
805
|
+
"init",
|
|
806
|
+
"sendMessage",
|
|
807
|
+
"cancelChat",
|
|
808
|
+
"startNewConversation",
|
|
809
|
+
"loadHistory",
|
|
810
|
+
"loadMoreHistory"
|
|
811
|
+
],
|
|
812
|
+
[
|
|
813
|
+
"getSnapshot",
|
|
814
|
+
"subscribe",
|
|
815
|
+
"resetConversation",
|
|
816
|
+
"getConversation",
|
|
817
|
+
"clearConversation",
|
|
818
|
+
"removeMessage",
|
|
819
|
+
"updateMessage"
|
|
820
|
+
],
|
|
821
|
+
["destroy", "abort"]
|
|
822
|
+
)
|
|
823
|
+
}
|
|
824
|
+
};
|
|
825
|
+
}
|
|
826
|
+
function createAutomaticClient(options, construct) {
|
|
827
|
+
const captured = { ...options, headers: { ...options.headers } };
|
|
828
|
+
let client;
|
|
829
|
+
let instanceAccountScope;
|
|
830
|
+
let tenantSelectionEnabled = true;
|
|
831
|
+
let pendingToken;
|
|
832
|
+
let hintKey;
|
|
833
|
+
try {
|
|
834
|
+
const endpoint = new URL(options.baseURL ?? "", "https://application.invalid");
|
|
835
|
+
if (!endpoint.username && !endpoint.password && !endpoint.search && !endpoint.hash) {
|
|
836
|
+
const contextHeaders = Object.entries(captured.headers).filter(([key]) => ["x-tenant-id", "x-app-id", "x-app-code", "x-env", "env"].includes(key.toLowerCase())).map(([key, value]) => [key.toLowerCase(), value]).sort(([a], [b]) => a.localeCompare(b));
|
|
837
|
+
hintKey = JSON.stringify([options.baseURL ?? "", contextHeaders]);
|
|
838
|
+
}
|
|
839
|
+
} catch {
|
|
840
|
+
}
|
|
841
|
+
const suppliedStorage = options.storage && typeof options.storage.getItem === "function" ? options.storage : void 0;
|
|
842
|
+
const storedApplication = suppliedStorage ? { reader: authClient.createStoredAuthReader(void 0, suppliedStorage), clearConsumerHint() {
|
|
843
|
+
}, remember(_value) {
|
|
844
|
+
} } : authClient.createStoredApplicationAuthReader(hintKey);
|
|
845
|
+
const storedAuth = storedApplication.reader;
|
|
846
|
+
let failed = false;
|
|
847
|
+
let generation = 0;
|
|
848
|
+
const queued = [];
|
|
849
|
+
const initialize = () => discoverApplicationScope(captured).then(async ({ scope, tenancyEnabled, tenantSelectionEnabled: selectionEnabled, legacySessionMigration }) => {
|
|
850
|
+
tenantSelectionEnabled = selectionEnabled !== false;
|
|
851
|
+
storedApplication.remember({ ...scope, tenancyEnabled });
|
|
852
|
+
if (!tenantSelectionEnabled) storedApplication.clearConsumerHint();
|
|
853
|
+
const legacyToken = !suppliedStorage && legacySessionMigration && pendingToken === void 0 && !authClient.createStoredAuthReader(JSON.stringify([scope.applicationCode, scope.environment])).getAccessToken() ? authClient.takePreservedLegacyAccessToken(JSON.stringify([scope.applicationCode, scope.environment])) : null;
|
|
854
|
+
const actions = queued.splice(0);
|
|
855
|
+
const servingScope = tenantSelectionEnabled ? scope : { ...scope, storage: null };
|
|
856
|
+
instanceAccountScope = new httpClient.RequestScopeController({ ...scope, storage: null });
|
|
857
|
+
client = construct({ ...captured, tenancy: tenancyEnabled ? servingScope : void 0 }, (auth2) => {
|
|
858
|
+
auth2.on("credentialsChanged", (kind) => {
|
|
859
|
+
if (kind !== "refresh") instanceAccountScope?.clear();
|
|
860
|
+
});
|
|
861
|
+
if (legacyToken) auth2.setAccessToken(legacyToken);
|
|
862
|
+
actions.filter(({ path }) => path[0] === "auth").forEach(({ method, args }) => auth2[method](...args));
|
|
863
|
+
});
|
|
864
|
+
actions.filter(({ path }) => path[0] !== "auth").forEach(({ path, method, args }) => resolve(path)?.[method](...args));
|
|
865
|
+
queued.splice(0).forEach(({ path, method, args }) => invoke(path, method, args));
|
|
866
|
+
if (tenancyEnabled && legacySessionMigration && client.auth.isAuthenticated())
|
|
867
|
+
await client.auth.getMe();
|
|
868
|
+
});
|
|
869
|
+
const observe = (operation) => {
|
|
870
|
+
void operation.catch(() => {
|
|
871
|
+
failed = true;
|
|
872
|
+
const local = queued.filter(
|
|
873
|
+
({ path, method }) => path[0] === "auth" && ["on", "off", "setAccessToken", "clearAuth"].includes(method) || path[0] === "tenancy" && method === "clearTenant"
|
|
874
|
+
);
|
|
875
|
+
queued.splice(0, queued.length, ...local);
|
|
876
|
+
});
|
|
877
|
+
return operation;
|
|
878
|
+
};
|
|
879
|
+
let initialized = observe(initialize());
|
|
880
|
+
const ready = () => {
|
|
881
|
+
if (failed && !client) {
|
|
882
|
+
failed = false;
|
|
883
|
+
initialized = observe(initialize());
|
|
884
|
+
}
|
|
885
|
+
return initialized;
|
|
886
|
+
};
|
|
887
|
+
const pending = () => Object.assign(new Error("Application context is not ready; await client.ready()"), {
|
|
888
|
+
code: "context_pending",
|
|
889
|
+
status: 503
|
|
890
|
+
});
|
|
891
|
+
const resolve = (path) => path.reduce((value, key) => value?.[key], client);
|
|
892
|
+
const invoke = (path, method, args) => {
|
|
893
|
+
const owner = resolve(path);
|
|
894
|
+
if (!owner) throw new tenancy.TenancyCapabilityError("tenant APIs on a non-tenancy application");
|
|
895
|
+
return owner[method](...args);
|
|
896
|
+
};
|
|
897
|
+
const changesScope = (path, method) => path[0] === "auth" && /^(login|logout|register|exchangeOAuthLoginTicket|handleOAuthCallback)/.test(method) || path[0] === "tenancy" && method === "selectTenant";
|
|
898
|
+
const afterReady = (path, method, args) => {
|
|
899
|
+
if (path[0] === "tenancy" && method === "selectTenant") storedApplication.clearConsumerHint();
|
|
900
|
+
if (changesScope(path, method)) generation++;
|
|
901
|
+
const capturedGeneration = generation;
|
|
902
|
+
return ready().then(
|
|
903
|
+
() => capturedGeneration === generation ? invoke(path, method, args) : {
|
|
904
|
+
data: null,
|
|
905
|
+
status: 409,
|
|
906
|
+
error: {
|
|
907
|
+
status: 409,
|
|
908
|
+
code: "scope_changed",
|
|
909
|
+
message: "Context changed during initialization"
|
|
910
|
+
}
|
|
911
|
+
},
|
|
912
|
+
(error) => ({
|
|
913
|
+
data: null,
|
|
914
|
+
status: error.status ?? 503,
|
|
915
|
+
error: {
|
|
916
|
+
status: error.status ?? 503,
|
|
917
|
+
code: error.code ?? "dependency_unverifiable",
|
|
918
|
+
message: error.message
|
|
919
|
+
}
|
|
920
|
+
})
|
|
921
|
+
);
|
|
922
|
+
};
|
|
923
|
+
function sync(path, method, args) {
|
|
924
|
+
if (!client && method === "getOAuthLoginURL") {
|
|
925
|
+
const query = new URLSearchParams();
|
|
926
|
+
if (args[1]) query.set("redirect_uri", String(args[1]));
|
|
927
|
+
const path2 = `/api/auth/oauth/${args[0]}${query.size ? `?${query}` : ""}`;
|
|
928
|
+
if (!options.baseURL) return path2;
|
|
929
|
+
return new URL(path2, typeof window === "undefined" ? options.baseURL : new URL(options.baseURL, window.location.href).href).href;
|
|
930
|
+
}
|
|
931
|
+
if (client) {
|
|
932
|
+
if (["setAccessToken", "clearAuth", "loginWithOAuth"].includes(method)) generation++;
|
|
933
|
+
return invoke(path, method, args);
|
|
934
|
+
}
|
|
935
|
+
if (method === "setAccessToken" || method === "clearAuth") {
|
|
936
|
+
generation++;
|
|
937
|
+
pendingToken = method === "setAccessToken" ? args[0] : null;
|
|
938
|
+
queued.push({ path, method, args });
|
|
939
|
+
return;
|
|
940
|
+
}
|
|
941
|
+
if (["on", "off", "loginWithOAuth", "bindOAuth"].includes(method)) {
|
|
942
|
+
if (method === "loginWithOAuth") generation++;
|
|
943
|
+
queued.push({ path, method, args });
|
|
944
|
+
return;
|
|
945
|
+
}
|
|
946
|
+
if (method === "getAccessToken")
|
|
947
|
+
return failed ? null : pendingToken !== void 0 ? pendingToken : storedAuth.getAccessToken();
|
|
948
|
+
if (method === "isAuthenticated") return !!sync(path, "getAccessToken", []);
|
|
949
|
+
if (!failed && pendingToken === void 0 && method in storedAuth)
|
|
950
|
+
return storedAuth[method](...args);
|
|
951
|
+
return false;
|
|
952
|
+
}
|
|
953
|
+
function service(path) {
|
|
954
|
+
return new Proxy(
|
|
955
|
+
{},
|
|
956
|
+
{
|
|
957
|
+
get(_target, property) {
|
|
958
|
+
if (typeof property !== "string" || property === "then") return void 0;
|
|
959
|
+
if (path[0] === "auth" && property === "getCredentialRevision") return void 0;
|
|
960
|
+
if (path[0] === "tenancy") {
|
|
961
|
+
if (property === "enabled") return client ? !!client.tenancy && tenantSelectionEnabled : null;
|
|
962
|
+
if (["applicationCode", "environment", "appTenantId", "subject", "snapshot", "authorization"].includes(
|
|
963
|
+
property
|
|
964
|
+
))
|
|
965
|
+
return resolve(path)?.[property] ?? null;
|
|
966
|
+
if (["capture", "onInvalidate"].includes(property))
|
|
967
|
+
return (...args) => {
|
|
968
|
+
if (!client) throw pending();
|
|
969
|
+
return invoke(path, property, args);
|
|
970
|
+
};
|
|
971
|
+
if (property === "isCurrent")
|
|
972
|
+
return (...args) => client ? invoke(path, property, args) : false;
|
|
973
|
+
if (property === "clearTenant")
|
|
974
|
+
return () => {
|
|
975
|
+
if (client) resolve(path)?.clearTenant();
|
|
976
|
+
else {
|
|
977
|
+
storedApplication.clearConsumerHint();
|
|
978
|
+
generation++;
|
|
979
|
+
queued.push({ path, method: "clearTenant", args: [] });
|
|
980
|
+
}
|
|
981
|
+
};
|
|
982
|
+
if (!["account", "listAccessible", "current", "selectTenant", "authorize"].includes(property))
|
|
983
|
+
return void 0;
|
|
984
|
+
}
|
|
985
|
+
if (path[0] === "auth" && [
|
|
986
|
+
"on",
|
|
987
|
+
"off",
|
|
988
|
+
"setAccessToken",
|
|
989
|
+
"clearAuth",
|
|
990
|
+
"getAccessToken",
|
|
991
|
+
"isAuthenticated",
|
|
992
|
+
"hasRole",
|
|
993
|
+
"hasPermission",
|
|
994
|
+
"hasAnyPermission",
|
|
995
|
+
"hasAllPermissions",
|
|
996
|
+
"loginWithOAuth",
|
|
997
|
+
"getOAuthLoginURL",
|
|
998
|
+
"bindOAuth"
|
|
999
|
+
].includes(property))
|
|
1000
|
+
return (...args) => sync(path, property, args);
|
|
1001
|
+
if (path[0] === "copilot" && property === "createConversationController")
|
|
1002
|
+
return (...args) => {
|
|
1003
|
+
if (!client) return factories.copilot.createConversationController(...args);
|
|
1004
|
+
return invoke(path, property, args);
|
|
1005
|
+
};
|
|
1006
|
+
if (path[0] === "chatflow" && property === "stream")
|
|
1007
|
+
return async function* (...args) {
|
|
1008
|
+
await ready();
|
|
1009
|
+
yield* invoke(path, property, args);
|
|
1010
|
+
};
|
|
1011
|
+
return (...args) => {
|
|
1012
|
+
if (client) {
|
|
1013
|
+
if (changesScope(path, property)) generation++;
|
|
1014
|
+
return invoke(path, property, args);
|
|
1015
|
+
}
|
|
1016
|
+
return afterReady(path, property, args);
|
|
1017
|
+
};
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
);
|
|
1021
|
+
}
|
|
1022
|
+
const auth = service(["auth"]);
|
|
1023
|
+
const checkFactory = () => {
|
|
1024
|
+
if (!client) throw pending();
|
|
1025
|
+
};
|
|
1026
|
+
const factories = createInitializationFactories(
|
|
1027
|
+
captured,
|
|
1028
|
+
service(["http"]),
|
|
1029
|
+
() => auth.getAccessToken(),
|
|
1030
|
+
() => client ? authClient.readCachedAuthUser(client.auth)?.uid ?? null : null,
|
|
1031
|
+
async () => {
|
|
1032
|
+
await ready();
|
|
1033
|
+
checkFactory();
|
|
1034
|
+
},
|
|
1035
|
+
checkFactory,
|
|
1036
|
+
() => generation,
|
|
1037
|
+
() => instanceAccountScope
|
|
1038
|
+
);
|
|
1039
|
+
const factory = (name) => (...args) => {
|
|
1040
|
+
if (!client) return factories[name](...args);
|
|
1041
|
+
return invoke([], name, args);
|
|
1042
|
+
};
|
|
1043
|
+
return {
|
|
1044
|
+
ready,
|
|
1045
|
+
auth,
|
|
1046
|
+
tenancy: service(["tenancy"]),
|
|
1047
|
+
entity: service(["entity"]),
|
|
1048
|
+
bpm: service(["bpm"]),
|
|
1049
|
+
workflow: service(["workflow"]),
|
|
1050
|
+
chatflow: service(["chatflow"]),
|
|
1051
|
+
copilot: service(["copilot"]),
|
|
1052
|
+
function: service(["function"]),
|
|
1053
|
+
knowledge: service(["knowledge"]),
|
|
1054
|
+
s3: service(["s3"]),
|
|
1055
|
+
http: service(["http"]),
|
|
1056
|
+
asr: factory("asr"),
|
|
1057
|
+
asrHttp: factory("asrHttp"),
|
|
1058
|
+
tts: factory("tts"),
|
|
1059
|
+
isAuthenticated: () => auth.isAuthenticated(),
|
|
1060
|
+
getAccessToken: () => auth.getAccessToken(),
|
|
1061
|
+
setAccessToken: (token) => auth.setAccessToken(token),
|
|
1062
|
+
clearAuth: () => auth.clearAuth()
|
|
1063
|
+
};
|
|
1064
|
+
}
|
|
1065
|
+
var record = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
1066
|
+
var contextText = (value) => typeof value === "string" && value.length > 0 && value.length <= 4096 && value.trim() === value && // Reject control characters in identifiers received across the trust boundary.
|
|
1067
|
+
// eslint-disable-next-line no-control-regex
|
|
1068
|
+
!/[\u0000-\u001f\u007f]/.test(value);
|
|
1069
|
+
function parseConsumerProfile(value, expected) {
|
|
1070
|
+
if (!record(value) || !record(value.context) || !record(value.profile)) return null;
|
|
1071
|
+
const account = tenancy.parseTenancyAccount(value);
|
|
1072
|
+
const contextAccount = tenancy.parseTenancyAccount({ uid: value.uid, subject: value.context.subject });
|
|
1073
|
+
if (!account?.profile || !contextAccount || !tenancy.sameSubject(account.subject, contextAccount.subject) || value.context.protocolVersion !== "1" || !contextText(value.context.releaseRevision) || !contextText(value.context.executionId))
|
|
1074
|
+
return null;
|
|
1075
|
+
try {
|
|
1076
|
+
const scope = new httpClient.RequestScopeController({ ...expected, storage: null });
|
|
1077
|
+
if (value.context.applicationCode !== scope.applicationCode || value.context.environment !== scope.environment || typeof value.context.appTenantId !== "string")
|
|
1078
|
+
return null;
|
|
1079
|
+
scope.setSubject(account.subject);
|
|
1080
|
+
scope.selectTenant(value.context.appTenantId);
|
|
1081
|
+
const captured = scope.capture();
|
|
1082
|
+
const authorization = tenancy.parseAuthorization(value.authorization, captured);
|
|
1083
|
+
if (!authorization) return null;
|
|
1084
|
+
const context = Object.freeze({
|
|
1085
|
+
protocolVersion: "1",
|
|
1086
|
+
applicationCode: scope.applicationCode,
|
|
1087
|
+
environment: scope.environment,
|
|
1088
|
+
appTenantId: scope.appTenantId,
|
|
1089
|
+
subject: account.subject,
|
|
1090
|
+
releaseRevision: value.context.releaseRevision,
|
|
1091
|
+
executionId: value.context.executionId
|
|
1092
|
+
});
|
|
1093
|
+
const user = {
|
|
1094
|
+
...value.profile,
|
|
1095
|
+
...account.profile,
|
|
1096
|
+
roles: [...authorization.roles],
|
|
1097
|
+
permissions: [...authorization.permissions],
|
|
1098
|
+
isSuperAdmin: authorization.isSuperAdmin === true,
|
|
1099
|
+
consumer: { context, authorization }
|
|
1100
|
+
};
|
|
1101
|
+
return { user, context, authorization };
|
|
1102
|
+
} catch {
|
|
1103
|
+
return null;
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
function parseConsumerUser(value, expected) {
|
|
1107
|
+
if (!record(value) || !record(value.consumer) || !record(value.consumer.context)) return null;
|
|
1108
|
+
return parseConsumerProfile(
|
|
1109
|
+
{
|
|
1110
|
+
uid: value.uid,
|
|
1111
|
+
subject: value.consumer.context.subject,
|
|
1112
|
+
profile: value,
|
|
1113
|
+
context: value.consumer.context,
|
|
1114
|
+
authorization: value.consumer.authorization
|
|
1115
|
+
},
|
|
1116
|
+
expected
|
|
1117
|
+
);
|
|
1118
|
+
}
|
|
1119
|
+
function normalizeConsumerResponse(result, expected) {
|
|
1120
|
+
if (result.error || !record(result.data)) return result;
|
|
1121
|
+
const body = result.data;
|
|
1122
|
+
const nested = record(body.user);
|
|
1123
|
+
const candidate = nested ? body.user : body;
|
|
1124
|
+
if (!record(candidate) || candidate.consumer === void 0) return result;
|
|
1125
|
+
const profile = parseConsumerUser(candidate, expected);
|
|
1126
|
+
if (!profile)
|
|
1127
|
+
return {
|
|
1128
|
+
...result,
|
|
1129
|
+
data: null,
|
|
1130
|
+
status: 503,
|
|
1131
|
+
error: { status: 503, code: "dependency_unverifiable", message: "Invalid consumer profile" }
|
|
1132
|
+
};
|
|
1133
|
+
return { ...result, data: nested ? { ...body, user: profile.user } : profile.user };
|
|
1134
|
+
}
|
|
1135
|
+
function createConsumerContext(scope, http, auth, authority) {
|
|
1136
|
+
let defaultSuppressed = false;
|
|
1137
|
+
const failure2 = (code, status, captured) => ({
|
|
1138
|
+
data: null,
|
|
1139
|
+
status,
|
|
1140
|
+
error: { code, status, message: code },
|
|
1141
|
+
scopeCapture: captured
|
|
1142
|
+
});
|
|
1143
|
+
const bind = (profile, token) => {
|
|
1144
|
+
if (!token || auth.getAccessToken() !== token) return failure2("scope_changed", 409);
|
|
1145
|
+
if (scope.currentIdentity && !tenancy.sameSubject(scope.currentIdentity, profile.context.subject))
|
|
1146
|
+
return failure2("unauthenticated", 401);
|
|
1147
|
+
let before = scope.capture("application");
|
|
1148
|
+
let expected = before.generation + (tenancy.sameSubject(scope.currentIdentity, profile.context.subject) ? 0 : 1);
|
|
1149
|
+
scope.setSubject(profile.context.subject);
|
|
1150
|
+
if (auth.getAccessToken() !== token || scope.capture("application").generation !== expected)
|
|
1151
|
+
return failure2("scope_changed", 409, before);
|
|
1152
|
+
before = scope.capture("application");
|
|
1153
|
+
expected = before.generation + (scope.appTenantId === profile.context.appTenantId ? 0 : 1);
|
|
1154
|
+
scope.selectTenant(profile.context.appTenantId);
|
|
1155
|
+
if (auth.getAccessToken() !== token || scope.capture("application").generation !== expected || scope.appTenantId !== profile.context.appTenantId)
|
|
1156
|
+
return failure2("scope_changed", 409, before);
|
|
1157
|
+
const captured = scope.capture();
|
|
1158
|
+
const failedInstall = authority.install(
|
|
1159
|
+
profile.authorization,
|
|
1160
|
+
profile.context.releaseRevision,
|
|
1161
|
+
captured
|
|
1162
|
+
);
|
|
1163
|
+
if (failedInstall) return failedInstall;
|
|
1164
|
+
if (initializing?.generation === before.generation)
|
|
1165
|
+
initializing.generation = captured.generation;
|
|
1166
|
+
return { data: profile.user, status: 200, error: null, scopeCapture: captured };
|
|
1167
|
+
};
|
|
1168
|
+
let initializing = null;
|
|
1169
|
+
const loadProfile = async () => {
|
|
1170
|
+
const token = auth.getAccessToken();
|
|
1171
|
+
const accountOnly = defaultSuppressed && !scope.appTenantId;
|
|
1172
|
+
if (!scope.currentIdentity) {
|
|
1173
|
+
const beforeAccount = scope.capture("application");
|
|
1174
|
+
const accountResult = await http.request({
|
|
1175
|
+
url: "/api/tenancy/account",
|
|
1176
|
+
method: "GET",
|
|
1177
|
+
scopeLevel: "application"
|
|
1178
|
+
});
|
|
1179
|
+
if (accountResult.error) return { ...accountResult, data: null };
|
|
1180
|
+
if (!accountResult.scopeCapture || !scope.isCurrent(accountResult.scopeCapture) || !scope.isCurrent(beforeAccount))
|
|
1181
|
+
return failure2("scope_changed", 409, accountResult.scopeCapture);
|
|
1182
|
+
const account2 = tenancy.parseTenancyAccount(accountResult.data);
|
|
1183
|
+
if (!account2) return failure2("dependency_unverifiable", 503, accountResult.scopeCapture);
|
|
1184
|
+
const expected = beforeAccount.generation + 1;
|
|
1185
|
+
scope.setSubject(account2.subject);
|
|
1186
|
+
if (scope.capture("application").generation !== expected)
|
|
1187
|
+
return failure2("scope_changed", 409, beforeAccount);
|
|
1188
|
+
if (initializing?.generation === beforeAccount.generation) initializing.generation = expected;
|
|
1189
|
+
if (accountOnly && scope.appTenantId) {
|
|
1190
|
+
scope.clearTenant();
|
|
1191
|
+
if (initializing?.generation === expected)
|
|
1192
|
+
initializing.generation = scope.capture("application").generation;
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
const before = scope.capture("application");
|
|
1196
|
+
const result = await http.request({
|
|
1197
|
+
url: accountOnly ? "/api/tenancy/account" : "/api/auth/me",
|
|
1198
|
+
method: "GET",
|
|
1199
|
+
scopeLevel: scope.currentIdentity && scope.appTenantId ? "tenant" : "application"
|
|
1200
|
+
});
|
|
1201
|
+
if (result.error) {
|
|
1202
|
+
if (result.scopeCapture && scope.isCurrent(result.scopeCapture)) {
|
|
1203
|
+
authority.clear();
|
|
1204
|
+
if (result.status === 401 && auth.getAccessToken() === token) auth.clearAuth();
|
|
1205
|
+
}
|
|
1206
|
+
return { ...result, data: null };
|
|
1207
|
+
}
|
|
1208
|
+
if (!result.scopeCapture || !scope.isCurrent(result.scopeCapture) || !scope.isCurrent(before))
|
|
1209
|
+
return failure2("scope_changed", 409, result.scopeCapture);
|
|
1210
|
+
const profile = accountOnly ? null : parseConsumerUser(result.data, scope);
|
|
1211
|
+
if (profile) {
|
|
1212
|
+
if (result.scopeCapture.appTenantId && profile.context.appTenantId !== result.scopeCapture.appTenantId) {
|
|
1213
|
+
authority.clear();
|
|
1214
|
+
return failure2("dependency_unverifiable", 503, result.scopeCapture);
|
|
1215
|
+
}
|
|
1216
|
+
if (scope.currentIdentity && !tenancy.sameSubject(scope.currentIdentity, profile.context.subject)) {
|
|
1217
|
+
authority.clear();
|
|
1218
|
+
return failure2("unauthenticated", 401, result.scopeCapture);
|
|
1219
|
+
}
|
|
1220
|
+
return { ...result, ...bind(profile, auth.getAccessToken()) };
|
|
1221
|
+
}
|
|
1222
|
+
const raw = result.data && typeof result.data === "object" && !Array.isArray(result.data) ? result.data : null;
|
|
1223
|
+
if (!accountOnly && raw && typeof raw.uid === "string" && scope.currentIdentity && raw.uid !== scope.currentIdentity.id) {
|
|
1224
|
+
authority.clear();
|
|
1225
|
+
return failure2("unauthenticated", 401, before);
|
|
1226
|
+
}
|
|
1227
|
+
const account = accountOnly ? tenancy.parseTenancyAccount(result.data) : raw && raw.consumer === void 0 && scope.currentIdentity ? tenancy.parseTenancyAccount({ uid: raw.uid, subject: scope.currentIdentity, profile: raw }) : null;
|
|
1228
|
+
if (account?.profile && !(result.data && typeof result.data === "object" && "context" in result.data)) {
|
|
1229
|
+
if (scope.currentIdentity && !tenancy.sameSubject(scope.currentIdentity, account.subject)) {
|
|
1230
|
+
authority.clear();
|
|
1231
|
+
return failure2("unauthenticated", 401, before);
|
|
1232
|
+
}
|
|
1233
|
+
const expected = before.generation + (tenancy.sameSubject(scope.currentIdentity, account.subject) ? 0 : 1);
|
|
1234
|
+
scope.setSubject(account.subject);
|
|
1235
|
+
if (scope.capture("application").generation !== expected)
|
|
1236
|
+
return failure2("scope_changed", 409, before);
|
|
1237
|
+
authority.clear();
|
|
1238
|
+
return {
|
|
1239
|
+
...result,
|
|
1240
|
+
data: { ...accountOnly ? {} : raw, ...account.profile },
|
|
1241
|
+
scopeCapture: scope.capture("application")
|
|
1242
|
+
};
|
|
1243
|
+
}
|
|
1244
|
+
authority.clear();
|
|
1245
|
+
return failure2("dependency_unverifiable", 503, result.scopeCapture);
|
|
1246
|
+
};
|
|
1247
|
+
const getMe = () => {
|
|
1248
|
+
auth.getAccessToken();
|
|
1249
|
+
const generation = scope.capture("application").generation;
|
|
1250
|
+
if (!initializing || initializing.generation !== generation) {
|
|
1251
|
+
const flight = { generation, promise: loadProfile() };
|
|
1252
|
+
initializing = flight;
|
|
1253
|
+
void flight.promise.finally(() => {
|
|
1254
|
+
if (initializing === flight) initializing = null;
|
|
1255
|
+
}).catch(() => {
|
|
1256
|
+
});
|
|
1257
|
+
}
|
|
1258
|
+
return initializing.promise;
|
|
1259
|
+
};
|
|
1260
|
+
return {
|
|
1261
|
+
suppressDefault() {
|
|
1262
|
+
defaultSuppressed = true;
|
|
1263
|
+
},
|
|
1264
|
+
reset() {
|
|
1265
|
+
defaultSuppressed = false;
|
|
1266
|
+
},
|
|
1267
|
+
get pending() {
|
|
1268
|
+
return initializing !== null;
|
|
1269
|
+
},
|
|
1270
|
+
getMe,
|
|
1271
|
+
login(user) {
|
|
1272
|
+
const profile = parseConsumerUser(user, scope);
|
|
1273
|
+
if (profile) bind(profile, auth.getAccessToken());
|
|
1274
|
+
},
|
|
1275
|
+
async ensure() {
|
|
1276
|
+
if (defaultSuppressed && !scope.appTenantId)
|
|
1277
|
+
return failure2(
|
|
1278
|
+
auth.getAccessToken() ? "invalid_scope" : "unauthenticated",
|
|
1279
|
+
auth.getAccessToken() ? 400 : 401
|
|
1280
|
+
);
|
|
1281
|
+
const result = await getMe();
|
|
1282
|
+
if (result.error) return result;
|
|
1283
|
+
if (!result.scopeCapture || !scope.isCurrent(result.scopeCapture))
|
|
1284
|
+
return failure2("scope_changed", 409, result.scopeCapture);
|
|
1285
|
+
if (!scope.currentIdentity || !scope.appTenantId || !authority.current)
|
|
1286
|
+
return failure2("default_tenant_not_ready", 409, result.scopeCapture);
|
|
1287
|
+
return result;
|
|
1288
|
+
}
|
|
1289
|
+
};
|
|
1290
|
+
}
|
|
1291
|
+
function unsupported() {
|
|
1292
|
+
return { data: null, status: 422, error: { status: 422, code: "capability_unsupported", message: "Use the tenancy account and authorization APIs" } };
|
|
1293
|
+
}
|
|
566
1294
|
function createClient(options = {}) {
|
|
1295
|
+
return createAutomaticClient(options, createResolvedClient);
|
|
1296
|
+
}
|
|
1297
|
+
function createResolvedClient(options, beforeAuthInitialize) {
|
|
1298
|
+
if (options.tenancy && options.tenancy.storage === void 0) {
|
|
1299
|
+
const namespace = JSON.stringify([options.tenancy.applicationCode, options.tenancy.environment]);
|
|
1300
|
+
const tenantStorage = options.storage ?? authClient.createStorageAdapter(namespace);
|
|
1301
|
+
options = { ...options, tenancy: { ...options.tenancy, storage: tenantStorage } };
|
|
1302
|
+
}
|
|
567
1303
|
const {
|
|
568
1304
|
baseURL,
|
|
569
1305
|
storage,
|
|
@@ -576,12 +1312,55 @@ function createClient(options = {}) {
|
|
|
576
1312
|
runtime,
|
|
577
1313
|
autoRefresh = true
|
|
578
1314
|
} = options;
|
|
1315
|
+
const scope = options.tenancy ? new httpClient.RequestScopeController(options.tenancy) : void 0;
|
|
1316
|
+
const defaultHeaders = scope ? Object.fromEntries(Object.entries(headers).filter(([key]) => key.toLowerCase() !== "authorization")) : headers;
|
|
1317
|
+
const accountScope = scope ? new httpClient.RequestScopeController({ applicationCode: scope.applicationCode, environment: scope.environment, storage: null }) : void 0;
|
|
1318
|
+
const authTransport = accountScope ? httpClient.createHttpClient({ baseURL, withCredentials, headers: defaultHeaders, runtime, requestScope: accountScope }) : void 0;
|
|
1319
|
+
const authHttp = authTransport ? {
|
|
1320
|
+
request: async (config) => {
|
|
1321
|
+
const method = String(config.method ?? "GET").toUpperCase();
|
|
1322
|
+
const permitted = /* @__PURE__ */ new Set([
|
|
1323
|
+
"GET /api/auth/me",
|
|
1324
|
+
"GET /api/tenancy/account",
|
|
1325
|
+
"GET /api/auth/captcha",
|
|
1326
|
+
"GET /api/auth/oauth/feishu/config",
|
|
1327
|
+
"GET /api/auth/oauth-bindings",
|
|
1328
|
+
"PUT /api/auth/me",
|
|
1329
|
+
"POST /api/auth/change-password",
|
|
1330
|
+
"GET /api/auth/sessions",
|
|
1331
|
+
"GET /api/auth/sessions/current",
|
|
1332
|
+
"DELETE /api/auth/sessions",
|
|
1333
|
+
"POST /api/auth/login",
|
|
1334
|
+
"POST /api/auth/register",
|
|
1335
|
+
"POST /api/auth/login-with-code",
|
|
1336
|
+
"POST /api/auth/send-code",
|
|
1337
|
+
"POST /api/auth/logout",
|
|
1338
|
+
"POST /api/auth/refresh",
|
|
1339
|
+
"POST /api/auth/oauth/ticket",
|
|
1340
|
+
"POST /api/auth/oauth/feishu/code",
|
|
1341
|
+
"POST /api/auth/miniprogram/login",
|
|
1342
|
+
"POST /api/auth/miniprogram/douyin/login",
|
|
1343
|
+
"POST /api/auth/miniprogram/phone-login",
|
|
1344
|
+
"POST /api/auth/miniprogram/phone",
|
|
1345
|
+
"POST /api/auth/miniprogram/douyin/phone"
|
|
1346
|
+
]);
|
|
1347
|
+
if (!permitted.has(`${method} ${config.url}`) && !(method === "DELETE" && (/^\/api\/auth\/sessions\/[1-9][0-9]*$/.test(config.url) || /^\/api\/auth\/oauth\/[^/]+\/unbind$/.test(config.url)))) return unsupported();
|
|
1348
|
+
const result = await authTransport.request({
|
|
1349
|
+
...config,
|
|
1350
|
+
scopeLevel: "application"
|
|
1351
|
+
});
|
|
1352
|
+
return normalizeConsumerResponse(result, accountScope);
|
|
1353
|
+
}
|
|
1354
|
+
} : void 0;
|
|
579
1355
|
const baseHttpClient = httpClient.createHttpClient({
|
|
580
1356
|
baseURL,
|
|
1357
|
+
headers: defaultHeaders,
|
|
581
1358
|
withCredentials,
|
|
582
|
-
|
|
583
|
-
|
|
1359
|
+
runtime,
|
|
1360
|
+
requestScope: scope
|
|
584
1361
|
});
|
|
1362
|
+
let consumerContext;
|
|
1363
|
+
let credentialRevision = 0;
|
|
585
1364
|
const auth = authClient.createAuthClient({
|
|
586
1365
|
storage,
|
|
587
1366
|
withCredentials,
|
|
@@ -592,11 +1371,46 @@ function createClient(options = {}) {
|
|
|
592
1371
|
onUnauthorized,
|
|
593
1372
|
autoHandleOAuthCallback,
|
|
594
1373
|
autoRedirectAfterLogin,
|
|
595
|
-
runtime
|
|
1374
|
+
runtime,
|
|
1375
|
+
storageNamespace: scope ? JSON.stringify([scope.applicationCode, scope.environment]) : void 0,
|
|
1376
|
+
syncUserOnInit: scope ? false : void 0,
|
|
1377
|
+
verifyRefresh: scope && authHttp ? async (accessToken) => {
|
|
1378
|
+
const expected = scope.currentIdentity;
|
|
1379
|
+
const result = await authHttp.request({ url: "/api/tenancy/account", method: "GET", headers: { Authorization: `Bearer ${accessToken}` } });
|
|
1380
|
+
if (result.error) return result.status === 0 ? { ...result, status: 503, error: { ...result.error, status: 503, code: "dependency_unverifiable" } } : result;
|
|
1381
|
+
const account = tenancy.parseTenancyAccount(result.data);
|
|
1382
|
+
if (!account) return { data: null, status: 503, error: { status: 503, code: "dependency_unverifiable", message: "Invalid account response" } };
|
|
1383
|
+
return !expected || tenancy.sameSubject(expected, account.subject) ? result : { data: null, status: 401, error: { status: 401, code: "unauthenticated", message: "Refreshed identity changed" } };
|
|
1384
|
+
} : void 0
|
|
1385
|
+
}, authHttp, (initializedAuth) => {
|
|
1386
|
+
initializedAuth.on("credentialsChanged", () => {
|
|
1387
|
+
credentialRevision++;
|
|
1388
|
+
});
|
|
1389
|
+
if (scope) {
|
|
1390
|
+
initializedAuth.on("credentialsChanged", (kind) => {
|
|
1391
|
+
if (kind !== "refresh") {
|
|
1392
|
+
consumerContext?.reset();
|
|
1393
|
+
scope.clear();
|
|
1394
|
+
accountScope?.clear();
|
|
1395
|
+
if (kind === "login") consumerContext?.login(authClient.readCachedAuthUser(initializedAuth));
|
|
1396
|
+
}
|
|
1397
|
+
});
|
|
1398
|
+
initializedAuth.on("login", (user) => consumerContext?.login(user));
|
|
1399
|
+
}
|
|
1400
|
+
beforeAuthInitialize?.(initializedAuth);
|
|
596
1401
|
});
|
|
1402
|
+
const credentials = {
|
|
1403
|
+
getAccessToken: () => auth.getAccessToken(),
|
|
1404
|
+
getCredentialRevision: () => {
|
|
1405
|
+
auth.getAccessToken();
|
|
1406
|
+
return credentialRevision;
|
|
1407
|
+
},
|
|
1408
|
+
refreshToken: () => auth.refreshToken()
|
|
1409
|
+
};
|
|
597
1410
|
const createAuthenticatedHttpClient = () => {
|
|
598
1411
|
let isRefreshing = false;
|
|
599
1412
|
let refreshPromise = null;
|
|
1413
|
+
let completedRefresh;
|
|
600
1414
|
function isTokenExpired(result) {
|
|
601
1415
|
if (result.status !== 401) return false;
|
|
602
1416
|
if (result.error?.message && /expired/i.test(result.error.message)) {
|
|
@@ -632,11 +1446,17 @@ function createClient(options = {}) {
|
|
|
632
1446
|
};
|
|
633
1447
|
let result = await baseHttpClient.request(mergedConfig);
|
|
634
1448
|
if (autoRefresh && result.status === 401 && isTokenExpired(result)) {
|
|
635
|
-
|
|
1449
|
+
const alreadyRefreshed = completedRefresh?.source === token && completedRefresh.token === auth.getAccessToken() && completedRefresh.revision === credentials.getCredentialRevision();
|
|
1450
|
+
if (!alreadyRefreshed && !isRefreshing) {
|
|
636
1451
|
isRefreshing = true;
|
|
637
1452
|
refreshPromise = (async () => {
|
|
638
1453
|
try {
|
|
639
1454
|
const refreshResult = await auth.refreshToken();
|
|
1455
|
+
if (refreshResult.data) completedRefresh = {
|
|
1456
|
+
source: token,
|
|
1457
|
+
token: auth.getAccessToken(),
|
|
1458
|
+
revision: credentials.getCredentialRevision()
|
|
1459
|
+
};
|
|
640
1460
|
return !!refreshResult.data;
|
|
641
1461
|
} finally {
|
|
642
1462
|
isRefreshing = false;
|
|
@@ -644,7 +1464,7 @@ function createClient(options = {}) {
|
|
|
644
1464
|
}
|
|
645
1465
|
})();
|
|
646
1466
|
}
|
|
647
|
-
const refreshed = await refreshPromise;
|
|
1467
|
+
const refreshed = alreadyRefreshed || await refreshPromise;
|
|
648
1468
|
if (refreshed) {
|
|
649
1469
|
const newToken = auth.getAccessToken();
|
|
650
1470
|
result = await baseHttpClient.request({
|
|
@@ -663,51 +1483,97 @@ function createClient(options = {}) {
|
|
|
663
1483
|
}
|
|
664
1484
|
};
|
|
665
1485
|
};
|
|
666
|
-
const
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
cachedUserUid = null;
|
|
1486
|
+
const scopedHttp = scope ? createScopedHttpClient(baseHttpClient, scope, credentials, autoRefresh, onUnauthorized) : void 0;
|
|
1487
|
+
const consumerHint = options.tenancy ? authClient.createConsumerUIHint(options.tenancy, () => auth.getAccessToken()) : void 0;
|
|
1488
|
+
const authority = scope ? tenancy.createConsumerAuthorization(scope, consumerHint) : void 0;
|
|
1489
|
+
auth.on("credentialsChanged", (kind) => {
|
|
1490
|
+
if (kind === "refresh" && authority?.current) consumerHint?.write(authority.current);
|
|
1491
|
+
else consumerHint?.clear();
|
|
673
1492
|
});
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
1493
|
+
consumerContext = scope && scopedHttp && authority ? createConsumerContext(scope, scopedHttp, auth, authority) : void 0;
|
|
1494
|
+
const authenticatedHttpClient = scopedHttp && scope && consumerContext ? {
|
|
1495
|
+
async request(config) {
|
|
1496
|
+
const application = config.scopeLevel === "application" || /^\/api\/auth\//.test(config.url);
|
|
1497
|
+
const selectedContextRead = config.url === "/api/tenancy/current" && !!scope.currentIdentity && !!scope.appTenantId;
|
|
1498
|
+
if (!application && (!selectedContextRead && consumerContext.pending || !scope.currentIdentity || !scope.appTenantId)) {
|
|
1499
|
+
const established = await consumerContext.ensure();
|
|
1500
|
+
if (established.error) return { ...established, data: null };
|
|
1501
|
+
if (!established.scopeCapture || !scope.isCurrent(established.scopeCapture)) return {
|
|
1502
|
+
data: null,
|
|
1503
|
+
status: 409,
|
|
1504
|
+
error: { code: "scope_changed", status: 409, message: "scope_changed" }
|
|
1505
|
+
};
|
|
678
1506
|
}
|
|
679
|
-
|
|
680
|
-
|
|
1507
|
+
const business = !/^\/api\/(auth|tenancy)\//.test(config.url);
|
|
1508
|
+
return scopedHttp.request({
|
|
1509
|
+
...config,
|
|
1510
|
+
...application ? { scopeLevel: "application" } : {},
|
|
1511
|
+
preserveBusinessResponse: business
|
|
1512
|
+
});
|
|
1513
|
+
}
|
|
1514
|
+
} : createAuthenticatedHttpClient();
|
|
1515
|
+
const tenancy$1 = scope ? tenancy.createTenancyClient(scope, authenticatedHttpClient, authority, () => consumerContext?.suppressDefault()) : void 0;
|
|
1516
|
+
if (tenancy$1) {
|
|
1517
|
+
auth.hasRole = (role) => {
|
|
1518
|
+
auth.getAccessToken();
|
|
1519
|
+
const view = tenancy$1.authorization ?? consumerHint?.read();
|
|
1520
|
+
return !!view?.isSuperAdmin || (view?.roles.includes(role) ?? false);
|
|
1521
|
+
};
|
|
1522
|
+
auth.hasPermission = (resource, action) => {
|
|
1523
|
+
auth.getAccessToken();
|
|
1524
|
+
const view = tenancy$1.authorization ?? consumerHint?.read();
|
|
1525
|
+
return !!view?.isSuperAdmin || (view?.permissions.includes(`${resource}.${action}`) ?? false);
|
|
1526
|
+
};
|
|
1527
|
+
auth.hasAnyPermission = (permissions) => permissions.some(({ resource, action }) => auth.hasPermission(resource, action));
|
|
1528
|
+
auth.hasAllPermissions = (permissions) => permissions.every(({ resource, action }) => auth.hasPermission(resource, action));
|
|
681
1529
|
}
|
|
682
|
-
|
|
1530
|
+
if (tenancy$1 && consumerContext) auth.getMe = () => consumerContext.getMe();
|
|
1531
|
+
const entity = entityClient.createEntityClient(authenticatedHttpClient, { preserveIdentityStrings: !!scope });
|
|
683
1532
|
const bpm = bpmClient.createBpmClient(authenticatedHttpClient);
|
|
684
1533
|
const workflow = workflowClient.createWorkflowClient(authenticatedHttpClient);
|
|
685
1534
|
const chatflow = workflowClient.createChatflowClient(authenticatedHttpClient, {
|
|
686
1535
|
baseURL,
|
|
687
1536
|
headers,
|
|
688
1537
|
getAccessToken: () => auth.getAccessToken(),
|
|
689
|
-
onUnauthorized
|
|
1538
|
+
onUnauthorized,
|
|
1539
|
+
requestScope: scope,
|
|
1540
|
+
beforeStream: consumerContext ? async () => {
|
|
1541
|
+
if (!scope.currentIdentity || !scope.appTenantId || consumerContext.pending) {
|
|
1542
|
+
const result = await consumerContext.ensure();
|
|
1543
|
+
if (result.error) throw Object.assign(new Error(result.error.message), { status: result.status });
|
|
1544
|
+
}
|
|
1545
|
+
} : void 0
|
|
690
1546
|
});
|
|
691
1547
|
const functionClient$1 = functionClient.createFunctionClient(authenticatedHttpClient);
|
|
692
|
-
const
|
|
1548
|
+
const accountBusinessTransport = accountScope && authTransport ? createScopedHttpClient(authTransport, accountScope, credentials, autoRefresh, onUnauthorized) : void 0;
|
|
1549
|
+
const applicationHttp = accountBusinessTransport ? {
|
|
1550
|
+
async request(config) {
|
|
1551
|
+
return accountBusinessTransport.request({ ...config, scopeLevel: "application", preserveBusinessResponse: true });
|
|
1552
|
+
}
|
|
1553
|
+
} : authenticatedHttpClient;
|
|
1554
|
+
const knowledge = createKnowledgeClient(applicationHttp);
|
|
693
1555
|
const copilot = copilotClient.createCopilotClient(
|
|
694
|
-
|
|
1556
|
+
applicationHttp,
|
|
695
1557
|
baseURL,
|
|
696
1558
|
() => auth.getAccessToken(),
|
|
697
|
-
() =>
|
|
1559
|
+
() => scope?.currentIdentity?.type === "user" ? scope.currentIdentity.id : authClient.readCachedAuthUser(auth)?.uid ?? null,
|
|
1560
|
+
accountScope
|
|
698
1561
|
);
|
|
699
|
-
const s3 = s3Client.createS3Client(
|
|
1562
|
+
const s3 = s3Client.createS3Client(applicationHttp);
|
|
700
1563
|
const asr = asrClient.createASRClient({
|
|
701
1564
|
getAccessToken: () => auth.getAccessToken()
|
|
702
1565
|
});
|
|
703
1566
|
const asrHttp = asrClient.createASRHttpClient({
|
|
704
1567
|
getAccessToken: () => auth.getAccessToken(),
|
|
705
|
-
http:
|
|
1568
|
+
http: applicationHttp
|
|
706
1569
|
});
|
|
707
1570
|
const tts = ttsClient.createTTSClient({
|
|
708
1571
|
getAccessToken: () => auth.getAccessToken()
|
|
709
1572
|
});
|
|
710
1573
|
const client = {
|
|
1574
|
+
ready: async () => {
|
|
1575
|
+
},
|
|
1576
|
+
...tenancy$1 ? { tenancy: tenancy$1 } : {},
|
|
711
1577
|
auth,
|
|
712
1578
|
entity,
|
|
713
1579
|
bpm,
|
|
@@ -762,6 +1628,10 @@ Object.defineProperty(exports, "splitTextIntoFragments", {
|
|
|
762
1628
|
enumerable: true,
|
|
763
1629
|
get: function () { return ttsClient.splitTextIntoFragments; }
|
|
764
1630
|
});
|
|
1631
|
+
Object.defineProperty(exports, "TenancyCapabilityError", {
|
|
1632
|
+
enumerable: true,
|
|
1633
|
+
get: function () { return tenancy.TenancyCapabilityError; }
|
|
1634
|
+
});
|
|
765
1635
|
exports.createClient = createClient;
|
|
766
1636
|
//# sourceMappingURL=index.cjs.map
|
|
767
1637
|
//# sourceMappingURL=index.cjs.map
|