@sagepilot-ai/react-native-events-addon 0.0.0-stage → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +21 -0
- package/README.md +138 -2
- package/SagepilotEventsAddon.podspec +16 -0
- package/android/build.gradle +8 -0
- package/android/src/main/AndroidManifest.xml +3 -0
- package/android/src/main/java/ai/sagepilot/events/SagepilotEventsHTTP.java +67 -0
- package/android/src/main/java/ai/sagepilot/events/SagepilotEventsModule.java +96 -0
- package/android/src/main/java/ai/sagepilot/events/SagepilotEventsPackage.java +16 -0
- package/android/src/main/java/ai/sagepilot/events/SagepilotEventsProjection.java +190 -0
- package/android/src/main/java/ai/sagepilot/events/SagepilotEventsRuntime.java +249 -0
- package/android/src/main/java/ai/sagepilot/events/SagepilotEventsStore.java +173 -0
- package/dist/index.d.mts +49 -0
- package/dist/index.d.ts +49 -0
- package/dist/index.js +1051 -0
- package/dist/index.mjs +1024 -0
- package/ios/SagepilotEventsCore.h +21 -0
- package/ios/SagepilotEventsCore.m +290 -0
- package/ios/SagepilotEventsHTTP.h +8 -0
- package/ios/SagepilotEventsHTTP.m +74 -0
- package/ios/SagepilotEventsModule.m +250 -0
- package/package.json +14 -4
- package/react-native.config.js +4 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
#import <Foundation/Foundation.h>
|
|
2
|
+
|
|
3
|
+
/** Native-worker projection shared by all supported app payload shapes. */
|
|
4
|
+
@interface SagepilotEventsProjection : NSObject
|
|
5
|
+
+ (NSDictionary *)project:(NSString *)body;
|
|
6
|
+
+ (NSString *)route:(NSString *)input;
|
|
7
|
+
@end
|
|
8
|
+
|
|
9
|
+
/** Bounded file journal; every method is owned by the module's serial background queue. */
|
|
10
|
+
@interface SagepilotEventsStore : NSObject
|
|
11
|
+
@property(nonatomic, readonly) NSString *installationId;
|
|
12
|
+
+ (NSString *)scopeForWorkspace:(NSString *)workspace channel:(NSString *)channel;
|
|
13
|
+
- (instancetype)initWithDirectory:(NSString *)directory scope:(NSString *)scope;
|
|
14
|
+
- (NSDictionary *)owner:(NSDictionary *)owner;
|
|
15
|
+
- (void)append:(NSDictionary *)event;
|
|
16
|
+
- (NSDictionary *)nextBatchForOwner:(NSDictionary *)owner nativeDropped:(NSUInteger)dropped;
|
|
17
|
+
- (void)acknowledge:(NSString *)lease ids:(NSArray<NSString *> *)ids;
|
|
18
|
+
- (void)clear;
|
|
19
|
+
- (void)reject;
|
|
20
|
+
- (NSDictionary *)diagnostics;
|
|
21
|
+
@end
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
#import "SagepilotEventsCore.h"
|
|
2
|
+
#import <CommonCrypto/CommonDigest.h>
|
|
3
|
+
#import <TargetConditionals.h>
|
|
4
|
+
#import <zlib.h>
|
|
5
|
+
|
|
6
|
+
static const NSUInteger SPEventBytes = 32768, SPBatchBytes = 131072, SPMaxRecords = 2048, SPMaxBytes = 10 * 1024 * 1024;
|
|
7
|
+
static NSString * const SPSensitivePattern = @"password|secret|token|auth|email|phone|address|card|payment|customer|user|session|cookie|medical|health|credential|private|passport|license|socialsecurity|apikey|accesskey|jwt|birth|iban|cvv|passcode|(^pin$)|(^otp$)|(^ssn$)";
|
|
8
|
+
static NSString * const SPTextPattern = @"name$|title$|description$|message$|comments?$|notes?$|^content$|html$|^text$|freetext$|^search$|^query$";
|
|
9
|
+
static NSString * const SPPrivateValuePattern = @"(?i)@|^bearer|^eyJ[A-Za-z0-9_-]*\\.|^(sk|pk)_(live|test)_|^(?:\\+?[0-9]{7,19}|\\+?[0-9]{1,4}[-.() ]?[0-9]{3}[-.() ]?[0-9]{3,4})$";
|
|
10
|
+
|
|
11
|
+
/** Turns local I/O/format failures into catchable collector errors instead of application failures. */
|
|
12
|
+
static void SPRequire(BOOL value) { if (!value) [NSException raise:@"SagepilotEvents" format:@"App-event journal operation failed"]; }
|
|
13
|
+
/** Encodes only already-projected, bounded JSON values. */
|
|
14
|
+
static NSData *SPJSON(id value) { NSData *data = [NSJSONSerialization dataWithJSONObject:value options:NSJSONWritingWithoutEscapingSlashes error:nil]; SPRequire(data != nil); return data; }
|
|
15
|
+
/** Writes one complete file atomically in the SDK-owned directory. */
|
|
16
|
+
static void SPAtomic(NSString *path, NSData *data) {
|
|
17
|
+
SPRequire([data writeToFile:path options:NSDataWritingAtomic error:nil]);
|
|
18
|
+
#if TARGET_OS_IPHONE
|
|
19
|
+
SPRequire([NSFileManager.defaultManager setAttributes:@{NSFileProtectionKey:NSFileProtectionCompleteUntilFirstUserAuthentication} ofItemAtPath:path error:nil]);
|
|
20
|
+
#endif
|
|
21
|
+
}
|
|
22
|
+
/** Reads a bounded metadata or event file without buffering an unlimited body. */
|
|
23
|
+
static NSDictionary *SPRead(NSString *path) {
|
|
24
|
+
NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
|
|
25
|
+
SPRequire(attributes && [attributes fileSize] <= SPEventBytes);
|
|
26
|
+
id value = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:path] options:0 error:nil];
|
|
27
|
+
SPRequire([value isKindOfClass:NSDictionary.class]); return value;
|
|
28
|
+
}
|
|
29
|
+
/** Preserves the exact original session and customer in a stable comparison key. */
|
|
30
|
+
static NSString *SPOwnerKey(NSDictionary *owner) {
|
|
31
|
+
return [[NSString alloc] initWithData:SPJSON(@[owner[@"session_id"] ?: @"", owner[@"customer_id"] ?: NSNull.null]) encoding:NSUTF8StringEncoding];
|
|
32
|
+
}
|
|
33
|
+
/** Normalizes allowlist matching without rewriting the source field's name. */
|
|
34
|
+
static NSString *SPKey(NSString *key) { return [[key stringByReplacingOccurrencesOfString:@"_" withString:@""] lowercaseString]; }
|
|
35
|
+
/** Matches bounded strings against fixed patterns, never app-provided regular expressions. */
|
|
36
|
+
static BOOL SPMatches(NSString *text, NSString *pattern) {
|
|
37
|
+
static NSDictionary<NSString *,NSRegularExpression *> *patterns; static dispatch_once_t once;
|
|
38
|
+
dispatch_once(&once, ^{
|
|
39
|
+
NSMutableDictionary *compiled = [NSMutableDictionary dictionary];
|
|
40
|
+
for (NSString *source in @[SPSensitivePattern,SPTextPattern,SPPrivateValuePattern,@"^[0-9]{7,15}$",@"^[A-Za-z0-9_./:@+-]{0,256}$",@"^[vV][0-9]{1,3}$",@"^[A-Za-z][A-Za-z_-]{0,47}$",@"(?i)^(Product|ProductVariant)$",@"[\\x00-\\x1f]",@"^\\s*[\\[{]",@"^[A-Za-z_][A-Za-z0-9_]{0,63}$",@"^[A-Za-z0-9-]{1,100}$"]) compiled[source] = [NSRegularExpression regularExpressionWithPattern:source options:0 error:nil];
|
|
41
|
+
patterns = [compiled copy];
|
|
42
|
+
});
|
|
43
|
+
NSRegularExpression *compiled = patterns[pattern];
|
|
44
|
+
return compiled ? [compiled firstMatchInString:text options:0 range:NSMakeRange(0,text.length)] != nil : NO;
|
|
45
|
+
}
|
|
46
|
+
/** Excludes sensitive subtrees before either values or structural paths are retained. */
|
|
47
|
+
static BOOL SPSensitive(NSString *name) { return SPMatches(name, SPSensitivePattern); }
|
|
48
|
+
/** Lists public product and money fields supported by the generic discovery collector. */
|
|
49
|
+
static NSSet *SPFields(void) {
|
|
50
|
+
static NSSet *fields; static dispatch_once_t once;
|
|
51
|
+
dispatch_once(&once, ^{ fields = [NSSet setWithArray:@[@"id",@"productid",@"productcode",@"variantid",@"variantcode",@"merchandiseid",@"sku",@"title",@"name",@"brand",@"category",@"price",@"unitprice",@"sellingprice",@"saleprice",@"amount",@"currency",@"currencycode",@"quantity",@"quantityadded",@"delta",@"discount",@"discountamount",@"image",@"imageurl",@"url",@"producturl",@"available",@"availability",@"typename"]]; });
|
|
52
|
+
return fields;
|
|
53
|
+
}
|
|
54
|
+
/** Recognizes explicit product references; a bare id is never sufficient. */
|
|
55
|
+
static BOOL SPCandidate(NSDictionary *object) {
|
|
56
|
+
for (NSString *key in @[@"sku",@"product_id",@"productId",@"productCode",@"product_code",@"merchandiseId",@"merchandise_id"]) if (object[key] && object[key] != NSNull.null) return YES;
|
|
57
|
+
return [object[@"__typename"] isKindOfClass:NSString.class] && SPMatches(object[@"__typename"], @"(?i)^(Product|ProductVariant)$");
|
|
58
|
+
}
|
|
59
|
+
/** Preserves bounded public product attributes and small nested money objects. */
|
|
60
|
+
static id SPAttribute(id value, NSString *name, NSUInteger depth) {
|
|
61
|
+
if (value == NSNull.null) return value;
|
|
62
|
+
if ([value isKindOfClass:NSNumber.class]) return isfinite([value doubleValue]) && fabs([value doubleValue]) <= 9007199254740991.0 ? value : nil;
|
|
63
|
+
if ([value isKindOfClass:NSString.class]) {
|
|
64
|
+
if ([value length] > 256 || SPMatches(value, @"[\\x00-\\x1f]")) return nil;
|
|
65
|
+
if ([name containsString:@"url"] || [name isEqual:@"image"]) {
|
|
66
|
+
NSURLComponents *url = [NSURLComponents componentsWithString:value];
|
|
67
|
+
if (!([url.scheme isEqual:@"https"] || [url.scheme isEqual:@"http"]) || !url.host.length || url.user || url.password) return nil;
|
|
68
|
+
url.query = nil; url.fragment = nil; return url.string;
|
|
69
|
+
}
|
|
70
|
+
BOOL reference = [name isEqual:@"id"] || [name hasSuffix:@"id"] || [name isEqual:@"sku"] || [name hasSuffix:@"code"];
|
|
71
|
+
return SPMatches(value, SPPrivateValuePattern) && !(reference && SPMatches(value, @"^[0-9]{7,15}$")) ? nil : value;
|
|
72
|
+
}
|
|
73
|
+
if ([value isKindOfClass:NSDictionary.class] && depth < 2) {
|
|
74
|
+
NSMutableDictionary *result = [NSMutableDictionary dictionary]; NSUInteger count = 0;
|
|
75
|
+
for (NSString *original in [[value allKeys] sortedArrayUsingSelector:@selector(compare:)]) {
|
|
76
|
+
if (count++ >= 32) break;
|
|
77
|
+
NSString *normalized = SPKey(original);
|
|
78
|
+
if (![SPFields() containsObject:normalized] || SPSensitive(normalized)) continue;
|
|
79
|
+
id projected = SPAttribute(value[original], normalized, depth + 1); if (projected) result[original] = projected;
|
|
80
|
+
}
|
|
81
|
+
return result.count ? result : nil;
|
|
82
|
+
}
|
|
83
|
+
return nil;
|
|
84
|
+
}
|
|
85
|
+
/** Applies a depth budget before NSJSONSerialization can recurse into an untrusted body. */
|
|
86
|
+
static BOOL SPSafeJSON(NSString *text) {
|
|
87
|
+
if (![text isKindOfClass:NSString.class] || text.length > 65536 || !SPMatches(text, @"^\\s*[\\[{]")) return NO;
|
|
88
|
+
NSInteger depth = 0; BOOL quoted = NO, escaped = NO;
|
|
89
|
+
for (NSUInteger i = 0; i < text.length; i++) {
|
|
90
|
+
unichar c = [text characterAtIndex:i];
|
|
91
|
+
if (quoted) { if (escaped) escaped = NO; else if (c == '\\') escaped = YES; else if (c == '"') quoted = NO; }
|
|
92
|
+
else if (c == '"') quoted = YES;
|
|
93
|
+
else if (c == '{' || c == '[') { if (++depth > 12) return NO; }
|
|
94
|
+
else if (c == '}' || c == ']') { if (--depth < 0) return NO; }
|
|
95
|
+
}
|
|
96
|
+
return depth == 0 && !quoted;
|
|
97
|
+
}
|
|
98
|
+
/** Applies one encoded byte budget to all retained projection entries. */
|
|
99
|
+
static void SPRetain(NSMutableArray *target, NSDictionary *entry, NSUInteger cap, NSMutableDictionary *state) {
|
|
100
|
+
NSUInteger bytes = [NSJSONSerialization dataWithJSONObject:entry options:NSJSONWritingWithoutEscapingSlashes error:nil].length + 1;
|
|
101
|
+
if (target.count >= cap || [state[@"bytes"] unsignedIntegerValue] + bytes > 11264) { state[@"limited"] = @YES; return; }
|
|
102
|
+
[target addObject:entry]; state[@"bytes"] = @([state[@"bytes"] unsignedIntegerValue] + bytes);
|
|
103
|
+
}
|
|
104
|
+
/** Retains typed scalar context across industries without declaring business semantics. */
|
|
105
|
+
static NSDictionary *SPField(id value, NSString *path, NSString *type) {
|
|
106
|
+
NSMutableDictionary *field = [@{@"path":path,@"type":type} mutableCopy];
|
|
107
|
+
NSString *name = SPKey([path componentsSeparatedByString:@"."].lastObject);
|
|
108
|
+
if ([value isKindOfClass:NSString.class]) {
|
|
109
|
+
if (SPMatches(name, SPTextPattern) && ![name isEqual:@"operationname"] && ![name isEqual:@"typename"]) { field[@"omitted"] = @"text_or_sensitive_value"; return field; }
|
|
110
|
+
if ([[value lowercaseString] hasPrefix:@"http://"] || [[value lowercaseString] hasPrefix:@"https://"]) {
|
|
111
|
+
NSString *url = [SagepilotEventsProjection route:value];
|
|
112
|
+
if (url) field[@"route_fingerprint"] = url;
|
|
113
|
+
field[@"omitted"] = url ? @"url_value" : @"invalid_url";
|
|
114
|
+
return field;
|
|
115
|
+
}
|
|
116
|
+
if (!SPMatches(value, @"^[A-Za-z0-9_./:@+-]{0,256}$") || SPMatches(value, @"[\\x00-\\x1f]") || SPMatches(value, SPPrivateValuePattern)) { field[@"omitted"] = @"text_or_sensitive_value"; return field; }
|
|
117
|
+
} else if ([value isKindOfClass:NSNumber.class] && (!isfinite([value doubleValue]) || fabs([value doubleValue]) > 9007199254740991.0)) { field[@"omitted"] = @"unsafe_number"; return field; }
|
|
118
|
+
field[@"value"] = value; return field;
|
|
119
|
+
}
|
|
120
|
+
/** Walks a bounded structural sample and retains permitted scalar context, excluding sensitive subtrees. */
|
|
121
|
+
static void SPWalk(id value, NSString *path, NSString *shape, NSUInteger depth, NSMutableDictionary *state) {
|
|
122
|
+
NSUInteger nodes = [state[@"nodes"] unsignedIntegerValue] + 1; state[@"nodes"] = @(nodes);
|
|
123
|
+
if (nodes > 512 || depth > 10) { state[@"limited"] = @YES; return; }
|
|
124
|
+
NSMutableArray *structure = state[@"structure"], *candidates = state[@"product_candidates"], *signals = state[@"signals"], *fields = state[@"fields"];
|
|
125
|
+
NSMutableSet *paths = state[@"paths"];
|
|
126
|
+
NSString *type = [value isKindOfClass:NSDictionary.class] ? @"object" : [value isKindOfClass:NSArray.class] ? @"array" : value == NSNull.null ? @"null"
|
|
127
|
+
: CFGetTypeID((__bridge CFTypeRef)value) == CFBooleanGetTypeID() ? @"boolean" : [value isKindOfClass:NSNumber.class] ? @"number" : @"string";
|
|
128
|
+
NSString *typedPath = [shape stringByAppendingFormat:@"|%@", type];
|
|
129
|
+
if (structure.count < 128 && ![paths containsObject:typedPath]) { [paths addObject:typedPath]; SPRetain(structure, @{@"path":shape,@"type":type}, 128, state); }
|
|
130
|
+
else if (structure.count >= 128 && ![paths containsObject:typedPath]) state[@"limited"] = @YES;
|
|
131
|
+
if ([value isKindOfClass:NSDictionary.class]) {
|
|
132
|
+
if (SPCandidate(value)) {
|
|
133
|
+
if ([value count] > 32) state[@"limited"] = @YES;
|
|
134
|
+
if (candidates.count < 20) { id attributes = SPAttribute(value, @"", 0); if (attributes) SPRetain(candidates, @{@"path":path,@"fields":attributes}, 20, state); }
|
|
135
|
+
else state[@"limited"] = @YES;
|
|
136
|
+
}
|
|
137
|
+
NSUInteger count = 0;
|
|
138
|
+
for (NSString *original in [[value allKeys] sortedArrayUsingSelector:@selector(compare:)]) {
|
|
139
|
+
if (count++ >= 64 || [state[@"nodes"] unsignedIntegerValue] >= 512) { state[@"limited"] = @YES; break; }
|
|
140
|
+
NSString *normalized = SPKey(original);
|
|
141
|
+
if (!SPMatches(original, @"^[A-Za-z_][A-Za-z0-9_]{0,63}$") || SPMatches(original, @"[\\x00-\\x1f]")) continue;
|
|
142
|
+
if (SPSensitive(normalized)) continue;
|
|
143
|
+
id child = value[original]; NSString *childPath = [path stringByAppendingFormat:@".%@", original];
|
|
144
|
+
if (SPMatches(normalized, SPTextPattern) && ![normalized isEqual:@"operationname"] && ![normalized isEqual:@"typename"] && ([child isKindOfClass:NSDictionary.class] || [child isKindOfClass:NSArray.class])) continue;
|
|
145
|
+
if (signals.count < 32 && ([normalized isEqual:@"success"] || [normalized isEqual:@"accepted"]) && CFGetTypeID((__bridge CFTypeRef)child) == CFBooleanGetTypeID()) SPRetain(signals, @{@"path":childPath,@"value":child}, 32, state);
|
|
146
|
+
SPWalk(child, childPath, [shape stringByAppendingFormat:@".%@", original], depth + 1, state);
|
|
147
|
+
}
|
|
148
|
+
} else if ([value isKindOfClass:NSArray.class]) {
|
|
149
|
+
for (NSUInteger i = 0; i < MIN(20, [value count]) && [state[@"nodes"] unsignedIntegerValue] < 512; i++) SPWalk(value[i], [path stringByAppendingFormat:@"[%lu]", (unsigned long)i], [shape stringByAppendingString:@"[]"], depth + 1, state);
|
|
150
|
+
if ([value count] > 20) state[@"limited"] = @YES;
|
|
151
|
+
} else SPRetain(fields, SPField(value, path, type), 64, state);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
@implementation SagepilotEventsProjection
|
|
155
|
+
/** Produces the same domain-neutral typed context contract as Android. */
|
|
156
|
+
+ (NSDictionary *)project:(NSString *)body {
|
|
157
|
+
if (!SPSafeJSON(body)) return @{@"omitted":@"size_depth_or_format_limit"};
|
|
158
|
+
id value = [NSJSONSerialization JSONObjectWithData:[body dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
|
|
159
|
+
if (!value) return @{@"omitted":@"invalid_json"};
|
|
160
|
+
NSMutableDictionary *state = [@{@"projection_version":@2,@"structure":[NSMutableArray array],@"fields":[NSMutableArray array],@"product_candidates":[NSMutableArray array],@"signals":[NSMutableArray array],@"paths":[NSMutableSet set],@"nodes":@0,@"bytes":@0,@"limited":@NO} mutableCopy];
|
|
161
|
+
SPWalk(value, @"$", @"$", 0, state); [state removeObjectForKey:@"paths"]; [state removeObjectForKey:@"nodes"]; [state removeObjectForKey:@"bytes"];
|
|
162
|
+
return state;
|
|
163
|
+
}
|
|
164
|
+
/** Fingerprints operation segments and masks probable IDs without retaining raw path text. */
|
|
165
|
+
+ (NSString *)route:(NSString *)input {
|
|
166
|
+
if (![input isKindOfClass:NSString.class] || input.length > 2048) return nil;
|
|
167
|
+
NSURLComponents *url = [NSURLComponents componentsWithString:input];
|
|
168
|
+
if (!([url.scheme isEqual:@"https"] || [url.scheme isEqual:@"http"]) || !url.host.length || url.user || url.password) return nil;
|
|
169
|
+
NSArray *parts = [url.percentEncodedPath componentsSeparatedByString:@"/"]; NSMutableArray *output = [NSMutableArray array];
|
|
170
|
+
for (NSUInteger i = 1; i < MIN(parts.count, 12); i++) {
|
|
171
|
+
NSString *part = [parts[i] stringByRemovingPercentEncoding] ?: @"";
|
|
172
|
+
if (!SPMatches(part, @"[\\x00-\\x1f]") && SPMatches(part, @"^[vV][0-9]{1,3}$")) [output addObject:part];
|
|
173
|
+
else if (!SPMatches(part, @"[\\x00-\\x1f]") && SPMatches(part, @"^[A-Za-z][A-Za-z_-]{0,47}$")) {
|
|
174
|
+
NSData *bytes = [part dataUsingEncoding:NSUTF8StringEncoding]; unsigned char digest[CC_SHA256_DIGEST_LENGTH]; CC_SHA256(bytes.bytes, (CC_LONG)bytes.length, digest);
|
|
175
|
+
NSMutableString *fingerprint = [NSMutableString stringWithString:@":op_"]; for (NSUInteger n = 0; n < 8; n++) [fingerprint appendFormat:@"%02x", digest[n]];
|
|
176
|
+
[output addObject:fingerprint];
|
|
177
|
+
} else [output addObject:part.length ? @":segment" : @""];
|
|
178
|
+
}
|
|
179
|
+
url.path = output.count ? [@"/" stringByAppendingString:[output componentsJoinedByString:@"/"]] : @"";
|
|
180
|
+
url.query = nil; url.fragment = nil; return url.string;
|
|
181
|
+
}
|
|
182
|
+
@end
|
|
183
|
+
|
|
184
|
+
@interface SagepilotEventsStore ()
|
|
185
|
+
@property(nonatomic) NSString *directory;
|
|
186
|
+
@property(nonatomic) NSMutableDictionary *metadata;
|
|
187
|
+
@property(nonatomic) NSMutableArray<NSDictionary *> *entries;
|
|
188
|
+
@property(nonatomic) NSUInteger bytes, dropped, rejected;
|
|
189
|
+
@property(nonatomic) NSString *lease;
|
|
190
|
+
@property(nonatomic) NSMutableSet<NSString *> *leased;
|
|
191
|
+
@end
|
|
192
|
+
|
|
193
|
+
@implementation SagepilotEventsStore
|
|
194
|
+
/** Generates a path-safe digest for one workspace/app scope. */
|
|
195
|
+
+ (NSString *)scopeForWorkspace:(NSString *)workspace channel:(NSString *)channel {
|
|
196
|
+
NSData *data = [[NSString stringWithFormat:@"%@:%@", workspace, channel] dataUsingEncoding:NSUTF8StringEncoding];
|
|
197
|
+
unsigned char digest[CC_SHA256_DIGEST_LENGTH]; CC_SHA256(data.bytes, (CC_LONG)data.length, digest);
|
|
198
|
+
NSMutableString *result = [NSMutableString string]; for (NSUInteger i = 0; i < sizeof(digest); i++) [result appendFormat:@"%02x", digest[i]]; return result;
|
|
199
|
+
}
|
|
200
|
+
/** Recovers bounded atomic files without retaining every product payload in memory. */
|
|
201
|
+
- (instancetype)initWithDirectory:(NSString *)directory scope:(NSString *)scope {
|
|
202
|
+
if (!(self = [super init])) return nil;
|
|
203
|
+
_directory = directory; _entries = [NSMutableArray array]; _leased = [NSMutableSet set];
|
|
204
|
+
SPRequire([NSFileManager.defaultManager createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:nil]);
|
|
205
|
+
@try { _metadata = [SPRead([directory stringByAppendingPathComponent:@"metadata.json"]) mutableCopy]; } @catch(NSException *error) { _metadata = [NSMutableDictionary dictionary]; }
|
|
206
|
+
NSArray *files = [NSFileManager.defaultManager contentsOfDirectoryAtPath:directory error:nil];
|
|
207
|
+
if (![_metadata[@"scope"] isEqual:scope]) {
|
|
208
|
+
for (NSString *file in files) { if ([file hasSuffix:@".event"]) _dropped++; SPRequire([NSFileManager.defaultManager removeItemAtPath:[directory stringByAppendingPathComponent:file] error:nil]); }
|
|
209
|
+
_metadata = [@{@"scope":scope,@"installation_id":NSUUID.UUID.UUIDString.lowercaseString} mutableCopy]; [self saveMetadata]; files = @[];
|
|
210
|
+
}
|
|
211
|
+
NSMutableArray *recovered = [NSMutableArray array];
|
|
212
|
+
for (NSString *file in files) {
|
|
213
|
+
NSString *path = [directory stringByAppendingPathComponent:file];
|
|
214
|
+
if (![file hasSuffix:@".event"]) { if (![file isEqual:@"metadata.json"]) [NSFileManager.defaultManager removeItemAtPath:path error:nil]; continue; }
|
|
215
|
+
@try {
|
|
216
|
+
NSDictionary *event = SPRead(path); SPRequire([event[@"event_id"] isKindOfClass:NSString.class] && [event[@"owner"] isKindOfClass:NSDictionary.class]);
|
|
217
|
+
NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
|
|
218
|
+
[recovered addObject:@{@"id":event[@"event_id"],@"path":path,@"bytes":@([attributes fileSize]),@"owner":SPOwnerKey(event[@"owner"]),@"modified":attributes[NSFileModificationDate] ?: NSDate.distantPast}]; _bytes += [attributes fileSize];
|
|
219
|
+
} @catch(NSException *error) { [NSFileManager.defaultManager removeItemAtPath:path error:nil]; _rejected++; }
|
|
220
|
+
}
|
|
221
|
+
[recovered sortUsingComparator:^NSComparisonResult(NSDictionary *a, NSDictionary *b) { NSComparisonResult result = [a[@"modified"] compare:b[@"modified"]]; return result == NSOrderedSame ? [a[@"id"] compare:b[@"id"]] : result; }];
|
|
222
|
+
[_entries addObjectsFromArray:recovered]; [self trim:0]; return self;
|
|
223
|
+
}
|
|
224
|
+
/** Persists small scope/owner metadata on the same background queue as the journal. */
|
|
225
|
+
- (void)saveMetadata { SPAtomic([self.directory stringByAppendingPathComponent:@"metadata.json"], SPJSON(self.metadata)); }
|
|
226
|
+
/** Returns a binding-scoped pseudonymous installation identity. */
|
|
227
|
+
- (NSString *)installationId { return self.metadata[@"installation_id"]; }
|
|
228
|
+
/** Reuses the original identity epoch after a restart only for the exact same session/customer. */
|
|
229
|
+
- (NSDictionary *)owner:(NSDictionary *)owner {
|
|
230
|
+
if (!owner) return nil;
|
|
231
|
+
NSDictionary *previous = self.metadata[@"owner"];
|
|
232
|
+
if (previous && [SPOwnerKey(previous) isEqual:SPOwnerKey(owner)]) return [previous copy];
|
|
233
|
+
NSMutableDictionary *next = [owner mutableCopy]; next[@"identity_epoch"] = NSUUID.UUID.UUIDString.lowercaseString;
|
|
234
|
+
self.metadata[@"owner"] = next; [self saveMetadata]; return [next copy];
|
|
235
|
+
}
|
|
236
|
+
/** Bounds bytes and record count before committing an incoming record. */
|
|
237
|
+
- (void)trim:(NSUInteger)incoming {
|
|
238
|
+
while (self.entries.count && (self.entries.count + (incoming ? 1 : 0) > SPMaxRecords || self.bytes + incoming > SPMaxBytes)) {
|
|
239
|
+
NSDictionary *entry = self.entries.firstObject; SPRequire([NSFileManager.defaultManager removeItemAtPath:entry[@"path"] error:nil]);
|
|
240
|
+
self.bytes -= [entry[@"bytes"] unsignedIntegerValue]; [self.entries removeObjectAtIndex:0]; self.dropped++;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
/** Atomically commits only sanitized records; oversize output becomes an explicit rejected counter. */
|
|
244
|
+
- (void)append:(NSDictionary *)event {
|
|
245
|
+
NSData *data = SPJSON(event); if (data.length > SPEventBytes) { self.rejected++; return; }
|
|
246
|
+
NSString *identifier = event[@"event_id"]; SPRequire([identifier isKindOfClass:NSString.class] && SPMatches(identifier, @"^[A-Za-z0-9-]{1,100}$"));
|
|
247
|
+
NSString *path = [self.directory stringByAppendingPathComponent:[identifier stringByAppendingString:@".event"]];
|
|
248
|
+
if ([NSFileManager.defaultManager fileExistsAtPath:path]) return;
|
|
249
|
+
[self trim:data.length]; SPAtomic(path, data);
|
|
250
|
+
[self.entries addObject:@{@"id":identifier,@"path":path,@"bytes":@(data.length),@"owner":SPOwnerKey(event[@"owner"])}]; self.bytes += data.length;
|
|
251
|
+
}
|
|
252
|
+
/** Builds and gzip-compresses one bounded same-owner batch on the native worker. */
|
|
253
|
+
- (NSDictionary *)nextBatchForOwner:(NSDictionary *)owner nativeDropped:(NSUInteger)dropped {
|
|
254
|
+
NSMutableArray *events = [NSMutableArray array], *ids = [NSMutableArray array]; NSUInteger size = 64;
|
|
255
|
+
for (NSDictionary *entry in self.entries) {
|
|
256
|
+
if (![entry[@"owner"] isEqual:SPOwnerKey(owner)]) continue;
|
|
257
|
+
if (events.count >= 100 || size + [entry[@"bytes"] unsignedIntegerValue] > SPBatchBytes - 1024) break;
|
|
258
|
+
[events addObject:SPRead(entry[@"path"])]; [ids addObject:entry[@"id"]]; size += [entry[@"bytes"] unsignedIntegerValue] + 1;
|
|
259
|
+
}
|
|
260
|
+
if (!events.count) return nil;
|
|
261
|
+
NSData *body = SPJSON(@{@"schema_version":@1,@"observations":events,@"capture_gaps":@{@"quota_evicted":@(self.dropped),@"rejected_payloads":@(self.rejected),@"collector_dropped":@(dropped)}});
|
|
262
|
+
z_stream stream = {0}; SPRequire(deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) == Z_OK);
|
|
263
|
+
NSMutableData *gzip = [NSMutableData dataWithLength:deflateBound(&stream, (uLong)body.length)];
|
|
264
|
+
stream.next_in = (Bytef *)body.bytes; stream.avail_in = (uInt)body.length; stream.next_out = gzip.mutableBytes; stream.avail_out = (uInt)gzip.length;
|
|
265
|
+
int status = deflate(&stream, Z_FINISH); NSUInteger length = stream.total_out; deflateEnd(&stream); SPRequire(status == Z_STREAM_END); gzip.length = length;
|
|
266
|
+
self.lease = NSUUID.UUID.UUIDString; self.leased = [NSMutableSet setWithArray:ids];
|
|
267
|
+
return @{@"lease":self.lease,@"event_ids":ids,@"gzip":gzip};
|
|
268
|
+
}
|
|
269
|
+
/** Deletes only files named by explicit terminal receipts for the currently leased batch. */
|
|
270
|
+
- (void)acknowledge:(NSString *)lease ids:(NSArray<NSString *> *)ids {
|
|
271
|
+
if (![lease isEqual:self.lease]) return;
|
|
272
|
+
for (NSString *identifier in ids) {
|
|
273
|
+
if (![self.leased containsObject:identifier]) continue;
|
|
274
|
+
NSUInteger index = [self.entries indexOfObjectPassingTest:^BOOL(NSDictionary *entry, NSUInteger position, BOOL *stop) { return [entry[@"id"] isEqual:identifier]; }];
|
|
275
|
+
if (index == NSNotFound) continue;
|
|
276
|
+
NSDictionary *entry = self.entries[index]; SPRequire([NSFileManager.defaultManager removeItemAtPath:entry[@"path"] error:nil]);
|
|
277
|
+
self.bytes -= [entry[@"bytes"] unsignedIntegerValue]; [self.entries removeObjectAtIndex:index]; [self.leased removeObject:identifier];
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
/** Purges unuploaded data on explicit collection revocation and invalidates all batch leases. */
|
|
281
|
+
- (void)clear {
|
|
282
|
+
for (NSDictionary *entry in self.entries) SPRequire([NSFileManager.defaultManager removeItemAtPath:entry[@"path"] error:nil]);
|
|
283
|
+
[self.entries removeAllObjects]; self.bytes = 0; [self.leased removeAllObjects]; self.lease = nil;
|
|
284
|
+
[self.metadata removeObjectForKey:@"owner"]; [self saveMetadata];
|
|
285
|
+
}
|
|
286
|
+
/** Counts omitted unsafe/unsupported network bodies without retaining them. */
|
|
287
|
+
- (void)reject { self.rejected++; }
|
|
288
|
+
/** Reports finite resource usage without bridging raw observations to the application. */
|
|
289
|
+
- (NSDictionary *)diagnostics { return @{@"pending_records":@(self.entries.count),@"pending_bytes":@(self.bytes),@"dropped_records":@(self.dropped),@"rejected_payloads":@(self.rejected)}; }
|
|
290
|
+
@end
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
#import <Foundation/Foundation.h>
|
|
2
|
+
|
|
3
|
+
/** Bounded native HTTP, independent of the journal's serial queue. */
|
|
4
|
+
@interface SagepilotEventsHTTP : NSObject <NSURLSessionDataDelegate>
|
|
5
|
+
- (void)post:(NSString *)endpoint headers:(NSDictionary<NSString *, NSString *> *)headers body:(NSData *)body completion:(void (^)(NSDictionary *, NSError *))completion;
|
|
6
|
+
- (void)cancel;
|
|
7
|
+
- (void)invalidate;
|
|
8
|
+
@end
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
#import "SagepilotEventsHTTP.h"
|
|
2
|
+
|
|
3
|
+
@interface SagepilotEventsHTTP ()
|
|
4
|
+
@property(nonatomic, strong) NSURLSession *session;
|
|
5
|
+
@property(nonatomic, strong) NSURLSessionDataTask *task;
|
|
6
|
+
@property(nonatomic, strong) NSMutableData *response;
|
|
7
|
+
@property(nonatomic, copy) void (^completion)(NSDictionary *, NSError *);
|
|
8
|
+
@property(nonatomic) NSInteger status;
|
|
9
|
+
@property(nonatomic) BOOL oversized;
|
|
10
|
+
@end
|
|
11
|
+
|
|
12
|
+
/** Returns a generic transport error without including tokens, URLs or response bodies. */
|
|
13
|
+
static NSError *SPHTTPError(NSInteger code) { return [NSError errorWithDomain:@"SagepilotAppEventsHTTP" code:code userInfo:@{NSLocalizedDescriptionKey:@"App-event batch admission failed"}]; }
|
|
14
|
+
|
|
15
|
+
@implementation SagepilotEventsHTTP
|
|
16
|
+
/** Reuses one ephemeral connection pool with bounded request/resource timeouts and no cookie storage. */
|
|
17
|
+
- (instancetype)init {
|
|
18
|
+
if (!(self = [super init])) return nil;
|
|
19
|
+
NSURLSessionConfiguration *config = NSURLSessionConfiguration.ephemeralSessionConfiguration;
|
|
20
|
+
config.timeoutIntervalForRequest = 15; config.timeoutIntervalForResource = 15; config.HTTPMaximumConnectionsPerHost = 1;
|
|
21
|
+
config.HTTPCookieStorage = nil; config.URLCache = nil; config.HTTPShouldSetCookies = NO;
|
|
22
|
+
NSOperationQueue *callbacks = [NSOperationQueue new]; callbacks.maxConcurrentOperationCount = 1; callbacks.qualityOfService = NSQualityOfServiceUtility;
|
|
23
|
+
_session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:callbacks]; return self;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Uploads already-compressed bytes without crossing the JS bridge or blocking the journal queue. */
|
|
27
|
+
- (void)post:(NSString *)endpoint headers:(NSDictionary<NSString *,NSString *> *)headers body:(NSData *)body completion:(void (^)(NSDictionary *,NSError *))completion {
|
|
28
|
+
NSURL *url = [NSURL URLWithString:endpoint];
|
|
29
|
+
BOOL secure = [url.scheme isEqual:@"https"], local = [url.scheme isEqual:@"http"] && [@[@"localhost",@"127.0.0.1",@"::1"] containsObject:url.host];
|
|
30
|
+
if ((!secure && !local) || url.user || url.password) { completion(nil, SPHTTPError(-1)); return; }
|
|
31
|
+
@synchronized(self) {
|
|
32
|
+
if (self.task || !self.session) { completion(nil, SPHTTPError(-2)); return; }
|
|
33
|
+
self.response = [NSMutableData data]; self.status = 0; self.oversized = NO; self.completion = completion;
|
|
34
|
+
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
|
|
35
|
+
request.HTTPMethod = @"POST"; request.allHTTPHeaderFields = headers; request.HTTPBody = body;
|
|
36
|
+
self.task = [self.session dataTaskWithRequest:request]; [self.task resume];
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Refuses redirects so a bearer token can never be forwarded to another origin. */
|
|
41
|
+
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler { completionHandler(nil); }
|
|
42
|
+
|
|
43
|
+
/** Rejects announced oversized receipts before buffering any response data. */
|
|
44
|
+
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
|
|
45
|
+
self.status = [(NSHTTPURLResponse *)response statusCode]; self.oversized = response.expectedContentLength > 65536;
|
|
46
|
+
completionHandler(self.oversized ? NSURLSessionResponseCancel : NSURLSessionResponseAllow);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Applies the same byte cap even when content length is absent or inaccurate. */
|
|
50
|
+
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveData:(NSData *)data {
|
|
51
|
+
if (self.response.length + data.length > 65536) { self.oversized = YES; [task cancel]; return; }
|
|
52
|
+
[self.response appendData:data];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Completes one bounded receipt and releases the request's in-memory credentials/body. */
|
|
56
|
+
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
|
|
57
|
+
void (^completion)(NSDictionary *, NSError *); id receipt = nil; NSError *failure = error;
|
|
58
|
+
@synchronized(self) {
|
|
59
|
+
if (self.oversized || self.status < 200 || self.status >= 300) failure = SPHTTPError(self.status ?: -3);
|
|
60
|
+
if (!failure) {
|
|
61
|
+
@try { receipt = [NSJSONSerialization JSONObjectWithData:self.response options:0 error:nil]; }
|
|
62
|
+
@catch(NSException *exception) { receipt = nil; }
|
|
63
|
+
if (![receipt isKindOfClass:NSDictionary.class]) failure = SPHTTPError(-4);
|
|
64
|
+
}
|
|
65
|
+
completion = self.completion; self.completion = nil; self.task = nil; self.response = nil;
|
|
66
|
+
}
|
|
67
|
+
if (completion) completion(failure ? nil : receipt, failure);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Cancels an old owner's in-flight request before another identity is activated. */
|
|
71
|
+
- (void)cancel { @synchronized(self) { [self.task cancel]; } }
|
|
72
|
+
/** Releases the NSURLSession/delegate retention cycle when collection or the React bridge stops. */
|
|
73
|
+
- (void)invalidate { @synchronized(self) { [self.task cancel]; [self.session invalidateAndCancel]; self.session = nil; } }
|
|
74
|
+
@end
|