code.dart 7.2 KB

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