-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmisc_ours.txt
More file actions
921 lines (779 loc) · 62 KB
/
misc_ours.txt
File metadata and controls
921 lines (779 loc) · 62 KB
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
/// Miscellaneous utility functions used across the package.
///
// Time-stamp: <Friday 2025-10-24 08:51:54 +1100 Graham Williams>
///
/// Copyright (C) 2024, Software Innovation Institute, ANU.
///
/// Licensed under the MIT License (the "License").
///
/// License: https://choosealicense.com/licenses/mit/.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
///
/// Authors: Anushka Vidanage, Dawei Chen, Zheyuan Xu
library;
import 'dart:convert';
import 'package:flutter/foundation.dart' show debugPrint;
import 'package:crypto/crypto.dart';
import 'package:encrypter_plus/encrypter_plus.dart';
import 'package:fast_rsa/fast_rsa.dart' show KeyPair;
import 'package:intl/intl.dart';
import 'package:jwt_decoder/jwt_decoder.dart';
import 'package:path/path.dart' as path;
import 'package:rdflib/rdflib.dart';
import 'package:solid_auth/solid_auth.dart' show genDpopToken, logout;
import 'package:solidpod/src/solid/api/rest_api.dart';
import 'package:solidpod/src/solid/constants/common.dart';
import 'package:solidpod/src/solid/constants/path_type.dart';
import 'package:solidpod/src/solid/constants/schema.dart';
import 'package:solidpod/src/solid/constants/web_acl.dart';
import 'package:solidpod/src/solid/revoke_permission_to_recipients.dart';
import 'package:solidpod/src/solid/utils/app_info.dart';
import 'package:solidpod/src/solid/utils/authdata_manager.dart';
import 'package:solidpod/src/solid/utils/exceptions.dart';
import 'package:solidpod/src/solid/utils/key_manager.dart';
import 'package:solidpod/src/solid/utils/permission.dart';
import 'package:solidpod/src/solid/utils/rdf.dart';
/// Global callback for clearing application-specific caches during logout.
/// Apps should register their cache clearing logic here.
/// This ensures caches are cleared BEFORE any blocking network operations.
Future<void> Function()? _onLogoutClearCaches;
/// Register a callback to clear application-specific caches during logout.
/// This callback will be invoked BEFORE the OAuth2 logout endpoint call,
/// preventing race conditions where cached data might be visible during logout.
void registerLogoutCacheCallback(Future<void> Function() callback) {
_onLogoutClearCaches = callback;
}
// solid-encrypt uses unencrypted local storage and refers to http: //yarrabah.net/ for predicates definition,
// do not use it before it is updated (same as what the gurriny project does)
// import 'package:solid_encrypt/solid_encrypt.dart' as solid_encrypt;
/// Write the given [key], [value] pair to the secure storage.
///
/// If [key] already exisits then delete that first and then
/// write again.
Future<void> writeToSecureStorage(String key, String value) async {
final isKeyExist = await secureStorage.containsKey(
key: key,
);
// Since write() method does not automatically overwrite an existing value.
// To overwrite an existing value, call delete() first.
if (isKeyExist) {
await secureStorage.delete(
key: key,
);
}
await secureStorage.write(
key: key,
value: value,
);
}
/// Encrypt data using AES with the specified key
String encryptData(String data, Key key, IV iv, {AESMode mode = AESMode.sic}) =>
Encrypter(AES(key, mode: mode)).encrypt(data, iv: iv).base64;
/// Decrypt a ciphertext value
String decryptData(
String encData,
Key key,
IV iv, {
AESMode mode = AESMode.sic,
}) =>
Encrypter(AES(key, mode: mode)).decrypt(Encrypted.from64(encData), iv: iv);
/// Load and parse a private TTL file from POD
Future<Map<String, dynamic>> loadPrvTTL(String fileUrl) async {
// final fileUrl = await getFileUrl(filePath);
try {
if (await checkResourceStatus(fileUrl) == ResourceStatus.exist) {
final rawContent = await fetchPrvFile(fileUrl);
return parseTtlContent(rawContent);
} else {
return {};
}
} on Exception catch (e) {
throw Exception(e);
}
}
/// Read the encryption key file content for display purposes.
///
/// This function directly reads the encryption key file without using readPod,
/// making it suitable for accessing files outside the appname/data directory.
///
/// Returns the raw TTL content of the encryption key file.
Future<String> readEncryptionKeyContent() async {
final encKeyPath = await getEncKeyPath();
final encKeyUrl = await getFileUrl(encKeyPath);
try {
if (await checkResourceStatus(encKeyUrl) == ResourceStatus.exist) {
return await fetchPrvFile(encKeyUrl);
} else {
throw Exception('Encryption key file does not exist at: $encKeyPath');
}
} on Exception catch (e) {
throw Exception('Failed to read encryption key file: $e');
}
}
/// Generates a public key block from a given key content.
String genPubKeyStr(String pubKeyContent) =>
'''-----BEGIN RSA PUBLIC KEY-----\n$pubKeyContent\n-----END RSA PUBLIC KEY-----''';
/// Get unique bit of the webId
String getUniqueStrWebId(String webId) {
var uniqueStr = webId.replaceAll('https://', '');
uniqueStr = uniqueStr.replaceAll('http://', '');
uniqueStr = uniqueStr.replaceAll('/$profCard', '');
uniqueStr = uniqueStr.replaceAll('/', '-');
return uniqueStr;
}
/// Generate unique ID for the resource URL
/// In order for the ID to be unique across all webIDs and no one can
/// reverse engineer the resource being shared we also use receiver webId
/// in the ID generation process
String getUniqueIdResUrl(String resourceUrl, String receiverWebId) {
return sha256.convert(utf8.encode(resourceUrl + receiverWebId)).toString();
}
/// From a given resource path [resourcePath] create its URL
/// [isContainer] should be true if the resource is a directory, otherwise false
/// returns the full resource URL
Future<String> _getResourceUrl(
String resourcePath,
bool isContainer, [
String? extWebId,
]) async {
// Check if resource url is needed for an external webId
final webId = extWebId ?? await AuthDataManager.getWebId();
// If webId is null (user logged out), return empty or throw informative error
if (webId == null || webId.isEmpty) {
throw Exception('User not logged in: cannot access resource URL');
}
if (!webId.contains(profCard)) {
throw Exception('Invalid webId format: must contain $profCard');
}
final resourceUrl = webId.replaceAll(profCard, resourcePath);
if (isContainer && !resourceUrl.endsWith('/')) {
return '$resourceUrl/';
}
return resourceUrl;
}
/// Create the URL for a file
Future<String> getFileUrl(String filePath, [String? extWebId]) async =>
await _getResourceUrl(filePath, false, extWebId);
/// Create the URL for a directory (container)
Future<String> getDirUrl(String dirPath, [String? extWebId]) async =>
await _getResourceUrl(dirPath, true, extWebId);
/// Get resource Url from a filename, with different options for how
/// the filename is provided. If [isExternalRes] or [isFileUrl] is
/// set to true, the filename is already the resource url and is
/// returned unchanged.
///
/// Parameters:
/// - [fileName] - name of file of interest.
/// - [isFile] - flag describing whether the resources is a file or not.
/// If false the [fileName] is a directory. (Default: true).
/// - [isFilePath] - flag describing whether [fileName] includes the
/// directory data path. (Default: false).
/// - [isFileUrl] - flag describing whether [fileName] is the url of the
/// file. (Default: false).
/// - [isExternalRes] - flag describing whether the file is an external
/// file shared with the user. In which case the [fileName] should be
/// the full URL of the file. (Default: false).
Future<String> filenameToResourceUrl({
required String fileName,
bool isFile = true,
bool isFileUrl = false,
bool isExternalRes = false,
}) async {
final String resourceUrl;
final String filePath;
// Note: external resources always specified by url
if (isExternalRes) {
isFileUrl = true;
}
// If not already a url, get url
if (!isExternalRes && !isFileUrl) {
// Get the file path
// Ensure path uses correct path separators and
// has app data dir prepended.
filePath = await normalizeFilePath(fileName, null);
// Get the url of the resource by prepending the
// user = owner webID (excluding profCard)
if (isFile) {
resourceUrl = await getFileUrl(filePath);
} else {
resourceUrl = await getDirUrl(filePath);
}
} else {
// Use fileName, fileName already the resource url
resourceUrl = fileName;
}
return resourceUrl;
}
/// Derive external POD inherited parent directory url from the resource url
/// and parent directory path
String getExtDirUrl(String resourceUrl, String dirPath) {
int pathIndex = resourceUrl.indexOf(dirPath);
String dirUrl = '';
if (pathIndex != -1) {
dirUrl = resourceUrl.substring(0, pathIndex + dirPath.length);
if (!dirUrl.endsWith('/')) {
dirUrl += '/';
}
}
return dirUrl;
}
/// Encrypt a given data string and format to TTL
Future<String> getEncTTLStr(
String filePath,
String fileContent,
Key key,
IV iv, {
String? extWebId,
String? inheritKeyFrom,
}) async {
final triples = {
URIRef(await getFileUrl(filePath, extWebId)): {
solidTermsNS.ns.withAttr(pathPred): filePath,
solidTermsNS.ns.withAttr(ivPred): iv.base64,
if (inheritKeyFrom != null)
solidTermsNS.ns.withAttr(inheritKeyPred): inheritKeyFrom,
solidTermsNS.ns.withAttr(encDataPred): encryptData(fileContent, key, iv),
},
};
final bindNS = {solidTermsNS.prefix: solidTermsNS.ns};
return tripleMapToTurtle(triples, bindNamespaces: bindNS);
}
/// Returns the path of file with verification key and private key
Future<String> getEncKeyPath() async =>
[appDirName, encDir, encKeyFile].join('/');
/// Returns the path of file with individual keys
Future<String> getIndKeyPath() async =>
[appDirName, encDir, indKeyFile].join('/');
/// Returns the path of file with public keys
Future<String> getPubKeyPath() async =>
[appDirName, sharingDir, pubKeyFile].join('/');
/// Returns the path of public file with individual keys
Future<String> getPubIndKeyPath() async =>
[appDirName, sharingDir, pubIndKeyFile].join('/');
/// Returns the path of file with individual keys accessed only
/// by authenticated users
Future<String> getAuthUserIndKeyPath() async =>
[appDirName, sharingDir, authUserIndKeyFile].join('/');
/// Returns the path of the data directory
Future<String> getDataDirPath() async => [appDirName, dataDir].join('/');
/// Returns the path of the shared directory
Future<String> getSharedDirPath() async => [appDirName, sharedDir].join('/');
/// Returns the path of the file with shared individual keys
Future<String> getSharedKeyFilePath() async =>
[appDirName, sharedDir, sharedKeyFile].join('/');
/// Returns the path of the encryption directory
Future<String> getEncDirPath() async => [appDirName, encDir].join('/');
/// Returns the path of the encryption directory
Future<String> getPermLogFilePath() async =>
[appDirName, logsDir, permLogFile].join('/');
/// Extract the app name and the version from the package info
/// Return a record (with named fields https://dart.dev/language/records)
Future<({String name, String version})> getAppNameVersion() async =>
(name: await AppInfo.name, version: await AppInfo.version);
/// Return the web ID
Future<String?> getWebId() async => AuthDataManager.getWebId();
/// Check whether a user is logged in or not
///
/// Check if the local storage has authentication
/// details of the user and also check whether the
/// access token is expired or not
/// returns boolean
Future<bool> checkLoggedIn() async {
final webId = await AuthDataManager.getWebId();
if (webId != null && webId.isNotEmpty) {
final accessToken = await AuthDataManager.getAccessToken();
if (accessToken != null && !JwtDecoder.isExpired(accessToken)) {
return true;
}
}
return false;
}
/// Create a directory with the given URL
Future<void> createDir(String dirUrl) async {
if (!dirUrl.endsWith('/')) {
throw Exception('Directory URL must end with /: $dirUrl');
}
await createResource(
dirUrl,
isFile: false,
replaceIfExist: false,
contentType: ResourceContentType.directory,
);
}
/// Delete login information from the local storage
///
/// returns true if successful
Future<bool> deleteLogIn() async => AuthDataManager.removeAuthData();
/// Generates a list of default folder paths for a given application.
///
/// This function takes the name of an application as input and returns a list of strings.
/// Each string in the list represents a path to a default folder for the application.
Future<List<String>> generateDefaultFolders() async {
final dataDirLoc = [appDirName, dataDir].join('/');
final sharingDirLoc = [appDirName, sharingDir].join('/');
final sharedDirLoc = [appDirName, sharedDir].join('/');
final encDirLoc = [appDirName, encDir].join('/');
final logDirLoc = [appDirName, logsDir].join('/');
final folders = [
appDirName,
sharingDirLoc,
sharedDirLoc,
dataDirLoc,
encDirLoc,
logDirLoc,
];
return folders;
}
/// Generates a list of default folder paths for a given application.
///
/// This function takes the name of an application as input and returns a list of strings.
/// Each string in the list represents a path to a default folder for the application.
Future<Map<dynamic, dynamic>> generateDefaultFiles() async {
final sharingDirLoc = [appDirName, sharingDir].join('/');
final sharedDirLoc = [appDirName, sharedDir].join('/');
final encDirLoc = [appDirName, encDir].join('/');
final logDirLoc = [appDirName, logsDir].join('/');
final files = {
sharingDirLoc: [
pubKeyFile,
'$pubKeyFile.acl',
],
logDirLoc: [
permLogFile,
'$permLogFile.acl',
],
sharedDirLoc: ['.acl'],
encDirLoc: [encKeyFile, indKeyFile],
};
return files;
}
/// Set directory name for the app for storing the POD data
///
/// If not initially set the app name will be taken by default.
Future<void> setAppDirName(String inputAppDirName) async {
if (inputAppDirName.isEmpty) {
appDirName = await AppInfo.canonicalName;
} else {
appDirName = inputAppDirName;
}
}
/// Get resource acl file path
String getResAclFile(String resourceUrl, [bool isFile = true]) {
final resourceAclUrl = resourceUrl.endsWith('.acl')
? resourceUrl
: isFile
? '$resourceUrl.acl'
: '$resourceUrl/.acl';
return resourceAclUrl;
}
/// Extract permission details of a file into a map.
/// Returns a map where keys are permission receiver webIds and
/// values are the list of permissions
Map<dynamic, dynamic> extractAclPerm(Map<dynamic, dynamic> aclFileContentMap) {
final filePermMap = <dynamic, dynamic>{};
for (final accessStr in aclFileContentMap.keys) {
final permList = aclFileContentMap[accessStr][modePred];
final receiverMap = {};
if ((aclFileContentMap[accessStr] as Map).containsKey(agentPred)) {
for (final receiverId
in aclFileContentMap[accessStr][agentPred] as List) {
receiverMap[receiverId] = agentPred;
}
}
if ((aclFileContentMap[accessStr] as Map).containsKey(agentClassPred)) {
for (final receiverId
in aclFileContentMap[accessStr][agentClassPred] as List) {
receiverMap[receiverId] = agentClassPred;
}
}
if ((aclFileContentMap[accessStr] as Map).containsKey(agentGroupPred)) {
for (final receiverId
in aclFileContentMap[accessStr][agentGroupPred] as List) {
receiverMap[receiverId] = agentGroupPred;
}
}
for (final receiverId in receiverMap.keys) {
if (filePermMap.containsKey(receiverId)) {
filePermMap[receiverId][permStr] += permList;
filePermMap[receiverId][agentStr] = receiverMap[receiverId];
} else {
filePermMap[receiverId] = {
permStr: permList,
agentStr: receiverMap[receiverId],
};
}
}
}
return filePermMap;
}
/// Get resource name from URL
String getResNameFromUrl(String resourceUrl) {
return resourceUrl.split('/').last;
}
/// Get tokens necessary to fetch a resource from a POD
///
/// returns the access token and DPoP token
Future<({String accessToken, String dPopToken})> getTokensForResource(
String resourceUrl,
String httpMethod,
) async {
final authData = await AuthDataManager.loadAuthData();
if (authData == null) {
throw Exception('No authentication data available');
}
final rsaInfo = authData['rsaInfo'];
final rsaKeyPair = rsaInfo['rsa'] as KeyPair;
final publicKeyJwk = rsaInfo['pubKeyJwk'];
return (
accessToken: authData['accessToken'] as String,
dPopToken: genDpopToken(resourceUrl, rsaKeyPair, publicKeyJwk, httpMethod),
);
}
/// Logging out the user with comprehensive error handling and platform support
///
/// This function performs a complete logout that includes:
/// 1. Clearing all encryption keys from memory
/// 2. Removing authentication data from secure storage
/// 3. Calling the OAuth2 logout endpoint (with error tolerance on web)
///
/// Returns true if logout succeeds or critical operations complete,
/// false only if critical operations (key/auth cleanup) fail.
Future<bool> logoutPod() async {
try {
// Step 1: Clear all cached encryption keys and security data from memory
// This is CRITICAL and must be done regardless of other failures
await KeyManager.clear();
debugPrint('logoutPod() => KeyManager.clear() completed');
// Step 2: Remove authentication data from secure storage
// This is CRITICAL - must succeed
final authDataRemoved = await AuthDataManager.removeAuthData();
if (!authDataRemoved) {
debugPrint(
'logoutPod() => WARNING: AuthDataManager.removeAuthData() failed',
);
// Don't return false yet - logout endpoint is still needed
}
// Step 2.5: Clear application-specific caches BEFORE network call
// This is CRITICAL to prevent race conditions where UI reads stale cache
// during logout, especially when network is slow
if (_onLogoutClearCaches != null) {
try {
await _onLogoutClearCaches!();
} on Object catch (e) {
debugPrint(
'logoutPod() => WARNING: Application cache callback failed (non-critical): $e',
);
// Continue - the critical auth data is already cleared
}
} else {
debugPrint(
'logoutPod() => No application cache callback registered',
);
}
// Step 3: Get the logout URL and attempt OAuth2 logout
// This is OPTIONAL - should not block if it fails
final logoutUrl = await AuthDataManager.getLogoutUrl();
if (logoutUrl != null && logoutUrl.isNotEmpty) {
try {
// Call the OAuth2 logout endpoint
// On web, this may fail with platform-related exceptions, but we continue anyway
await logout(logoutUrl);
debugPrint('logoutPod() => OAuth2 logout endpoint called successfully');
} on Object catch (e) {
// On Flutter Web, platform-related exceptions might occur
// This is NOT a critical failure - the local session is already cleared
debugPrint('logoutPod() => OAuth2 logout warning (non-critical): $e');
// Continue - local data is already cleared which is most important
}
} else {
debugPrint(
'logoutPod() => No logout URL available, skipping OAuth2 logout',
);
}
// Success if we cleared the local data (most important part)
return authDataRemoved;
} on Object catch (e) {
// Catch any remaining exceptions
debugPrint('logoutPod() => CRITICAL ERROR: $e');
// Even if we reach here, attempt to clear auth data as fallback
try {
await AuthDataManager.removeAuthData();
await KeyManager.clear();
} catch (fallbackError) {
debugPrint('logoutPod() => Fallback cleanup also failed: $fallbackError');
}
return false;
}
}
/// Removes header and footer (which mess up the TTL format) from a PEM-formatted public key string.
///
/// This function takes a public key string, typically in PEM format, and removes
/// the standard PEM headers and footers.
String trimPubKeyStr(String keyStr) {
final itemList = keyStr.split('\n');
itemList.remove('-----BEGIN RSA PUBLIC KEY-----');
itemList.remove('-----END RSA PUBLIC KEY-----');
itemList.remove('-----BEGIN PUBLIC KEY-----');
itemList.remove('-----END PUBLIC KEY-----');
final keyStrTrimmed = itemList.join();
return keyStrTrimmed;
}
/// Initialise the directory and file structure in a POD
Future<void> initPod(
String securityKey, {
List<String>? dirUrls,
List<String>? fileUrls,
}) async {
// Check if the user has logged in
final loggedIn = await checkLoggedIn();
if (!loggedIn) {
throw NotLoggedInException('Can not initialise POD without logging in');
}
// Check (and generate) the directory URLs
if (dirUrls == null || dirUrls.isEmpty) {
final defaultDirs = await generateDefaultFolders();
dirUrls = [for (final d in defaultDirs) await getDirUrl(d)];
}
// Require the creation of the encryption directory and
// the encKeyFile and indKeyFile in it.
// (The app asks for the security key, so this is a reasonable requirement?)
final encDirUrl = await getDirUrl(await getEncDirPath());
if (!dirUrls.contains(encDirUrl)) {
throw Exception('Can not initialise POD without creating $encDirUrl');
}
// Create the required directories
for (final d in dirUrls) {
await createResource(
d,
isFile: false,
contentType: ResourceContentType.directory,
);
}
// Check (and generate) the file URLs
if (fileUrls == null || fileUrls.isEmpty) {
final defaultFiles = await generateDefaultFiles();
fileUrls = <String>[];
for (final entry in defaultFiles.entries) {
final d = entry.key;
for (final f in entry.value as List) {
fileUrls.add([d, f].join('/'));
}
}
}
// Create the encKeyFile, indKeyFile and pubKeyFile
// and remove them from the fileUrls list
await KeyManager.initPodKeys(securityKey);
fileUrls.remove(await getFileUrl(await getEncKeyPath()));
fileUrls.remove(await getFileUrl(await getIndKeyPath()));
fileUrls.remove(await getFileUrl(await getPubKeyPath()));
for (final f in fileUrls) {
final fileName = f.split('/').last;
late String fileContent;
late bool aclFlag;
if (f.split('.').last == 'acl') {
final items = f.split('.');
final resourceUrl = items.getRange(0, items.length - 1).join('.');
late Set<AccessMode> publicAccess;
var isFile = true;
switch (fileName) {
case '$pubKeyFile.acl':
publicAccess = {AccessMode.read};
case '$permLogFile.acl':
publicAccess = {AccessMode.append};
default:
debugPrint(fileName);
if (fileName != '.acl') {
debugPrint('Warning: Unexpected ACL file: $fileName');
}
publicAccess = {AccessMode.read, AccessMode.write};
isFile = false;
}
fileContent = await genAclTurtle(
resourceUrl,
isFile: isFile,
publicAccess: publicAccess,
);
aclFlag = true;
} else {
debugPrint(fileName);
if (fileName != permLogFile) {
debugPrint('Warning: Unexpected file: $fileName');
}
fileContent = genPermLogTTLStr(f);
aclFlag = false;
}
await createResource(f, content: fileContent, replaceIfExist: aclFlag);
}
}
/// Delete the ACL file for a resource
Future<void> deleteAclForResource(String resourceUrl) async {
final aclUrl = '$resourceUrl.acl';
final status = await checkResourceStatus(aclUrl);
switch (status) {
case ResourceStatus.exist:
await deleteResource(aclUrl, ResourceContentType.turtleText);
case ResourceStatus.forbidden:
debugPrint(
'Access to ACL file "$aclUrl" for "$resourceUrl" is forbidden.',
);
case ResourceStatus.notExist:
debugPrint('ACL file "$aclUrl" for "$resourceUrl" does not exist.');
case ResourceStatus.unknown:
throw Exception(
'Error occurred when checking status of ACL file "$aclUrl" for "$resourceUrl"',
);
}
}
/// Delete a file and its associated resources, after first revoking
/// external access to the file. The file with path [filePath],
/// its ACL file, and its encryption key (if exists) will be deleted.
/// The permission logs of any recipients to the file, will also be
/// updated with a log line recording that permissions have been
/// revoked.
/// Throws an exception if the file does not exist or any error occurs.
///
/// Arguments:
///
/// - [filePath] - path of file to be deleted. Where [filePath] is the
/// app data directory and the filename.
/// - [contentType] - the type of content of the resource. Default:
/// [ResourceContentType.turtleText].
/// - [isKey] - flag describing whether the file to be deleted is a
/// security key. Use this flag if file is a security key to avoid
/// unnecessary operations that are not needed to delete a key.
Future<void> deleteFile(
String filePath, {
ResourceContentType contentType = ResourceContentType.turtleText,
bool isKey = false,
}) async {
if (!isKey) {
// File to be deleted != key => perform all steps
// Revoke permission to recipients:
// to avoid the permission log of recipients still
// showing the recipient as having access to the
// file that is being deleted
await revokePermissionToRecipients(
fileName: filePath,
);
final fileUrl = await getFileUrl(filePath);
await deleteResource(fileUrl, contentType);
await deleteAclForResource(fileUrl);
if (await KeyManager.hasIndividualKey(fileUrl)) {
await KeyManager.removeIndividualKey(filePath);
}
} else {
// File to be deleted == key => perform delete only
final fileUrl = await getFileUrl(filePath);
await deleteResource(fileUrl, contentType);
}
}
/// Delete an external file with path [fileUrl] and the shared key
/// if the file is encrypted.
/// Throws an exception if the file does not exist or any error occurs.
Future<void> deleteExternalFile(
String fileUrl, {
ResourceContentType contentType = ResourceContentType.turtleText,
}) async {
await deleteResource(fileUrl, contentType);
await deleteAclForResource(fileUrl);
if (await KeyManager.hasSharedIndividualKey(fileUrl)) {
final webId = await AuthDataManager.getWebId();
final resUniqueId = getUniqueIdResUrl(fileUrl, webId!);
await KeyManager.removeSharedIndividualKey(fileUrl, resUniqueId);
}
/// av: Need to add the funtionality to remove the log line from permission
/// log. Otherwise, it will give an error.
}
/// Get date and time from a string
String getDateTime(String dateTimeStr) {
final dateTime = DateTime.parse(dateTimeStr);
final dateFormat = DateFormat('dd/MM/yyyy hh:mm:ss a');
return dateFormat.format(dateTime);
}
/// Normalise file path for readPod/writePod operations.
///
/// Handles backward compatibility by checking if the filePath already includes
/// the app directory prefix, and constructs the appropriate normalised path.
///
/// When basePath is null (default for readPod/writePod), uses appname/data as base path.
///
/// [filePath] - The input file path
/// [basePath] - The base path to use (defaults to appname/data when null)
///
/// Returns the normalised file path.
///
/// Examples:
/// - `normalizeFilePath('abc.ttl', null)` returns `appname/data/abc.ttl`
/// - `normalizeFilePath('movies/abc.ttl', null)` returns `appname/data/movies/abc.ttl`
/// - `normalizeFilePath('appname/data/keys.ttl', null)` returns `appname/data/keys.ttl`
///
/// Note: Only `appname/data/` paths are supported for readPod/writePod operations.
Future<String> normalizeFilePath(String filePath, String? basePath) async {
// Normalise path separators for cross-platform compatibility.
final normalizedInput = filePath.replaceAll(path.separator, '/');
// Use provided path or default to appname/data.
final effectiveBasePath = basePath == null || basePath.trim().isEmpty
? await getDataDirPath()
: basePath;
// Check if path already starts with the correct base path (appname/data/).
if (normalizedInput.startsWith(effectiveBasePath)) {
// Full path is already prepended (appname/data/).
return normalizedInput;
} else {
// Prepend the base path.
return [effectiveBasePath, normalizedInput].join('/');
}
}
/// Check if a given path string is a directory or not
bool isDir(String path) {
if (path.endsWith('/') || !path.contains('.')) {
return true;
} else {
return false;
}
}
/// Generate the URL of resource according to its path and the type of the path.
Future<String> generateResourceUrlFromPath({
required String resourcePath,
required PathType pathType,
bool isFile = true,
}) async {
final func = isFile ? getFileUrl : getDirUrl;
switch (pathType) {
case PathType.absoluteUrl:
return resourcePath;
case PathType.relativeToPod:
return await func(resourcePath);
case PathType.relativeToApp:
return await func([appDirName, resourcePath].join('/'));
case PathType.relativeToData:
return await func([await getDataDirPath(), resourcePath].join('/'));
}
}
/// Extract resource path from its URL
Future<String> extractResourcePathFromUrl(
String resourceUrl, {
bool isFile = true,
}) async {
// See https://api.dart.dev/dart-core/Uri-class.html for details
final segments = Uri.parse(resourceUrl).pathSegments;
final path = segments.getRange(1, segments.length).join('/');
return !(isFile || path.endsWith('/')) ? '$path/' : path;
}