qrcode.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /**
  2. * This file is part of Threema Web.
  3. *
  4. * Threema Web is free software: you can redistribute it and/or modify it
  5. * under the terms of the GNU Affero General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or (at
  7. * your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  12. * General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Affero General Public License
  15. * along with Threema Web. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. import {stringToUtf8a} from '../helpers';
  18. /**
  19. * Functionality related to the initial QR code.
  20. */
  21. export class QrCodeService {
  22. private config: threema.Config;
  23. private protocolVersion: number;
  24. public static $inject = ['CONFIG', 'PROTOCOL_VERSION'];
  25. constructor(CONFIG: threema.Config, PROTOCOL_VERSION: number) {
  26. this.config = CONFIG;
  27. this.protocolVersion = PROTOCOL_VERSION;
  28. }
  29. /**
  30. * Create QR code payload.
  31. *
  32. * See `docs/qr_code.md` for more information.
  33. */
  34. public buildQrCodePayload(initiatorKey: Uint8Array, authToken: Uint8Array, serverKey: Uint8Array | null,
  35. host: string, port: number,
  36. persistent: boolean): string {
  37. // tslint:disable:no-bitwise
  38. // Allocate array buffer
  39. const saltyRtcHostBytes = stringToUtf8a(host);
  40. const buf = new ArrayBuffer(2 + 1 + 32 + 32 + 32 + 2 + saltyRtcHostBytes.byteLength);
  41. // Options bitfield
  42. let options = 0;
  43. options |= (this.config.SELF_HOSTED === true ? 1 : 0) << 0;
  44. options |= (persistent ? 1 : 0) << 1;
  45. // Write version and options
  46. const dataView = new DataView(buf);
  47. dataView.setUint16(0, this.protocolVersion);
  48. dataView.setUint8(2, options);
  49. // Write initiator key, auth token and server key
  50. const u8Array = new Uint8Array(buf);
  51. u8Array.set(initiatorKey, 3);
  52. u8Array.set(authToken, 35);
  53. if (serverKey === null) {
  54. u8Array.set(new Uint8Array(32), 67);
  55. } else {
  56. u8Array.set(serverKey, 67);
  57. }
  58. // Write SaltyRTC host and port
  59. dataView.setUint16(99, port);
  60. u8Array.set(saltyRtcHostBytes, 101);
  61. // Base64 encode
  62. return btoa(String.fromCharCode.apply(null, new Uint8Array(buf)));
  63. // tslint:enable:no-bitwise
  64. }
  65. }