code.dart 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. import 'package:ente_auth/utils/totp_util.dart';
  2. import 'package:flutter/foundation.dart';
  3. class Code {
  4. static const defaultDigits = 6;
  5. static const steamDigits = 5;
  6. static const defaultPeriod = 30;
  7. int? generatedID;
  8. final String account;
  9. final String issuer;
  10. final int digits;
  11. final int period;
  12. final String secret;
  13. final Algorithm algorithm;
  14. final Type type;
  15. /// otpauth url in the code
  16. final String rawData;
  17. final int counter;
  18. bool? hasSynced;
  19. final CodeDisplay display;
  20. bool get isPinned => display.pinned;
  21. Code(
  22. this.account,
  23. this.issuer,
  24. this.digits,
  25. this.period,
  26. this.secret,
  27. this.algorithm,
  28. this.type,
  29. this.counter,
  30. this.rawData, {
  31. this.generatedID,
  32. required this.display,
  33. });
  34. Code copyWith({
  35. String? account,
  36. String? issuer,
  37. int? digits,
  38. int? period,
  39. String? secret,
  40. Algorithm? algorithm,
  41. Type? type,
  42. int? counter,
  43. CodeDisplay? display,
  44. }) {
  45. final String updateAccount = account ?? this.account;
  46. final String updateIssuer = issuer ?? this.issuer;
  47. final int updatedDigits = digits ?? this.digits;
  48. final int updatePeriod = period ?? this.period;
  49. final String updatedSecret = secret ?? this.secret;
  50. final Algorithm updatedAlgo = algorithm ?? this.algorithm;
  51. final Type updatedType = type ?? this.type;
  52. final int updatedCounter = counter ?? this.counter;
  53. final CodeDisplay updatedDisplay = display ?? this.display;
  54. return Code(
  55. updateAccount,
  56. updateIssuer,
  57. updatedDigits,
  58. updatePeriod,
  59. updatedSecret,
  60. updatedAlgo,
  61. updatedType,
  62. updatedCounter,
  63. "otpauth://${updatedType.name}/$updateIssuer:$updateAccount?algorithm=${updatedAlgo.name}"
  64. "&digits=$updatedDigits&issuer=$updateIssuer"
  65. "&period=$updatePeriod&secret=$updatedSecret${updatedType == Type.hotp ? "&counter=$updatedCounter" : ""}",
  66. generatedID: generatedID,
  67. display: updatedDisplay,
  68. );
  69. }
  70. static Code fromAccountAndSecret(
  71. Type type,
  72. String account,
  73. String issuer,
  74. String secret,
  75. CodeDisplay? display,
  76. int digits,
  77. ) {
  78. return Code(
  79. account,
  80. issuer,
  81. digits,
  82. defaultPeriod,
  83. secret,
  84. Algorithm.sha1,
  85. type,
  86. 0,
  87. "otpauth://${type.name}/$issuer:$account?algorithm=SHA1&digits=$digits&issuer=$issuer&period=30&secret=$secret",
  88. display: display ?? CodeDisplay(),
  89. );
  90. }
  91. static Code fromOTPAuthUrl(String rawData, {CodeDisplay? display}) {
  92. Uri uri = Uri.parse(rawData);
  93. final issuer = _getIssuer(uri);
  94. try {
  95. return Code(
  96. _getAccount(uri),
  97. issuer,
  98. _getDigits(uri, issuer),
  99. _getPeriod(uri),
  100. getSanitizedSecret(uri.queryParameters['secret']!),
  101. _getAlgorithm(uri),
  102. _getType(uri),
  103. _getCounter(uri),
  104. rawData,
  105. display: CodeDisplay.fromUri(uri) ?? CodeDisplay(),
  106. );
  107. } catch (e) {
  108. // if account name contains # without encoding,
  109. // rest of the url are treated as url fragment
  110. if (rawData.contains("#")) {
  111. return Code.fromOTPAuthUrl(rawData.replaceAll("#", '%23'));
  112. } else {
  113. rethrow;
  114. }
  115. }
  116. }
  117. static String _getAccount(Uri uri) {
  118. try {
  119. String path = Uri.decodeComponent(uri.path);
  120. if (path.startsWith("/")) {
  121. path = path.substring(1, path.length);
  122. }
  123. // Parse account name from documented auth URI
  124. // otpauth://totp/ACCOUNT?secret=SUPERSECRET&issuer=SERVICE
  125. if (uri.queryParameters.containsKey("issuer") && !path.contains(":")) {
  126. return path;
  127. }
  128. return path.split(':')[1];
  129. } catch (e) {
  130. return "";
  131. }
  132. }
  133. static Code fromExportJson(Map rawJson) {
  134. try {
  135. Code resultCode = Code.fromOTPAuthUrl(
  136. rawJson['rawData'],
  137. display: CodeDisplay.fromJson(rawJson['display']),
  138. );
  139. return resultCode;
  140. } catch (e) {
  141. debugPrint("Failed to parse code from export json $e");
  142. rethrow;
  143. }
  144. }
  145. String toExportFormat() {
  146. return jsonEncode(
  147. Uri.parse(
  148. "$rawData&codeDisplay="
  149. "${jsonEncode(display.toJson())}",
  150. ).toString(),
  151. );
  152. }
  153. static String _getIssuer(Uri uri) {
  154. try {
  155. if (uri.queryParameters.containsKey("issuer")) {
  156. String issuerName = uri.queryParameters['issuer']!;
  157. // Handle issuer name with period
  158. // See https://github.com/ente-io/ente/pull/77
  159. if (issuerName.contains("period=")) {
  160. return issuerName.substring(0, issuerName.indexOf("period="));
  161. }
  162. return issuerName;
  163. }
  164. final String path = Uri.decodeComponent(uri.path);
  165. return path.split(':')[0].substring(1);
  166. } catch (e) {
  167. return "";
  168. }
  169. }
  170. static int _getDigits(Uri uri, String issuer) {
  171. try {
  172. return int.parse(uri.queryParameters['digits']!);
  173. } catch (e) {
  174. if (issuer.toLowerCase() == "steam") {
  175. return steamDigits;
  176. }
  177. return defaultDigits;
  178. }
  179. }
  180. static int _getPeriod(Uri uri) {
  181. try {
  182. return int.parse(uri.queryParameters['period']!);
  183. } catch (e) {
  184. return defaultPeriod;
  185. }
  186. }
  187. static int _getCounter(Uri uri) {
  188. try {
  189. final bool hasCounterKey = uri.queryParameters.containsKey('counter');
  190. if (!hasCounterKey) {
  191. return 0;
  192. }
  193. return int.parse(uri.queryParameters['counter']!);
  194. } catch (e) {
  195. return defaultPeriod;
  196. }
  197. }
  198. static Algorithm _getAlgorithm(Uri uri) {
  199. try {
  200. final algorithm =
  201. uri.queryParameters['algorithm'].toString().toLowerCase();
  202. if (algorithm == "sha256") {
  203. return Algorithm.sha256;
  204. } else if (algorithm == "sha512") {
  205. return Algorithm.sha512;
  206. }
  207. } catch (e) {
  208. // nothing
  209. }
  210. return Algorithm.sha1;
  211. }
  212. static Type _getType(Uri uri) {
  213. if (uri.host == "totp") {
  214. return Type.totp;
  215. } else if (uri.host == "steam") {
  216. return Type.steam;
  217. } else if (uri.host == "hotp") {
  218. return Type.hotp;
  219. }
  220. throw UnsupportedError("Unsupported format with host ${uri.host}");
  221. }
  222. @override
  223. bool operator ==(Object other) {
  224. if (identical(this, other)) return true;
  225. return other is Code &&
  226. other.account == account &&
  227. other.issuer == issuer &&
  228. other.digits == digits &&
  229. other.period == period &&
  230. other.secret == secret &&
  231. other.counter == counter &&
  232. other.type == type &&
  233. other.rawData == rawData;
  234. }
  235. @override
  236. int get hashCode {
  237. return account.hashCode ^
  238. issuer.hashCode ^
  239. digits.hashCode ^
  240. period.hashCode ^
  241. secret.hashCode ^
  242. type.hashCode ^
  243. counter.hashCode ^
  244. rawData.hashCode;
  245. }
  246. }
  247. enum Type {
  248. totp,
  249. hotp,
  250. steam;
  251. bool get isTOTPCompatible => this == totp || this == steam;
  252. }
  253. enum Algorithm {
  254. sha1,
  255. sha256,
  256. sha512,
  257. }