'use strict';

var errors = require('@backstage/errors');

function parseJwtPayload(token) {
  const [_header, payload, _signature] = token.split(".");
  return JSON.parse(Buffer.from(payload, "base64").toString());
}
function prepareBackstageIdentityResponse(result) {
  if (!result.token) {
    throw new errors.InputError(`Identity response must return a token`);
  }
  const { sub, ent = [], exp: expStr } = parseJwtPayload(result.token);
  if (!sub) {
    throw new errors.InputError(
      `Identity response must return a token with subject claim`
    );
  }
  const expAt = Number(expStr);
  const exp = expAt ? Math.round(expAt - Date.now() / 1e3) : void 0;
  if (exp && exp < 0) {
    throw new errors.InputError(`Identity response must not return an expired token`);
  }
  return {
    ...result,
    expiresInSeconds: exp,
    identity: result.identity ?? {
      type: "user",
      userEntityRef: sub,
      ownershipEntityRefs: ent
    }
  };
}

exports.prepareBackstageIdentityResponse = prepareBackstageIdentityResponse;
//# sourceMappingURL=prepareBackstageIdentityResponse.cjs.js.map
