All files sdjwt.ts

94.58% Statements 297/314
88.33% Branches 53/60
100% Functions 10/10
94.58% Lines 297/314

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 3151x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 159x 159x 159x 159x 1x 1x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x           105x 105x 105x 8x 97x 105x 105x 105x 105x 105x 452x 105x 105x 105x 105x 105x 105x 105x 105x 105x 1x 1x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 1x 1x 22x     22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x         22x 22x 22x 22x 22x 22x 22x 22x 22x 1x 1x 51x 51x 51x     51x 51x 51x 51x 51x 43x 43x 43x 43x 43x 51x 51x 51x 51x 1x 1x 21x 21x 1x 1x 3x     3x 3x 3x 3x 3x 3x 3x 1x 1x 78x     78x 78x 78x 78x 78x 78x 78x 1x 1x 1x 85x 85x 211x 211x 211x 211x 211x 63x 63x 211x 85x 85x 1x 1x 76x 76x 76x 76x 76x 76x 3x 3x 3x 3x 3x 73x 76x 76x 76x 76x 22x 22x 22x 22x 22x 35x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 35x 22x 22x 55x 12x 43x 55x 55x 41x 41x 41x 41x 41x 55x 14x 14x 55x 22x 3x 3x 3x 22x 22x 51x 51x 51x 51x 76x 68x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 68x 51x 51x 51x 76x 116x 28x 88x 116x 116x 73x 73x 73x 73x 73x 73x 106x 43x 43x 116x 48x 76x 6x 6x 6x 51x 76x 37x 37x 51x 51x  
import { createDecoy } from './decoy';
import { SDJWTException, Disclosure } from '@hopae/sd-jwt-util';
import { Jwt } from './jwt';
import { KBJwt } from './kbjwt';
import {
  DisclosureFrame,
  Hasher,
  HasherAndAlg,
  SDJWTCompact,
  SD_DECOY,
  SD_DIGEST,
  SD_LIST_KEY,
  SD_SEPARATOR,
  SaltGenerator,
  kbHeader,
  kbPayload,
} from '@hopae/sd-jwt-type';
import {
  createHashMapping,
  getSDAlgAndPayload,
  unpack,
} from '@hopae/sd-jwt-decode';
 
export type SDJwtData<
  Header extends Record<string, any>,
  Payload extends Record<string, any>,
  KBHeader extends kbHeader = kbHeader,
  KBPayload extends kbPayload = kbPayload,
> = {
  jwt?: Jwt<Header, Payload>;
  disclosures?: Array<Disclosure<any>>;
  kbJwt?: KBJwt<KBHeader, KBPayload>;
};
 
export class SDJwt<
  Header extends Record<string, any> = Record<string, any>,
  Payload extends Record<string, any> = Record<string, any>,
  KBHeader extends kbHeader = kbHeader,
  KBPayload extends kbPayload = kbPayload,
