@surbee/cipher 0.1.0

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/src/cipher.ts ADDED
@@ -0,0 +1,225 @@
1
+ /**
2
+ * Cipher - AI-powered survey response validation
3
+ *
4
+ * Main class for validating survey responses through Surbee's
5
+ * secure validation engine.
6
+ *
7
+ * ```typescript
8
+ * import { Cipher } from '@surbee/cipher';
9
+ *
10
+ * const cipher = new Cipher({ apiKey: 'cipher_sk_...' });
11
+ * const result = await cipher.validate(input);
12
+ * ```
13
+ */
14
+
15
+ import type {
16
+ CipherConfig,
17
+ CipherTier,
18
+ ValidationInput,
19
+ ValidationResult,
20
+ BatchValidationInput,
21
+ BatchValidationResult,
22
+ CipherError,
23
+ CipherErrorCode,
24
+ } from './types';
25
+
26
+ /**
27
+ * Default configuration
28
+ */
29
+ const DEFAULT_CONFIG = {
30
+ tier: 3 as CipherTier,
31
+ thresholds: {
32
+ fail: 0.4,
33
+ review: 0.7,
34
+ },
35
+ debug: false,
36
+ endpoint: 'https://api.surbee.com/v1/cipher',
37
+ };
38
+
39
+ /**
40
+ * Tier information (public-facing, no implementation details)
41
+ */
42
+ const TIER_INFO: Record<CipherTier, { name: string; description: string; checksCount: number }> = {
43
+ 1: {
44
+ name: 'Basic',
45
+ description: 'Essential fraud detection with behavioral heuristics',
46
+ checksCount: 6,
47
+ },
48
+ 2: {
49
+ name: 'Standard',
50
+ description: 'Adds device fingerprinting and automation detection',
51
+ checksCount: 15,
52
+ },
53
+ 3: {
54
+ name: 'Enhanced',
55
+ description: 'Adds AI-powered content quality analysis',
56
+ checksCount: 22,
57
+ },
58
+ 4: {
59
+ name: 'Advanced',
60
+ description: 'Full behavioral analysis with network validation',
61
+ checksCount: 30,
62
+ },
63
+ 5: {
64
+ name: 'Maximum',
65
+ description: 'All 43 checks with cross-respondent fraud detection',
66
+ checksCount: 43,
67
+ },
68
+ };
69
+
70
+ /**
71
+ * Cipher SDK
72
+ */
73
+ export class Cipher {
74
+ private config: Required<Omit<CipherConfig, 'endpoint'>> & { endpoint: string };
75
+
76
+ constructor(config: CipherConfig) {
77
+ if (!config.apiKey) {
78
+ throw new Error('API key is required. Get one from Settings > API Keys in your Surbee dashboard.');
79
+ }
80
+
81
+ if (!config.apiKey.startsWith('cipher_sk_') && !config.apiKey.startsWith('cipher_pk_')) {
82
+ throw new Error('Invalid API key format. Keys should start with cipher_sk_ or cipher_pk_');
83
+ }
84
+
85
+ this.config = {
86
+ apiKey: config.apiKey,
87
+ tier: config.tier ?? DEFAULT_CONFIG.tier,
88
+ thresholds: {
89
+ fail: config.thresholds?.fail ?? DEFAULT_CONFIG.thresholds.fail,
90
+ review: config.thresholds?.review ?? DEFAULT_CONFIG.thresholds.review,
91
+ },
92
+ debug: config.debug ?? DEFAULT_CONFIG.debug,
93
+ endpoint: config.endpoint ?? DEFAULT_CONFIG.endpoint,
94
+ };
95
+ }
96
+
97
+ /**
98
+ * Validate a single response
99
+ */
100
+ async validate(input: ValidationInput): Promise<ValidationResult> {
101
+ const response = await this.request('/validate', {
102
+ tier: this.config.tier,
103
+ thresholds: this.config.thresholds,
104
+ input,
105
+ });
106
+
107
+ return response as ValidationResult;
108
+ }
109
+
110
+ /**
111
+ * Validate multiple responses in batch
112
+ */
113
+ async validateBatch(input: BatchValidationInput): Promise<BatchValidationResult> {
114
+ const response = await this.request('/validate/batch', {
115
+ tier: this.config.tier,
116
+ thresholds: this.config.thresholds,
117
+ submissions: input.submissions,
118
+ crossAnalysis: input.crossAnalysis ?? (this.config.tier === 5),
119
+ });
120
+
121
+ return response as BatchValidationResult;
122
+ }
123
+
124
+ /**
125
+ * Get tier information
126
+ */
127
+ getTierInfo(tier?: CipherTier) {
128
+ const t = tier ?? this.config.tier;
129
+ return TIER_INFO[t];
130
+ }
131
+
132
+ /**
133
+ * Get all available tiers
134
+ */
135
+ getAllTiers() {
136
+ return Object.entries(TIER_INFO).map(([tier, info]) => ({
137
+ tier: Number(tier) as CipherTier,
138
+ ...info,
139
+ }));
140
+ }
141
+
142
+ /**
143
+ * Check API key validity and credits
144
+ */
145
+ async checkStatus(): Promise<{
146
+ valid: boolean;
147
+ credits: number;
148
+ tier: CipherTier;
149
+ rateLimit: { remaining: number; resetAt: number };
150
+ }> {
151
+ const response = await this.request('/status', {});
152
+ return response as any;
153
+ }
154
+
155
+ /**
156
+ * Make API request to Surbee
157
+ */
158
+ private async request(path: string, body: Record<string, unknown>): Promise<unknown> {
159
+ const url = `${this.config.endpoint}${path}`;
160
+
161
+ if (this.config.debug) {
162
+ console.log(`[Cipher] POST ${url}`);
163
+ }
164
+
165
+ try {
166
+ const response = await fetch(url, {
167
+ method: 'POST',
168
+ headers: {
169
+ 'Content-Type': 'application/json',
170
+ 'Authorization': `Bearer ${this.config.apiKey}`,
171
+ 'X-Cipher-SDK': '0.1.0',
172
+ },
173
+ body: JSON.stringify(body),
174
+ });
175
+
176
+ if (!response.ok) {
177
+ const errorData = await response.json().catch(() => ({})) as Record<string, unknown>;
178
+ throw this.createError(response.status, errorData);
179
+ }
180
+
181
+ return response.json();
182
+ } catch (error: unknown) {
183
+ if (error && typeof error === 'object' && 'code' in error) {
184
+ throw error;
185
+ }
186
+ throw this.createError(0, { message: error instanceof Error ? error.message : 'Unknown error' });
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Create a typed error
192
+ */
193
+ private createError(status: number, data: Record<string, unknown>): CipherError {
194
+ let code: CipherErrorCode;
195
+ let message: string;
196
+
197
+ switch (status) {
198
+ case 401:
199
+ code = 'INVALID_API_KEY';
200
+ message = 'Invalid API key. Check your key in Settings > API Keys.';
201
+ break;
202
+ case 402:
203
+ code = 'INSUFFICIENT_CREDITS';
204
+ message = 'Insufficient credits. Add more credits in your Surbee dashboard.';
205
+ break;
206
+ case 429:
207
+ code = 'RATE_LIMITED';
208
+ message = 'Rate limited. Please slow down your requests.';
209
+ break;
210
+ case 400:
211
+ code = 'INVALID_INPUT';
212
+ message = (data.message as string) || 'Invalid input data.';
213
+ break;
214
+ case 403:
215
+ code = 'TIER_NOT_AVAILABLE';
216
+ message = 'This tier is not available on your plan. Upgrade to access higher tiers.';
217
+ break;
218
+ default:
219
+ code = status === 0 ? 'NETWORK_ERROR' : 'SERVER_ERROR';
220
+ message = (data.message as string) || 'An error occurred.';
221
+ }
222
+
223
+ return { code, message, details: data };
224
+ }
225
+ }
package/src/index.ts ADDED
@@ -0,0 +1,75 @@
1
+ /**
2
+ * @surbee/cipher - AI-powered survey response validation SDK
3
+ *
4
+ * Detect fraudulent survey responses with Surbee's secure validation engine.
5
+ * All processing happens server-side - no algorithms or models are exposed.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import { Cipher } from '@surbee/cipher';
10
+ *
11
+ * // Initialize with your API key from Settings > API Keys
12
+ * const cipher = new Cipher({
13
+ * apiKey: 'cipher_sk_...',
14
+ * tier: 4, // 1-5, higher = more checks
15
+ * });
16
+ *
17
+ * // Validate a response
18
+ * const result = await cipher.validate({
19
+ * responses: [
20
+ * { question: 'What do you think?', answer: 'Great product!' }
21
+ * ],
22
+ * behavioralMetrics: tracker.getMetrics(),
23
+ * deviceInfo: tracker.getDeviceInfo(),
24
+ * });
25
+ *
26
+ * console.log(result.score); // 0.92
27
+ * console.log(result.recommendation); // 'keep' | 'review' | 'discard'
28
+ * ```
29
+ *
30
+ * @packageDocumentation
31
+ */
32
+
33
+ // Main class
34
+ export { Cipher } from './cipher';
35
+
36
+ // Types (only what developers need)
37
+ export type {
38
+ // Config
39
+ CipherConfig,
40
+ CipherTier,
41
+
42
+ // Input types
43
+ ValidationInput,
44
+ ResponseInput,
45
+ BehavioralMetrics,
46
+ DeviceInfo,
47
+ SurveyContext,
48
+
49
+ // Output types
50
+ ValidationResult,
51
+ ValidationSummary,
52
+ ValidationMeta,
53
+ CheckResult,
54
+ CheckId,
55
+
56
+ // Batch types
57
+ BatchValidationInput,
58
+ BatchValidationResult,
59
+ FraudIndicators,
60
+
61
+ // Error types
62
+ CipherError,
63
+ CipherErrorCode,
64
+
65
+ // Metric types (for building custom trackers)
66
+ MouseMovement,
67
+ MouseClick,
68
+ KeystrokeEvent,
69
+ ScrollEvent,
70
+ FocusEvent,
71
+ HoverEvent,
72
+ } from './types';
73
+
74
+ // Version
75
+ export const VERSION = '0.1.0';