-
-
Notifications
You must be signed in to change notification settings - Fork 425
Expand file tree
/
Copy pathschemas.ts
More file actions
330 lines (295 loc) · 8.69 KB
/
schemas.ts
File metadata and controls
330 lines (295 loc) · 8.69 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
import * as v from 'valibot'
import validateNpmPackageName from 'validate-npm-package-name'
// Validation pattern for npm usernames/org names
// These follow similar rules: lowercase alphanumeric with hyphens, can't start/end with hyphen
const NPM_USERNAME_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/i
// ============================================================================
// Base Schemas
// ============================================================================
/**
* Validates an npm package name using the official npm validation package
* Accepts both new and legacy package name formats
*/
export const PackageNameSchema = v.pipe(
v.string(),
v.nonEmpty('Package name is required'),
v.check(input => {
const result = validateNpmPackageName(input)
return result.validForNewPackages || result.validForOldPackages
}, 'Invalid package name format'),
)
/**
* Validates an npm package name for new packages only
* Stricter than PackageNameSchema - rejects legacy formats (uppercase, etc.)
* @internal
*/
export const NewPackageNameSchema = v.pipe(
v.string(),
v.nonEmpty('Package name is required'),
v.check(input => {
const result = validateNpmPackageName(input)
return result.validForNewPackages === true
}, 'Invalid package name format. New packages must be lowercase and follow npm naming conventions.'),
)
/**
* Validates an npm username
* Must be alphanumeric with hyphens, max 50 chars, can't start/end with hyphen
*/
export const UsernameSchema = v.pipe(
v.string(),
v.nonEmpty('Username is required'),
v.maxLength(50, 'Username is too long'),
v.regex(NPM_USERNAME_RE, 'Invalid username format'),
)
/**
* Validates an npm org name (without the @ prefix)
* Same rules as username
*/
export const OrgNameSchema = v.pipe(
v.string(),
v.nonEmpty('Org name is required'),
v.maxLength(50, 'Org name is too long'),
v.regex(NPM_USERNAME_RE, 'Invalid org name format'),
)
/**
* Validates a scope:team format (e.g., @myorg:developers)
*/
export const ScopeTeamSchema = v.pipe(
v.string(),
v.nonEmpty('Scope:team is required'),
v.maxLength(100, 'Scope:team is too long'),
v.check(input => {
const match = input.match(/^@([^:]+):(.+)$/)
if (!match) return false
const [, scope, team] = match
if (!scope || !NPM_USERNAME_RE.test(scope)) return false
if (!team || !NPM_USERNAME_RE.test(team)) return false
return true
}, 'Invalid scope:team format. Expected @scope:team'),
)
/**
* Validates org roles
* @internal
*/
export const OrgRoleSchema = v.picklist(
['developer', 'admin', 'owner'],
'Invalid role. Must be developer, admin, or owner',
)
/**
* Validates access permissions
* @internal
*/
export const PermissionSchema = v.picklist(
['read-only', 'read-write'],
'Invalid permission. Must be read-only or read-write',
)
/**
* Validates operation types
*/
export const OperationTypeSchema = v.picklist([
'org:add-user',
'org:rm-user',
'org:set-role',
'team:create',
'team:destroy',
'team:add-user',
'team:rm-user',
'access:grant',
'access:revoke',
'owner:add',
'owner:rm',
'package:init',
'package:deprecate',
])
/**
* Validates OTP (6-digit code)
* @internal
*/
export const OtpSchema = v.optional(
v.pipe(v.string(), v.regex(/^\d{6}$/, 'OTP must be a 6-digit code')),
)
/**
* Validates a hex token (like session tokens and operation IDs)
* @internal
*/
export const HexTokenSchema = v.pipe(
v.string(),
v.nonEmpty('Token is required'),
v.regex(/^[a-f0-9]+$/i, 'Invalid token format'),
)
/**
* Validates operation ID (16-char hex)
* @internal
*/
export const OperationIdSchema = v.pipe(
v.string(),
v.nonEmpty('Operation ID is required'),
v.regex(/^[a-f0-9]{16}$/i, 'Invalid operation ID format'),
)
// ============================================================================
// Request Body Schemas
// ============================================================================
/**
* Schema for /connect request body
*/
export const ConnectBodySchema = v.object({
token: HexTokenSchema,
})
/**
* Schema for /execute request body
*/
export const ExecuteBodySchema = v.object({
otp: OtpSchema,
})
/**
* Schema for operation params based on type
* Validates the params object for each operation type
*/
const OperationParamsSchema = v.record(v.string(), v.string())
/**
* Schema for single operation request body
*/
export const CreateOperationBodySchema = v.object({
type: OperationTypeSchema,
params: OperationParamsSchema,
description: v.pipe(v.string(), v.nonEmpty('Description is required'), v.maxLength(500)),
command: v.pipe(v.string(), v.nonEmpty('Command is required'), v.maxLength(1000)),
})
/**
* Schema for batch operation request body
*/
export const BatchOperationsBodySchema = v.array(CreateOperationBodySchema)
// ============================================================================
// Type-specific Operation Params Schemas
// ============================================================================
/** @internal */
export const OrgAddUserParamsSchema = v.object({
org: OrgNameSchema,
user: UsernameSchema,
role: OrgRoleSchema,
})
const OrgRemoveUserParamsSchema = v.object({
org: OrgNameSchema,
user: UsernameSchema,
})
const TeamCreateParamsSchema = v.object({
scopeTeam: ScopeTeamSchema,
})
const TeamDestroyParamsSchema = v.object({
scopeTeam: ScopeTeamSchema,
})
const TeamAddUserParamsSchema = v.object({
scopeTeam: ScopeTeamSchema,
user: UsernameSchema,
})
const TeamRemoveUserParamsSchema = v.object({
scopeTeam: ScopeTeamSchema,
user: UsernameSchema,
})
/** @internal */
export const AccessGrantParamsSchema = v.object({
permission: PermissionSchema,
scopeTeam: ScopeTeamSchema,
pkg: PackageNameSchema,
})
const AccessRevokeParamsSchema = v.object({
scopeTeam: ScopeTeamSchema,
pkg: PackageNameSchema,
})
const OwnerAddParamsSchema = v.object({
user: UsernameSchema,
pkg: PackageNameSchema,
})
const OwnerRemoveParamsSchema = v.object({
user: UsernameSchema,
pkg: PackageNameSchema,
})
/** @internal */
export const PackageInitParamsSchema = v.object({
name: NewPackageNameSchema,
author: v.optional(UsernameSchema),
})
const PackageDeprecateParamsSchema = v.object({
pkg: PackageNameSchema,
message: v.pipe(
v.string(),
v.nonEmpty('Deprecation message is required'),
v.maxLength(500, 'Message is too long'),
),
version: v.optional(v.pipe(v.string(), v.nonEmpty())),
dryRun: v.optional(v.picklist(['true', 'false'], 'dryRun must be "true" or "false"')),
registry: v.optional(v.pipe(v.string(), v.minLength(1, 'Registry URL cannot be empty'))),
})
// ============================================================================
// Helper Functions
// ============================================================================
/**
* Validates operation params based on operation type
* @throws ValiError if validation fails
*/
export function validateOperationParams(
type: v.InferOutput<typeof OperationTypeSchema>,
params: Record<string, string>,
): void {
switch (type) {
case 'org:add-user':
v.parse(OrgAddUserParamsSchema, params)
break
case 'org:rm-user':
v.parse(OrgRemoveUserParamsSchema, params)
break
case 'org:set-role':
v.parse(OrgAddUserParamsSchema, params) // same params as add-user
break
case 'team:create':
v.parse(TeamCreateParamsSchema, params)
break
case 'team:destroy':
v.parse(TeamDestroyParamsSchema, params)
break
case 'team:add-user':
v.parse(TeamAddUserParamsSchema, params)
break
case 'team:rm-user':
v.parse(TeamRemoveUserParamsSchema, params)
break
case 'access:grant':
v.parse(AccessGrantParamsSchema, params)
break
case 'access:revoke':
v.parse(AccessRevokeParamsSchema, params)
break
case 'owner:add':
v.parse(OwnerAddParamsSchema, params)
break
case 'owner:rm':
v.parse(OwnerRemoveParamsSchema, params)
break
case 'package:init':
v.parse(PackageInitParamsSchema, params)
break
case 'package:deprecate':
v.parse(PackageDeprecateParamsSchema, params)
break
}
}
/**
* Safe parse wrapper that returns a formatted error message
*/
export function safeParse<T extends v.GenericSchema>(
schema: T,
input: unknown,
): { success: true; data: v.InferOutput<T> } | { success: false; error: string } {
const result = v.safeParse(schema, input)
if (result.success) {
return { success: true, data: result.output }
}
// Format the first error message
const firstIssue = result.issues[0]
const path = firstIssue?.path?.map(p => p.key).join('.') || ''
const message = firstIssue?.message || 'Validation failed'
return {
success: false,
error: path ? `${path}: ${message}` : message,
}
}