> {
  public jwt?: Jwt<Header, Payload>;
  public disclosures?: Array<Disclosure<any>>;
  public kbJwt?: KBJwt<KBHeader, KBPayload>;
 
  constructor(data?: SDJwtData<Header, Payload, KBHeader, KBPayload>) {
    this.jwt = data?.jwt;
    this.disclosures = data?.disclosures;
    this.kbJwt = data?.kbJwt;
  }
 
  public static async decodeSDJwt<
    Header extends Record<string, any> = Record<string, any>,
    Payload extends Record<string, any> = Record<string, any>,
    KBHeader extends kbHeader = kbHeader,
    KBPayload extends kbPayload = kbPayload,
  >(
    sdjwt: SDJWTCompact,
    hasher: Hasher,
  ): Promise<{
    jwt: Jwt<Header, Payload>;
    disclosures: Array<Disclosure<any>>;
    kbJwt?: KBJwt<KBHeader, KBPayload>;
  }> {
    const [encodedJwt, ...encodedDisclosures] = sdjwt.split(SD_SEPARATOR);
    const jwt = Jwt.fromEncode<Header, Payload>(encodedJwt);
 
    if (encodedDisclosures.length === 0) {
      return {
        jwt,
        disclosures: [],
      };
    }
 
    const encodedKeyBindingJwt = encodedDisclosures.pop();
    const kbJwt = encodedKeyBindingJwt
      ? KBJwt.fromKBEncode<KBHeader, KBPayload>(encodedKeyBindingJwt)
      : undefined;
 
    const { _sd_alg } = getSDAlgAndPayload(jwt.payload);
 
    const disclosures = await Promise.all(
      encodedDisclosures.map((ed) =>
        Disclosure.fromEncode(ed, { alg: _sd_alg, hasher }),
      ),
    );
 
    return {
      jwt,
      disclosures,
      kbJwt,
    };
  }
 
  public static async fromEncode<
    Header extends Record<string, any> = Record<string, any>,
    Payload extends Record<string, any> = Record<string, any>,
    KBHeader extends kbHeader = kbHeader,
    KBPayload extends kbPayload = kbPayload,
  >(
    encodedSdJwt: SDJWTCompact,
    hasher: Hasher,
  ): Promise<SDJwt<Header, Payload>> {
    const { jwt, disclosures, kbJwt } = await SDJwt.decodeSDJwt<
      Header,
      Payload,
      KBHeader,
      KBPayload
    >(encodedSdJwt, hasher);
 
    return new SDJwt<Header, Payload, KBHeader, KBPayload>({
      jwt,
      disclosures,
      kbJwt,
    });
  }
 
  public async present(keys: string[], hasher: Hasher): Promise<SDJWTCompact> {
    if (!this.jwt?.payload || !this.disclosures) {
      throw new SDJWTException('Invalid sd-jwt: jwt or disclosures is missing');
    }
    const { _sd_alg: alg } = getSDAlgAndPayload(this.jwt.payload);
    const hash = { alg, hasher };
    const hashmap = await createHashMapping(this.disclosures, hash);
    const { disclosureKeymap } = await unpack(
      this.jwt.payload,
      this.disclosures,
      hasher,
    );
 
    const presentableKeys = Object.keys(disclosureKeymap);
    const missingKeys = keys.filter((k) => !presentableKeys.includes(k));
    if (missingKeys.length > 0) {
      throw new SDJWTException(
        `Invalid sd-jwt: invalid present keys: ${missingKeys.join(', ')}`,
      );
    }
 
    const disclosures = keys.map((k) => hashmap[disclosureKeymap[k]]);
    const presentSDJwt = new SDJwt({
      jwt: this.jwt,
      disclosures,
      kbJwt: this.kbJwt,
    });
    return presentSDJwt.encodeSDJwt();
  }
 
  public encodeSDJwt(): SDJWTCompact {
    const data: string[] = [];
 
    if (!this.jwt) {
      throw new SDJWTException('Invalid sd-jwt: jwt is missing');
    }
 
    const encodedJwt = this.jwt.encodeJwt();
    data.push(encodedJwt);
 
    if (this.disclosures && this.disclosures.length > 0) {
      const encodeddisclosures = this.disclosures
        .map((dc) => dc.encode())
        .join(SD_SEPARATOR);
      data.push(encodeddisclosures);
    }
 
    data.push(this.kbJwt ? this.kbJwt.encodeJwt() : '');
    return data.join(SD_SEPARATOR);
  }
 
  public async keys(hasher: Hasher): Promise<string[]> {
    return listKeys(await this.getClaims(hasher)).sort();
  }
 
  public async presentableKeys(hasher: Hasher): Promise<string[]> {
    if (!this.jwt?.payload || !this.disclosures) {
      throw new SDJWTException('Invalid sd-jwt: jwt or disclosures is missing');
    }
    const { disclosureKeymap } = await unpack(
      this.jwt?.payload,
      this.disclosures,
      hasher,
    );
    return Object.keys(disclosureKeymap).sort();
  }
 
  public async getClaims<T>(hasher: Hasher): Promise<T> {
    if (!this.jwt?.payload || !this.disclosures) {
      throw new SDJWTException('Invalid sd-jwt: jwt or disclosures is missing');
    }
    const { unpackedObj } = await unpack(
      this.jwt.payload,
      this.disclosures,
      hasher,
    );
    return unpackedObj as T;
  }
}
 
