forked from Adamantine-guild/guildpass-integrations
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypes.ts
More file actions
526 lines (464 loc) · 16.4 KB
/
Copy pathtypes.ts
File metadata and controls
526 lines (464 loc) · 16.4 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
/**
* This file was auto-generated from the OpenAPI schema.
* DO NOT EDIT THIS FILE DIRECTLY.
* To update these types, edit test/fixtures/openapi.json and run:
* npm run sync-types
*/
import { z } from 'zod';
import { ApiError } from './errors'
export type Role = 'member' | 'moderator' | 'admin'
export const RoleSchema = z.enum(['member', 'moderator', 'admin'])
export type MembershipTier = 'free' | 'standard' | 'pro'
export const MembershipTierSchema = z.enum(['free', 'standard', 'pro'])
export const WebhookEventStatusSchema = z.enum(['success', 'failed', 'pending'])
export const WebhookEventTypeSchema = z.enum(['membership.created', 'membership.renewed', 'membership.expired', 'tier.upgraded', 'policy.updated'])
export const WebhookPayloadSummarySchema = z.object({
network: z.string().optional(),
txHash: z.string().optional(),
tier: z.string().optional(),
reason: z.string().optional(),
})
export const WebhookEventLogSchema = z.object({
id: z.string(),
eventType: WebhookEventTypeSchema,
status: WebhookEventStatusSchema,
timestamp: z.string(),
affectedIdentifier: z.string(),
payloadSummary: WebhookPayloadSummarySchema,
/** Raw event payload for detail inspection (optional — added by the replay/debug tool). */
fullPayload: z.record(z.unknown()).optional(),
/** True when this entry was injected via the replay/debug tool rather than ingested from a real webhook. */
isReplay: z.boolean().optional(),
})
export interface Community {
id: string
name: string
description?: string
tiers: MembershipTier[]
}
export const CommunitySchema = z.object({
id: z.string(),
name: z.string(),
description: z.string().optional(),
tiers: z.array(MembershipTierSchema),
})
export interface Membership {
address: string
tier: MembershipTier
active: boolean
expiresAt?: string
}
export const MembershipSchema = z.object({
address: z.string(),
tier: MembershipTierSchema,
active: z.boolean(),
expiresAt: z.string().optional(),
})
export interface MemberProfile {
address: string
displayName?: string
bio?: string
badges: string[]
}
export const MemberProfileSchema = z.object({
address: z.string(),
displayName: z.string().optional(),
bio: z.string().optional(),
badges: z.array(z.string()),
})
export interface Session {
address?: string
roles: Role[]
membership?: Membership
community?: Community
badges?: string[]
}
export const SessionSchema = z.object({
address: z.string().optional(),
roles: z.array(RoleSchema),
membership: MembershipSchema.optional(),
community: CommunitySchema.optional(),
badges: z.array(z.string()).optional(),
})
export interface ResourceContentBlock {
type: string
body?: string
url?: string
title?: string
level?: string
}
export const ResourceContentBlockSchema = z.object({
type: z.string(),
body: z.string().optional(),
url: z.string().optional(),
title: z.string().optional(),
level: z.string().optional(),
})
export interface Resource {
id: string
title: string
description?: string
minTier?: MembershipTier
roles?: Role[]
content?: ResourceContentBlock[]
}
export type ResourceLookupResult =
| { status: 'found'; data: Resource; source: 'direct' | 'fallback' }
| { status: 'not_found' }
| { status: 'error'; error: ApiError }
export const ResourceSchema = z.object({
id: z.string(),
title: z.string(),
description: z.string().optional(),
minTier: MembershipTierSchema.optional(),
roles: z.array(RoleSchema).optional(),
content: z.array(ResourceContentBlockSchema).optional(),
})
export type AccessRule =
| { type: 'tier'; minTier: MembershipTier }
| { type: 'role'; role: Role }
| { type: 'badge'; badge: string }
| { type: 'and'; rules: AccessRule[] }
| { type: 'or'; rules: AccessRule[] }
export const AccessRuleSchema: z.ZodType<AccessRule> = z.lazy(() =>
z.union([
z.object({ type: z.enum(['tier']), minTier: MembershipTierSchema }),
z.object({ type: z.enum(['role']), role: RoleSchema }),
z.object({ type: z.enum(['badge']), badge: z.string() }),
z.object({ type: z.enum(['and']), rules: z.array(AccessRuleSchema) }),
z.object({ type: z.enum(['or']), rules: z.array(AccessRuleSchema) }),
]),
)
export interface AccessPolicy {
resourceId: string
minTier?: MembershipTier
roles?: Role[]
rule?: AccessRule
}
export const AccessPolicySchema = z.object({
resourceId: z.string(),
minTier: MembershipTierSchema.optional(),
roles: z.array(RoleSchema).optional(),
rule: AccessRuleSchema.optional(),
})
export interface MemberRow {
address: string
roles: Role[]
tier: MembershipTier
active: boolean
}
export const MemberRowSchema = z.object({
address: z.string(),
roles: z.array(RoleSchema),
tier: MembershipTierSchema,
active: z.boolean(),
})
export const ApiErrorBodySchema = z.object({
code: z.string().optional(),
error: z.string().optional(),
message: z.string().optional(),
details: z.record(z.unknown()).optional(),
})
export interface SiweAuthSession {
isAuthenticated: true
/** Short-lived access token (typically 1 h). Attach as `Authorization: Bearer` on admin mutations. */
token: string
address: string
/** ISO 8601 expiry of the access token. */
expiresAt: string
/**
* Opaque longer-lived refresh credential (typically 7 d).
* Must be treated as a secret — never log or expose it.
* Optional so that existing persisted sessions without a refresh token
* are still valid (they will just not support silent renewal).
*/
refreshToken?: string
/** ISO 8601 expiry of the refresh token. Absence means no refresh is available. */
refreshExpiresAt?: string
}
export const SiweAuthSessionSchema = z.object({
isAuthenticated: z.literal(true),
token: z.string(),
address: z.string(),
expiresAt: z.string(),
refreshToken: z.string().optional(),
refreshExpiresAt: z.string().optional(),
})
export const WalletVerificationSchema = z.object({
verified: z.boolean(),
method: z.string().optional(),
checkedAt: z.string(),
})
export type WebhookEventStatus = 'success' | 'failed' | 'pending';
export type WebhookEventType =
| 'membership.created'
| 'membership.renewed'
| 'membership.expired'
| 'tier.upgraded'
| 'policy.updated';
export type WebhookEventUnsubscribe = () => void
export interface WebhookEventLog {
id: string;
eventType: WebhookEventType;
status: WebhookEventStatus;
timestamp: string;
affectedIdentifier: string; // Wallet address or Resource ID
payloadSummary: {
network?: string;
txHash?: string;
tier?: string;
reason?: string;
};
/** Raw event payload for detail inspection (optional — added by the replay/debug tool). */
fullPayload?: Record<string, unknown>;
/** True when this entry was injected via the replay/debug tool rather than ingested from a real webhook. */
isReplay?: boolean;
}
export interface WalletVerification {
verified: boolean
method?: string
checkedAt: string
}
export interface ApiErrorBody {
code?: string
error?: string
message?: string
details?: Record<string, unknown>
}
// ── Analytics Types ──────────────────────────────────────────────────────────
// NOTE: The analytics endpoint is PROVISIONAL. The path /v1/admin/analytics
// has not yet been confirmed by guildpass-core. This contract is documented
// here so the frontend and backend can align. Tracked in issue #157.
/**
* A single data point in the member growth time series.
*/
export interface MemberGrowthDataPoint {
/** ISO 8601 date (YYYY-MM-DD) representing the start of the interval. */
date: string
/** Number of new members who joined during this interval. */
newMembers: number
/** Cumulative total member count at end of interval. */
totalMembers: number
}
export const MemberGrowthDataPointSchema = z.object({
date: z.string(),
newMembers: z.number().int().nonnegative(),
totalMembers: z.number().int().nonnegative(),
})
/**
* Access attempt counts for a single gated resource.
*/
export interface ResourceAccessCount {
resourceId: string
resourceTitle: string
/** Total number of access attempts for this resource. */
accessCount: number
/** Number of denied access attempts (insufficient tier/role). */
deniedCount: number
}
export const ResourceAccessCountSchema = z.object({
resourceId: z.string(),
resourceTitle: z.string(),
accessCount: z.number().int().nonnegative(),
deniedCount: z.number().int().nonnegative(),
})
/**
* Top-level analytics summary for the admin dashboard.
*
* @provisional Endpoint `/v1/admin/analytics` is not yet implemented in
* guildpass-core. This type definition captures the proposed contract so
* frontend and backend can align. The mock implementation uses seeded data;
* the live implementation will use this schema once the backend ships.
*/
export interface AnalyticsSummary {
/** Total community member count. */
totalMembers: number
/** Count of members with an active membership. */
activeMembers: number
/** Member growth time series (most recent 30 days, daily intervals). */
memberGrowth: MemberGrowthDataPoint[]
/** Per-resource access and denial counts. */
resourceAccess: ResourceAccessCount[]
/** ISO timestamp when this summary was generated. */
generatedAt: string
}
export const AnalyticsSummarySchema = z.object({
totalMembers: z.number().int().nonnegative(),
activeMembers: z.number().int().nonnegative(),
memberGrowth: z.array(MemberGrowthDataPointSchema),
resourceAccess: z.array(ResourceAccessCountSchema),
generatedAt: z.string(),
})
// ── Access Decision (cached per wallet + resource) ───────────────────────────
/**
* Result of an access check for a specific resource.
* This is the value stored in the route-level access cache.
* Only safe display metadata is included — never sensitive tokens.
*/
export interface AccessDecision {
/** Whether access is granted */
allowed: boolean
/** Human-readable reason for the decision (safe for display) */
reason: string
/** ISO timestamp of when the check was performed */
checkedAt: string
}
// ── Client-side State Types ──────────────────────────────────────────────────
/**
* Distinct states of the admin authentication session.
*
* - disconnected — no wallet connected
* - connected — wallet connected, but SIWE sign-in not yet performed
* - authenticating — SIWE signing flow is in-flight
* - authenticated — valid, non-expired session token is held
* - expired — a session was held but the token has since expired (or
* the backend rejected it with 401); re-auth is required
*/
export type AdminSessionStatus =
| 'disconnected'
| 'connected'
| 'authenticating'
| 'authenticated'
| 'expired'
/**
* Union of authenticated / unauthenticated states for the SIWE context.
*/
export type SiweAuthState =
| SiweAuthSession
| { isAuthenticated: false }
// ── Backend raw types (guildpass-core response shapes) ───────────────────────
// These are the shapes returned by /v1/* endpoints. The live API client maps
// them into the frontend types above. Fields are optional because backend
// versions may use snake_case or camelCase, and this mapping handles both.
export interface BackendMember {
address?: string
wallet_address?: string
tier?: MembershipTier
membership_tier?: MembershipTier
active?: boolean
is_active?: boolean
expiresAt?: string
expires_at?: string
roles?: Role[]
// Profile fields (returned by /v1/members/:address/profile)
displayName?: string
display_name?: string
username?: string
bio?: string
badges?: string[]
}
export interface BackendResource {
id: string
title?: string
name?: string
description?: string
minTier?: MembershipTier
min_tier?: MembershipTier
roles?: Role[]
content?: ResourceContentBlock[]
}
export interface BackendPolicy {
resourceId?: string
resource_id?: string
minTier?: MembershipTier
min_tier?: MembershipTier
roles?: Role[]
rule?: AccessRule
}
export interface BackendSession {
address?: string
wallet_address?: string
roles?: Role[]
membership?: Partial<BackendMember>
community?: {
id: string
name: string
description?: string
tiers?: MembershipTier[]
}
}
// ── API Interface ─────────────────────────────────────────────────────────────
/**
* Read-only member and resource queries.
* No SIWE token is required for these operations.
*/
export interface PaginatedMembers {
members: MemberRow[]
nextCursor?: string
}
export interface MemberAccessApi {
// ── Read-only (no auth token required) ──────────────────────────────────
getSession(signal?: AbortSignal): Promise<Session>
getCommunity(signal?: AbortSignal): Promise<Community>
getMembership(address: string, signal?: AbortSignal): Promise<Membership | null>
verifyWallet(address: string, signal?: AbortSignal): Promise<WalletVerification>
getProfile(address: string, signal?: AbortSignal): Promise<MemberProfile | null>
listMembers(params?: { cursor?: string; limit?: number; filter?: string }, signal?: AbortSignal): Promise<MemberRow[] | PaginatedMembers>
listResources(signal?: AbortSignal): Promise<Resource[]>
listPolicies(signal?: AbortSignal): Promise<AccessPolicy[]>
getResource(id: string, signal?: AbortSignal): Promise<ResourceLookupResult>
getPolicy(resourceId: string, signal?: AbortSignal): Promise<AccessPolicy | null>
}
/**
* Authenticated admin queries and mutations.
* These methods require a valid SIWE token context.
*/
export interface AdminAccessApi {
// ── Admin queries & mutations (require a valid SIWE token context) ────────
listWebhookEvents(signal?: AbortSignal): Promise<WebhookEventLog[]>
/**
* Subscribe to the admin webhook event stream.
*
* @provisional Live mode attempts `GET /v1/admin/events/stream` as an
* SSE-compatible stream. If setup fails, the caller should fall back to
* `listWebhookEvents()` polling.
*/
subscribeWebhookEvents(
onEvent: (event: WebhookEventLog) => void,
onError?: (error: unknown) => void,
): WebhookEventUnsubscribe
/**
* Fetch the analytics summary for the admin dashboard.
*
* @provisional Calls `GET /v1/admin/analytics` — endpoint not yet live in
* guildpass-core. Contract tracked in issue #157; pending backend confirmation.
*/
getAnalyticsSummary(signal?: AbortSignal): Promise<AnalyticsSummary>
assignRole(address: string, role: Role): Promise<void>
removeRole(address: string, role: Role): Promise<void>
updatePolicy(policy: AccessPolicy): Promise<void>
}
/**
* SIWE authentication endpoints.
*/
export interface SiweAuthApi {
// ── SIWE authentication endpoints ────────────────────────────────────────
/** Fetch a one-time nonce for the given address to include in the SIWE message. */
getNonce(address: string): Promise<string>
/**
* Submit a signed EIP-4361 message and receive an authenticated session
* token. The backend verifies the signature and returns a short-lived access
* token plus a longer-lived refresh token.
*/
siweVerify(message: string, signature: string): Promise<SiweAuthSession>
/**
* Exchange a valid refresh token for a fresh access token (and a new
* refresh token — token rotation). The caller must immediately persist the
* returned session and discard the old refresh token.
*
* Throws a 401 ApiError when the refresh token is expired or invalid,
* signalling that the user must re-sign with their wallet.
*/
siweRefresh(refreshToken: string): Promise<SiweAuthSession>
/** Invalidate the current server-side session (no-op for stateless JWTs). */
siweLogout(token: string): Promise<void>
verifyWallet(address: string): Promise<WalletVerification>
}
/**
* Composed client-side API contract.
*
* Built from {@link MemberAccessApi}, {@link AdminAccessApi}, and
* {@link SiweAuthApi} so each surface has a single, unambiguous responsibility
* and implementations cannot drift between duplicated declarations.
*/
export type AccessApi = MemberAccessApi & AdminAccessApi & SiweAuthApi