185 lines
No EOL
9.1 KiB
JavaScript
185 lines
No EOL
9.1 KiB
JavaScript
"use strict";
|
|
// Copyright (c) Microsoft Corporation.
|
|
// Licensed under the MIT License.
|
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
}) : (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
o[k2] = m[k];
|
|
}));
|
|
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
}) : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = (this && this.__importStar) || function (mod) {
|
|
if (mod && mod.__esModule) return mod;
|
|
var result = {};
|
|
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
return new (P || (P = Promise))(function (resolve, reject) {
|
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
});
|
|
};
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.SharePointSSOTokenExchangeMiddleware = void 0;
|
|
const z = __importStar(require("zod"));
|
|
const botbuilder_core_1 = require("botbuilder-core");
|
|
function getStorageKey(context) {
|
|
var _a;
|
|
const activity = context.activity;
|
|
const channelId = activity.channelId;
|
|
if (!channelId) {
|
|
throw new Error('invalid activity. Missing channelId');
|
|
}
|
|
const conversationId = (_a = activity.conversation) === null || _a === void 0 ? void 0 : _a.id;
|
|
if (!conversationId) {
|
|
throw new Error('invalid activity. Missing conversation.id');
|
|
}
|
|
const value = activity.value;
|
|
if (!(value === null || value === void 0 ? void 0 : value.id)) {
|
|
throw new Error('Invalid signin/tokenExchange. Missing activity.value.id.');
|
|
}
|
|
return `${channelId}/${conversationId}/${value.id}`;
|
|
}
|
|
function sendInvokeResponse(context, body = null, status = botbuilder_core_1.StatusCodes.OK) {
|
|
return __awaiter(this, void 0, void 0, function* () {
|
|
yield context.sendActivity({
|
|
type: botbuilder_core_1.ActivityTypes.InvokeResponse,
|
|
value: { body, status },
|
|
});
|
|
});
|
|
}
|
|
const ExchangeToken = z.custom((val) => typeof val.exchangeToken === 'function', { message: 'ExtendedUserTokenProvider' });
|
|
/**
|
|
* If the activity name is cardExtension/token, this middleware will attempt to
|
|
* exchange the token, and deduplicate the incoming call, ensuring only one
|
|
* exchange request is processed.
|
|
*
|
|
* If a user is signed into multiple devices, the Bot could receive a
|
|
* "cardExtension/token" from each device. Each token exchange request for a
|
|
* specific user login will have an identical activity.value.id.
|
|
*
|
|
* Only one of these token exchange requests should be processed by the bot.
|
|
* The others return [StatusCodes.PRECONDITION_FAILED](xref:botframework-schema:StatusCodes.PRECONDITION_FAILED).
|
|
* For a distributed bot in production, this requires distributed storage
|
|
* ensuring only one token exchange is processed. This middleware supports
|
|
* CosmosDb storage found in botbuilder-azure, or MemoryStorage for local development.
|
|
*/
|
|
class SharePointSSOTokenExchangeMiddleware {
|
|
/**
|
|
* Initializes a new instance of the SharePointSSOTokenExchangeMiddleware class.
|
|
*
|
|
* @param storage The [Storage](xref:botbuilder-core.Storage) to use for deduplication
|
|
* @param oAuthConnectionName The connection name to use for the single sign on token exchange
|
|
*/
|
|
constructor(storage, oAuthConnectionName) {
|
|
this.storage = storage;
|
|
this.oAuthConnectionName = oAuthConnectionName;
|
|
if (!storage) {
|
|
throw new TypeError('`storage` parameter is required');
|
|
}
|
|
if (!oAuthConnectionName) {
|
|
throw new TypeError('`oAuthConnectionName` parameter is required');
|
|
}
|
|
}
|
|
/**
|
|
* Called each time the bot receives a new request.
|
|
*
|
|
* @param context Context for current turn of conversation with the user.
|
|
* @param _next Function to call to continue execution to the next step in the middleware chain.
|
|
*/
|
|
onTurn(context, _next) {
|
|
return __awaiter(this, void 0, void 0, function* () {
|
|
if (context.activity.channelId === botbuilder_core_1.Channels.M365 && context.activity.name === botbuilder_core_1.sharePointTokenExchange) {
|
|
// If the TokenExchange is NOT successful, the response will have already been sent by exchangedToken
|
|
if (!(yield this.exchangedToken(context))) {
|
|
return;
|
|
}
|
|
// Only one token exchange should proceed from here. Deduplication is performed second because in the case
|
|
// of failure due to consent required, every caller needs to receive a response
|
|
if (!(yield this.deduplicatedTokenExchangeId(context))) {
|
|
// If the token is not exchangeable, do not process this activity further.
|
|
return;
|
|
}
|
|
}
|
|
return;
|
|
});
|
|
}
|
|
deduplicatedTokenExchangeId(context) {
|
|
var _a, _b;
|
|
return __awaiter(this, void 0, void 0, function* () {
|
|
// Create a StoreItem with Etag of the unique 'signin/tokenExchange' request
|
|
const storeItem = {
|
|
eTag: (_a = context.activity.value) === null || _a === void 0 ? void 0 : _a.id,
|
|
};
|
|
try {
|
|
// Writing the IStoreItem with ETag of unique id will succeed only once
|
|
yield this.storage.write({
|
|
[getStorageKey(context)]: storeItem,
|
|
});
|
|
}
|
|
catch (err) {
|
|
const message = (_b = err.message) === null || _b === void 0 ? void 0 : _b.toLowerCase();
|
|
// Do NOT proceed processing this message, some other thread or machine already has processed it.
|
|
// Send 200 invoke response.
|
|
if (message.includes('etag conflict') || message.includes('precondition is not met')) {
|
|
yield sendInvokeResponse(context);
|
|
return false;
|
|
}
|
|
throw err;
|
|
}
|
|
return true;
|
|
});
|
|
}
|
|
exchangedToken(context) {
|
|
return __awaiter(this, void 0, void 0, function* () {
|
|
let tokenExchangeResponse;
|
|
const aceRequest = context.activity.value;
|
|
try {
|
|
const userTokenClient = context.turnState.get(context.adapter.UserTokenClientKey);
|
|
const exchangeToken = ExchangeToken.safeParse(context.adapter);
|
|
if (userTokenClient) {
|
|
tokenExchangeResponse = yield userTokenClient.exchangeToken(context.activity.from.id, this.oAuthConnectionName, context.activity.channelId, { token: aceRequest.data });
|
|
}
|
|
else if (exchangeToken.success) {
|
|
tokenExchangeResponse = yield exchangeToken.data.exchangeToken(context, this.oAuthConnectionName, context.activity.from.id, { token: aceRequest.data });
|
|
}
|
|
else {
|
|
new Error('Token Exchange is not supported by the current adapter.');
|
|
}
|
|
}
|
|
catch (_err) {
|
|
// Ignore Exceptions
|
|
// If token exchange failed for any reason, tokenExchangeResponse above stays null,
|
|
// and hence we send back a failure invoke response to the caller.
|
|
}
|
|
if (!(tokenExchangeResponse === null || tokenExchangeResponse === void 0 ? void 0 : tokenExchangeResponse.token)) {
|
|
// The token could not be exchanged (which could be due to a consent requirement)
|
|
// Notify the sender that PreconditionFailed so they can respond accordingly.
|
|
const invokeResponse = {
|
|
id: 'FAKE ID',
|
|
connectionName: this.oAuthConnectionName,
|
|
failureDetail: 'The bot is unable to exchange token. Proceed with regular login.',
|
|
};
|
|
yield sendInvokeResponse(context, invokeResponse, botbuilder_core_1.StatusCodes.PRECONDITION_FAILED);
|
|
return false;
|
|
}
|
|
return true;
|
|
});
|
|
}
|
|
}
|
|
exports.SharePointSSOTokenExchangeMiddleware = SharePointSSOTokenExchangeMiddleware;
|
|
//# sourceMappingURL=sharePointSSOTokenExchangeMiddleware.js.map
|