export const listKeys = (obj: any, prefix: string = '') => {
  const keys: string[] = [];
  for (let key in obj) {
    if (obj[key] === undefined) continue;
    const newKey = prefix ? `${prefix}.${key}` : key;
    keys.push(newKey);
 
    if (obj[key] && typeof obj[key] === 'object' && obj[key] !== null) {
      keys.push(...listKeys(obj[key], newKey));
    }
  }
  return keys;
};
 
export const pack = async <T extends object>(
  claims: T,
  disclosureFrame: DisclosureFrame<T> | undefined,
  hash: HasherAndAlg,
  saltGenerator: SaltGenerator,
): Promise<{ packedClaims: any; disclosures: Array<Disclosure<any>> }> => {
  if (!disclosureFrame) {
    return {
      packedClaims: claims,
      disclosures: [],
    };
  }
 
  const sd = disclosureFrame[SD_DIGEST] ?? [];
  const decoyCount = disclosureFrame[SD_DECOY] ?? 0;
 
  if (claims instanceof Array) {
    const packedClaims: any[] = [];
    const disclosures: any[] = [];
    const recursivePackedClaims: any = {};
 
    for (const key in disclosureFrame) {
      if (key !== SD_DIGEST) {
        const idx = parseInt(key);
        const packed = await pack(
          claims[idx],
          // @ts-ignore
          disclosureFrame[idx],
          hash,
          saltGenerator,
        );
        recursivePackedClaims[idx] = packed.packedClaims;
        disclosures.push(...packed.disclosures);
      }
    }
 
    for (let i = 0; i < (claims as Array<any>).length; i++) {
      const claim = recursivePackedClaims[i]
        ? recursivePackedClaims[i]
        : claims[i];
      // @ts-ignore
      if (sd.includes(i)) {
        const salt = await saltGenerator(16);
        const disclosure = new Disclosure([salt, claim]);
        const digest = await disclosure.digest(hash);
        packedClaims.push({ [SD_LIST_KEY]: digest });
        disclosures.push(disclosure);
      } else {
        packedClaims.push(claim);
      }
    }
    for (let j = 0; j < decoyCount; j++) {
      const decoyDigest = await createDecoy(hash, saltGenerator);
      packedClaims.push({ [SD_LIST_KEY]: decoyDigest });
    }
    return { packedClaims, disclosures };
  }
 
  const packedClaims: any = {};
  const disclosures: any[] = [];
  const recursivePackedClaims: any = {};
  for (const key in disclosureFrame) {
    if (key !== SD_DIGEST) {
      const packed = await pack(
        // @ts-ignore
        claims[key],
        disclosureFrame[key],
        hash,
        saltGenerator,
      );
      recursivePackedClaims[key] = packed.packedClaims;
      disclosures.push(...packed.disclosures);
    }
  }
 
  const _sd: string[] = [];
 
  for (const key in claims) {
    const claim = recursivePackedClaims[key]
      ? recursivePackedClaims[key]
      : claims[key];
    // @ts-ignore
    if (sd.includes(key)) {
      const salt = await saltGenerator(16);
      const disclosure = new Disclosure([salt, key, claim]);
      const digest = await disclosure.digest(hash);
 
      _sd.push(digest);
      disclosures.push(disclosure);
    } else {
      packedClaims[key] = claim;
    }
  }
 
  for (let j = 0; j < decoyCount; j++) {
    const decoyDigest = await createDecoy(hash, saltGenerator);
    _sd.push(decoyDigest);
  }
 
  if (_sd.length > 0) {
    packedClaims[SD_DIGEST] = _sd.sort();
  }
  return { packedClaims, disclosures };
};