@sylphx/sdk 0.10.7 → 0.11.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/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { SdkBillingPlan, SdkBillingSubscription, BillingCheckoutRequest, BillingCheckoutResponse, BillingPortalRequest, BillingPortalResponse, BillingBalanceResponse, BillingUsageResponse, SdkConsentType, UserConsent as UserConsent$1, AIModel as AIModel$1, GetModelsResponse, GetRateLimitResponse, GetUsageResponse, ReferralLeaderboardEntry, ReferralRewardDefaults as ReferralRewardDefaults$1, WebhookDelivery as WebhookDelivery$1, DeviceApproveRequest, DeviceApproveResponse, DeviceDenyRequest, DeviceDenyResponse, DeviceInitResponse, DeviceInitRequest, DevicePollResponse, LoginRequest as LoginRequest$1, LoginResponse as LoginResponse$1, UserFullProfile as UserFullProfile$1, LogoutInput, PlatformPasswordChangeRequest, PlatformPasswordChangeResponse, PlatformPasswordSetRequest, PlatformPasswordSetResponse, PlatformPasswordStatusResponse, RefreshTokenInput, RefreshTokenResult, PlatformSessionRenameRequest, PlatformSessionRenameResponse, PlatformSessionRevokeAllResponse, PlatformSessionRevokeRequest, PlatformSessionRevokeOtherResponse, PlatformSessionRevokeResponse, PlatformSessionsListResponse, AuthUserDeleteRequest, AuthUserDeleteResponse, AuthUserExportResponse, RegisterRequest as RegisterRequest$1, RegisterResponse as RegisterResponse$1, ResendEmailVerificationRequest as ResendEmailVerificationRequest$1, ResendEmailVerificationResponse as ResendEmailVerificationResponse$1, AuthTokensResponse, TwoFactorVerifyRequest as TwoFactorVerifyRequest$1, OAuthIntrospectResponse, PlatformAuditQueryRequest, PlatformAuditQueryResponse, PlatformRateLimitStatusRequest, PlatformRateLimitStatusResponse, PlatformRateLimitStrategiesListRequest, PlatformRateLimitStrategiesListResponse, PlatformRateLimitStrategyDeleteRequest, PlatformRateLimitStrategyDeleteResponse, PlatformRateLimitStrategyUpsertRequest, PlatformRateLimitStrategyUpsertResponse, File as File$1, UploadId, FileId, TakedownFileRequest, TakedownFileResult, FileVersion, FileVersionId, CreateOrgInput as CreateOrgInput$1, InviteMemberInput as InviteMemberInput$1, OrgSdkRole, OrgInvitation, OrgMember, MembershipInfo, Organization, UpdateOrgInput as UpdateOrgInput$1, UserOrganizationMembership, UserOrganizationsResponse } from '@sylphx/contract';
1
+ export { DEFAULT_MACHINE_SIZE, MACHINE_CONFIGS, MACHINE_MAX_INSTANCES, MACHINE_RESOURCE_REQUIREMENTS, MACHINE_SIZES, MachineConfig, MachineResourceRequirements, MachineTierResources, isMachineSize, parseMachineSize, resolveMachineConfig, resolveMachineMaxInstances, resolveMachineResources, resolveMachineTierResources, toPublicMachineSize } from '@sylphx/contract/compute';
2
+ import { SdkBillingPlan, SdkBillingSubscription, BillingCheckoutRequest, BillingCheckoutResponse, BillingPortalRequest, BillingPortalResponse, BillingBalanceResponse, BillingUsageResponse, SdkConsentType, UserConsent as UserConsent$1, AIModel as AIModel$1, GetModelsResponse, GetRateLimitResponse, GetUsageResponse, ReferralLeaderboardEntry, ReferralRewardDefaults as ReferralRewardDefaults$1, WebhookDelivery as WebhookDelivery$1, OAuthTokenResponse, OAuthTokenErrorResponse, OAuthClientCredentialsResponse, LogoutInput, RefreshTokenInput, RefreshTokenResult, OAuthIntrospectResponse, PlatformPasswordChangeRequest, PlatformPasswordChangeResponse, PlatformPasswordSetRequest, PlatformPasswordSetResponse, PlatformPasswordStatusResponse, PlatformSessionRenameRequest, PlatformSessionRenameResponse, PlatformSessionRevokeAllResponse, PlatformSessionRevokeRequest, PlatformSessionRevokeOtherResponse, PlatformSessionRevokeResponse, PlatformSessionsListResponse, AuthUserDeleteRequest, AuthUserDeleteResponse, AuthUserExportResponse, DeviceApproveRequest, DeviceApproveResponse, DeviceDenyRequest, DeviceDenyResponse, DeviceInitResponse, DeviceInitRequest, DevicePollResponse, LoginRequest as LoginRequest$1, LoginResponse as LoginResponse$1, UserFullProfile as UserFullProfile$1, RegisterRequest as RegisterRequest$1, RegisterResponse as RegisterResponse$1, ResendEmailVerificationRequest as ResendEmailVerificationRequest$1, ResendEmailVerificationResponse as ResendEmailVerificationResponse$1, AuthTokensResponse, TwoFactorVerifyRequest as TwoFactorVerifyRequest$1, PlatformAuditQueryRequest, PlatformAuditQueryResponse, PlatformRateLimitStatusRequest, PlatformRateLimitStatusResponse, PlatformRateLimitStrategiesListRequest, PlatformRateLimitStrategiesListResponse, PlatformRateLimitStrategyDeleteRequest, PlatformRateLimitStrategyDeleteResponse, PlatformRateLimitStrategyUpsertRequest, PlatformRateLimitStrategyUpsertResponse, File as File$1, UploadId, FileId, TakedownFileRequest, TakedownFileResult, FileVersion, FileVersionId, CreateOrgInput as CreateOrgInput$1, InviteMemberInput as InviteMemberInput$1, OrgSdkRole, OrgInvitation, OrgMember, MembershipInfo, Organization, UpdateOrgInput as UpdateOrgInput$1, UserOrganizationMembership, UserOrganizationsResponse, MachineSize } from '@sylphx/contract';
2
3
  export { BillingBalanceResponse as BalanceResponse, BillingCheckoutRequest as CheckoutRequest, BillingCheckoutResponse as CheckoutResponse, FileId, FileVersion, FileVersionId, FileVisibility, Organization, BillingPortalRequest as PortalRequest, BillingPortalResponse as PortalResponse, SignedUrlDisposition, File as StorageFile, UploadId, BillingUsageResponse as UsageResponse } from '@sylphx/contract';
3
4
 
4
5
  /**
@@ -7,19 +8,19 @@ export { BillingBalanceResponse as BalanceResponse, BillingCheckoutRequest as Ch
7
8
  *
8
9
  * Function-bundle download for the Sylphx-internal edge-runtime
9
10
  * orchestrator. Unlike the sibling Platform namespaces this one
10
- * authenticates with a shared `internalToken` (cluster-internal secret)
11
+ * authenticates with a shared `internalToken` (service-internal secret)
11
12
  * rather than a platform-audience JWT, because the caller is another
12
13
  * Sylphx service (the edge-runtime that spawns V8 isolates to invoke
13
14
  * user functions) not an end user. The BaaS runtime
14
15
  * (`apps/runtime/src/server/runtime/routes/functions/admin.ts`)
15
- * owns the raw `@aws-sdk/client-s3` client — Platform callers
16
- * dogfood through this SDK surface and never touch the S3 primitive.
16
+ * owns the object-storage implementation — Platform callers dogfood through
17
+ * this SDK surface and never touch backend storage credentials.
17
18
  *
18
19
  * Phase Σ1 SoC rename: this was previously exported out of `./auth`
19
20
  * as `functions` (re-exported at the package root as `functionsInternal`)
20
21
  * and spoke to `/auth/platform-functions/*`. The server-side surface
21
22
  * moved to `/v1/functions/admin/*` (function bundle admin is a
22
- * cross-cutting BaaS primitive — infrastructure storage — not an auth
23
+ * cross-cutting BaaS primitive — function bundle storage — not an auth
23
24
  * verb); this SDK module nests the admin verbs under
24
25
  * `functions.admin.*` at the package root.
25
26
  */
@@ -39,8 +40,8 @@ interface PlatformFunctionsDownloadBundleResult {
39
40
  * `pk_`/`sk_` pair. The BaaS runtime
40
41
  * (`apps/runtime/src/server/runtime/routes/realtime/admin.ts`)
41
42
  * verifies the token against audience `'platform'`, confirms
42
- * `verifyProjectAccess(userId, projectId)`, and owns the Redis set
43
- * operations.
43
+ * `verifyProjectAccess(userId, projectId)`, and owns the channel
44
+ * registration operations.
44
45
  *
45
46
  * Phase Σ1 SoC rename: this was previously exported out of `./auth`
46
47
  * as `realtime` (re-exported at the package root as `realtimeAdmin`)
@@ -63,7 +64,6 @@ interface PlatformRealtimeChannel {
63
64
  }
64
65
  interface PlatformRealtimeStatusResult {
65
66
  readonly available: boolean;
66
- readonly provider: string;
67
67
  }
68
68
  interface PlatformRealtimeListChannelsResult {
69
69
  readonly channels: readonly PlatformRealtimeChannel[];
@@ -77,10 +77,80 @@ interface PlatformRealtimeDeleteChannelResult {
77
77
  }
78
78
 
79
79
  /**
80
- * Sylphx Connection URL Parser — SDK Self-Contained Copy
80
+ * Database Pricing Configuration (SSOT)
81
+ *
82
+ * All database billing constants centralized here.
83
+ * Used by billing calculations, usage tracking, and cost display.
84
+ *
85
+ * Pricing Strategy:
86
+ * - Self-hosted infra on AX162-R: flat ~$270/month
87
+ * - Competitive pricing with 75-99% margins
88
+ *
89
+ * Customer Prices (updated for self-hosted, 2026-02):
90
+ * - Compute: $0.08/hour (25% below Neon $0.106/hr)
91
+ * - Storage: $0.25/GB-month (29% below Neon $0.35/GB)
92
+ * - Transfer: $0.09/GB (matches Supabase)
93
+ */
94
+ /** Price per compute hour in microdollars ($0.08/hour = 80,000 microdollars) */
95
+ declare const COMPUTE_PRICE_PER_HOUR_MICRODOLLARS = 80000;
96
+ /** Free compute hours per month (platform free tier) */
97
+ declare const FREE_COMPUTE_HOURS = 3;
98
+ /** Price per GB-month in microdollars ($0.25/GB-month = 250,000 microdollars) */
99
+ declare const STORAGE_PRICE_PER_GB_MONTH_MICRODOLLARS = 250000;
100
+ /** Free storage in GB (256 MB) */
101
+ declare const FREE_STORAGE_GB = 0.25;
102
+ /** Price per GB data transfer ($0.09/GB = 90,000 microdollars) */
103
+ declare const TRANSFER_PRICE_PER_GB_MICRODOLLARS = 90000;
104
+ /** KV free storage in GB (256 MB) */
105
+ declare const KV_FREE_STORAGE_GB = 0.25;
106
+ /** Hours per month (AWS/GCP standard for billing) */
107
+ declare const HOURS_PER_MONTH = 730;
108
+
109
+ /**
110
+ * Referrals Configuration (SSOT)
111
+ *
112
+ * Single source of truth for referral system configuration.
113
+ * Used by: referral router, SDK referral endpoints
114
+ */
115
+ /** Default points awarded per successful referral */
116
+ declare const DEFAULT_POINTS_REWARD = 100;
117
+ /** Number of months the referral discount is valid */
118
+ declare const DISCOUNT_DURATION_MONTHS = 3;
119
+ /** Default discount percentage */
120
+ declare const DISCOUNT_PERCENT = 20;
121
+ /** Premium trial days from referral */
122
+ declare const PREMIUM_TRIAL_DAYS = 7;
123
+ /**
124
+ * Generate a cryptographically secure referral code
125
+ *
126
+ * Uses crypto.getRandomValues for uniform random bytes (0-255).
127
+ * Since REFERRAL_CODE_CHARS has exactly 32 characters and 256 / 32 = 8,
128
+ * byte % 32 produces perfectly uniform distribution with zero modulo bias.
129
+ *
130
+ * Entropy: 8 chars * log2(32) = 40 bits (~1.1 trillion possible codes)
131
+ *
132
+ * Format: 8 uppercase alphanumeric characters (excluding ambiguous: 0, O, I, L, 1)
133
+ */
134
+ declare function generateReferralCode(): string;
135
+
136
+ declare function getErrorMessage$1(error: unknown, fallback?: string): string;
137
+ interface ErrorDetails$1 {
138
+ message: string;
139
+ code?: string;
140
+ name?: string;
141
+ stack?: string;
142
+ status?: number;
143
+ cause?: unknown;
144
+ }
145
+ declare function getErrorDetails$1(error: unknown, fallbackMessage?: string): ErrorDetails$1;
146
+
147
+ /**
148
+ * Sylphx Connection URL — Single Source of Truth (ADR-123)
81
149
  *
82
150
  * Implements the canonical connection string format defined in ADR-055 §5.
83
- * This is a self-contained copy for SDK package independence (no app imports).
151
+ * This module is the SDK-owned SSOT per ADR-123 (SDK/application boundary).
152
+ * Consuming applications MUST import from `@sylphx/sdk` rather than duplicating
153
+ * this logic.
84
154
  *
85
155
  * Hosted format:
86
156
  * sylphx://{credential}@{tenant-slug}.api.sylphx.com[:port][/v{version}]
@@ -118,10 +188,38 @@ interface ParsedConnectionUrl {
118
188
  /** Ready-to-use SDK base URL, always HTTPS (e.g. `https://bold-river-a1b2c3.api.sylphx.com/v1`) */
119
189
  readonly apiBaseUrl: string;
120
190
  }
191
+ interface BuildConnectionUrlInput {
192
+ /** Credential — must match the credential format regex */
193
+ readonly credential: string;
194
+ /** Resource slug — validated DNS label */
195
+ readonly slug: string;
196
+ /** SDK API domain suffix; defaults to `api.sylphx.com`. Use `sylphx.dev` for dev. */
197
+ readonly domain?: string;
198
+ /** API version suffix, e.g. `v1`. Defaults to `v1`. Pass empty string to omit. */
199
+ readonly version?: string;
200
+ }
201
+ /**
202
+ * Credential format — opaque token with type, env, optional project ref, and
203
+ * hex payload. Ref-scoped credentials are emitted by Platform app-env injection;
204
+ * legacy credentials without the ref remain valid for existing deploys.
205
+ */
206
+ declare const CREDENTIAL_REGEX: RegExp;
121
207
  declare class InvalidConnectionUrlError extends Error {
122
208
  readonly code: "INVALID_CONNECTION_URL";
123
209
  constructor(message: string);
124
210
  }
211
+ /**
212
+ * Build a canonical Sylphx connection URL.
213
+ *
214
+ * Throws `InvalidConnectionUrlError` if any component is malformed.
215
+ */
216
+ declare function buildConnectionUrl(input: BuildConnectionUrlInput): string;
217
+ /**
218
+ * Parse a Sylphx connection URL into its structured components.
219
+ *
220
+ * Throws `InvalidConnectionUrlError` on any structural problem.
221
+ */
222
+ declare function parseConnectionUrl(url: string): ParsedConnectionUrl;
125
223
 
126
224
  /**
127
225
  * SDK Configuration — ADR-055 Connection URL API
@@ -261,6 +359,666 @@ type SylphxConfigInput = string | SylphxClientInput;
261
359
  */
262
360
  declare const createConfig: typeof createClient;
263
361
 
362
+ /**
363
+ * CSV utilities for browser and server SDK consumers.
364
+ */
365
+ /**
366
+ * Escape a CSV field to handle commas, quotes, and newlines.
367
+ *
368
+ * Handles null/undefined by returning an empty field. Wraps values containing
369
+ * RFC 4180 special characters in double quotes and escapes internal quotes.
370
+ */
371
+ declare function escapeCsvField(value: string | null | undefined): string;
372
+
373
+ /**
374
+ * Formatting Utilities
375
+ *
376
+ * Shared formatting functions for consistent display across the project.
377
+ */
378
+ /**
379
+ * Calculate percentage with consistent rounding.
380
+ * SSOT for all success rate, completion rate calculations.
381
+ *
382
+ * @param count - The numerator (e.g., successful count)
383
+ * @param total - The denominator (e.g., total count)
384
+ * @param decimals - Number of decimal places (default: 2)
385
+ * @returns Percentage value (0-100)
386
+ *
387
+ * @example
388
+ * ```ts
389
+ * calculatePercentage(75, 100) // 75
390
+ * calculatePercentage(1, 3) // 33.33
391
+ * calculatePercentage(0, 0) // 100 (safe division)
392
+ * ```
393
+ */
394
+ declare function calculatePercentage(count: number, total: number, decimals?: number): number;
395
+ /**
396
+ * Format microdollars to currency string
397
+ * @param microdollars Amount in microdollars (1 dollar = 1,000,000 microdollars)
398
+ * @param options Intl.NumberFormat options
399
+ */
400
+ declare function formatMicrodollars(microdollars: number, options?: Intl.NumberFormatOptions): string;
401
+ /**
402
+ * Format cents to currency string
403
+ * @param cents Amount in cents (100 cents = 1 dollar)
404
+ *
405
+ * @example
406
+ * ```ts
407
+ * formatCents(1999) // "$19.99"
408
+ * formatCents(100) // "$1.00"
409
+ * ```
410
+ */
411
+ declare function formatCents(cents: number): string;
412
+ /**
413
+ * Format dollars to currency string with optional compact notation
414
+ * @param amount Amount in dollars
415
+ * @param compact Use compact notation for large amounts (default: false)
416
+ *
417
+ * @example
418
+ * ```ts
419
+ * formatCurrency(1999.99) // "$1,999.99"
420
+ * formatCurrency(1999.99, true) // "$2.0K"
421
+ * formatCurrency(1999.99, { currency: 'EUR' }) // "€1,999.99"
422
+ * formatCurrency(1999.99, { compact: true }) // "$2.0K"
423
+ * ```
424
+ *
425
+ * Second argument accepts either a bare `boolean` (back-compat for
426
+ * the historical `compact` flag) or an options object with
427
+ * `{ currency, compact }`. The options form is required for any UI
428
+ * surface that displays multi-currency amounts (billing, invoices,
429
+ * usage statements) — previously two local copies of this function
430
+ * lived in `billing-management.tsx` to work around the missing
431
+ * currency parameter.
432
+ */
433
+ declare function formatCurrency(amount: number, optsOrCompact?: boolean | {
434
+ compact?: boolean;
435
+ currency?: string;
436
+ decimals?: number;
437
+ }): string;
438
+ /**
439
+ * Format percentage with sign for trend display
440
+ * @param value Percentage value (not multiplied by 100)
441
+ *
442
+ * @example
443
+ * ```ts
444
+ * formatPercent(12.5) // "+12.5%"
445
+ * formatPercent(-5.2) // "-5.2%"
446
+ * formatPercent(0) // "+0.0%"
447
+ * ```
448
+ */
449
+ declare function formatPercent(value: number): string;
450
+ /**
451
+ * Format number with abbreviated suffix (K, M, B) or compact notation
452
+ * @param num Number to format
453
+ * @param compact Use Intl compact notation (default: false, uses K/M/B suffix)
454
+ *
455
+ * @example
456
+ * ```ts
457
+ * formatNumber(1234) // "1,234"
458
+ * formatNumber(1234567) // "1.2M"
459
+ * formatNumber(1234, true) // "1.2K" (Intl compact)
460
+ * ```
461
+ */
462
+ declare function formatNumber(num: number, compact?: boolean): string;
463
+ /**
464
+ * Format duration in milliseconds to human-readable string.
465
+ * SSOT for latency display in traces, performance, and monitoring.
466
+ *
467
+ * @param ms Duration in milliseconds
468
+ * @returns Formatted string (e.g., "<1ms", "42ms", "1.23s")
469
+ *
470
+ * @example
471
+ * ```ts
472
+ * formatDuration(0.5) // "<1ms"
473
+ * formatDuration(42) // "42ms"
474
+ * formatDuration(1500) // "1.50s"
475
+ * ```
476
+ */
477
+ declare function formatDuration(ms: number): string;
478
+ /**
479
+ * Format bytes to human-readable string
480
+ * @param bytes Number of bytes
481
+ * @param decimals Number of decimal places (default: 1)
482
+ */
483
+ declare function formatBytes(bytes: number | null | undefined, decimals?: number): string;
484
+ /** Badge variant type for consistency */
485
+ type BadgeVariant = 'default' | 'secondary' | 'success' | 'warning' | 'error' | 'outline';
486
+ /**
487
+ * Get billing status badge variant.
488
+ * Pure function — no side effects, deterministic output.
489
+ *
490
+ * @param status Billing account status
491
+ * @returns Badge variant for display
492
+ */
493
+ declare function getBillingStatusVariant(status: string): BadgeVariant;
494
+ /**
495
+ * Get invoice status badge variant.
496
+ * Pure function — no side effects, deterministic output.
497
+ *
498
+ * @param status Invoice status
499
+ * @returns Badge variant for display
500
+ */
501
+ declare function getInvoiceStatusVariant(status: string): BadgeVariant;
502
+ /**
503
+ * Format date for display
504
+ * @param date Date to format (null returns fallback)
505
+ * @param options Intl.DateTimeFormat options
506
+ * @param fallback Value to return when date is null (default: '-')
507
+ */
508
+ declare function formatDate(date: Date | string | null, options?: Intl.DateTimeFormatOptions, fallback?: string): string;
509
+ /**
510
+ * Format date with time for display
511
+ * @param date Date to format (null returns fallback)
512
+ * @param options Override options
513
+ * @param fallback Value to return when date is null (default: '-')
514
+ */
515
+ declare function formatDateTime(date: Date | string | null, options?: Intl.DateTimeFormatOptions, fallback?: string): string;
516
+ /**
517
+ * Format relative time (e.g., "2 hours ago")
518
+ *
519
+ * Uses native Intl.RelativeTimeFormat for proper localization.
520
+ *
521
+ * @param date Date to format (null returns 'Never')
522
+ */
523
+ declare function formatRelativeTime(date: Date | string | null): string;
524
+ /**
525
+ * Format relative time in compact form (e.g., "2h ago", "3d ago").
526
+ * SSOT for dense UI contexts: tables, feeds, badges.
527
+ *
528
+ * Uses short suffixes (s/m/h/d/w) instead of Intl.RelativeTimeFormat words.
529
+ * For prose contexts, use {@link formatRelativeTime} instead.
530
+ *
531
+ * @param date Date to format (null returns 'Never')
532
+ *
533
+ * @example
534
+ * ```ts
535
+ * formatRelativeTimeShort(new Date()) // "Just now"
536
+ * formatRelativeTimeShort('2024-01-01T00:00:00Z') // "3d ago"
537
+ * formatRelativeTimeShort(null) // "Never"
538
+ * ```
539
+ */
540
+ declare function formatRelativeTimeShort(date: Date | string | null): string;
541
+ /**
542
+ * Format month and year (e.g., "January 2024")
543
+ * SSOT for billing period display, invoice headers.
544
+ * @param date Date to format (null returns fallback)
545
+ * @param fallback Value to return when date is null
546
+ */
547
+ declare function formatMonthYear(date: Date | string | null, fallback?: string): string;
548
+ /**
549
+ * Format time only (e.g., "2:30 PM")
550
+ * SSOT for log timestamps, activity feeds.
551
+ * @param date Date to format (null returns fallback)
552
+ * @param fallback Value to return when date is null
553
+ */
554
+ declare function formatTime(date: Date | string | null, fallback?: string): string;
555
+
556
+ /**
557
+ * Safely parse a JSON string, returning a fallback value on failure instead of throwing.
558
+ *
559
+ * Use this when malformed input is a normal (non-exceptional) case — e.g. parsing
560
+ * user-provided data, localStorage values, or Redis cache entries where the caller
561
+ * simply wants a default on failure.
562
+ *
563
+ * For cases where parse failure is truly exceptional and the caller needs to handle
564
+ * the error explicitly, use a standard try-catch with proper logging instead.
565
+ */
566
+ declare function safeJsonParse<T = unknown>(input: string, fallback?: T): T | null;
567
+
568
+ /**
569
+ * Utility Functions
570
+ */
571
+ /**
572
+ * Get the base URL for API requests
573
+ *
574
+ * Use cases:
575
+ * - getBaseUrl(): For relative URLs in browser, absolute in SSR (tRPC, API calls)
576
+ * - getBaseUrl('origin'): For absolute URLs that need the actual origin (auth, sharing)
577
+ *
578
+ * Priority: NEXT_PUBLIC_APP_URL > localhost
579
+ */
580
+ declare function getBaseUrl(mode?: 'relative' | 'origin'): string;
581
+ /**
582
+ * Escape HTML special characters to prevent XSS
583
+ *
584
+ * Uses single-pass regex replacement for efficiency.
585
+ */
586
+ declare function escapeHtml(str: string): string;
587
+ /**
588
+ * Generate a URL-friendly slug from text
589
+ *
590
+ * @param text - Text to convert to slug
591
+ * @param maxLength - Optional maximum length (default: no limit)
592
+ * @returns Lowercase slug with hyphens
593
+ *
594
+ * @example
595
+ * generateSlug('My Awesome App') // 'my-awesome-app'
596
+ * generateSlug('Hello World!') // 'hello-world'
597
+ * generateSlug('My Org Name', 48) // 'my-org-name' (max 48 chars)
598
+ */
599
+ declare function generateSlug(text: string, maxLength?: number): string;
600
+
601
+ /**
602
+ * User Agent Parsing Utilities
603
+ *
604
+ * Extracts browser, OS, and device type from user agent strings.
605
+ * Simple implementation - no external dependencies.
606
+ */
607
+ interface ParsedUserAgent {
608
+ browser: string | null;
609
+ os: string | null;
610
+ deviceType: 'desktop' | 'mobile' | 'tablet' | null;
611
+ }
612
+ /**
613
+ * Parse a user agent string to extract browser, OS, and device type.
614
+ * Returns null values if unable to determine.
615
+ */
616
+ declare function parseUserAgent(ua: string): ParsedUserAgent;
617
+
618
+ /**
619
+ * Authentication Configuration (SSOT)
620
+ *
621
+ * Single source of truth for authentication-related constants.
622
+ * Used by: validation schemas, auth forms, password policies
623
+ */
624
+ /** Minimum password length */
625
+ declare const MIN_PASSWORD_LENGTH = 8;
626
+ /** Maximum password length */
627
+ declare const MAX_PASSWORD_LENGTH = 128;
628
+ /** Password requirements for display in UI */
629
+ declare const PASSWORD_REQUIREMENTS: {
630
+ readonly minLength: 8;
631
+ readonly maxLength: 128;
632
+ readonly description: "Must be at least 8 characters";
633
+ readonly placeholder: "Min. 8 characters";
634
+ };
635
+
636
+ /**
637
+ * Billing Configuration (SSOT)
638
+ *
639
+ * Single source of truth for billing-related configuration.
640
+ * Used by: billing pages, usage tracking, invoicing
641
+ */
642
+ /** Bytes per gigabyte — use instead of hardcoding 1024*1024*1024 */
643
+ declare const BYTES_PER_GB: number;
644
+ /** Microdollars per cent ($0.01 = 10,000 microdollars) */
645
+ declare const MICRODOLLARS_PER_CENT = 10000;
646
+ /** Invoice payment due after billing period ends (days) */
647
+ declare const INVOICE_DUE_DAYS = 15;
648
+ /**
649
+ * Billing metrics per service
650
+ * These are user-facing metric names (NOT technical terms like 'commands')
651
+ */
652
+ declare const SERVICE_METRICS: {
653
+ readonly kv: {
654
+ readonly operations: "operations";
655
+ readonly storage: "storage";
656
+ };
657
+ readonly realtime: {
658
+ readonly messages: "messages";
659
+ readonly connections: "connections";
660
+ };
661
+ readonly ai: {
662
+ readonly tokens: "tokens";
663
+ };
664
+ readonly email: {
665
+ readonly emails: "emails";
666
+ readonly marketingEmails: "marketing_emails";
667
+ };
668
+ readonly notifications: {
669
+ readonly sends: "sends";
670
+ };
671
+ readonly analytics: {
672
+ readonly events: "events";
673
+ readonly forwarding: "forwarding";
674
+ };
675
+ readonly storage: {
676
+ readonly capacity: "capacity";
677
+ readonly uploads: "uploads";
678
+ readonly egress: "egress";
679
+ };
680
+ readonly auth: {
681
+ readonly mau: "mau";
682
+ };
683
+ readonly flags: {
684
+ readonly evaluations: "evaluations";
685
+ };
686
+ readonly consent: {
687
+ readonly records: "records";
688
+ };
689
+ readonly referrals: {
690
+ readonly conversions: "conversions";
691
+ };
692
+ readonly engagement: {
693
+ readonly operations: "operations";
694
+ };
695
+ readonly billing: {
696
+ readonly subscriptions: "subscriptions";
697
+ readonly usageRecords: "usage_records";
698
+ };
699
+ readonly search: {
700
+ readonly documents: "documents";
701
+ readonly searches: "searches";
702
+ };
703
+ readonly webhooks: {
704
+ readonly deliveries: "deliveries";
705
+ };
706
+ readonly monitoring: {
707
+ readonly errors: "errors";
708
+ };
709
+ readonly jobs: {
710
+ readonly invocations: "invocations";
711
+ readonly cronSchedules: "cron_schedules";
712
+ };
713
+ readonly database: {
714
+ readonly computeSeconds: "compute_seconds";
715
+ readonly storage: "storage";
716
+ readonly dataTransferBytes: "data_transfer_bytes";
717
+ };
718
+ readonly deploy: {
719
+ readonly buildMinutes: "build_minutes";
720
+ };
721
+ };
722
+ /** Active vCPU rate: $0.024/hr = $0.0004/min = 400 microdollars/min (ADR-034) */
723
+ declare const COMPUTE_VCPU_ACTIVE_RATE_MICRODOLLARS = 400;
724
+ /** Idle vCPU rate: $0.003/hr = $0.00005/min = 50 microdollars/min — 1/8 of active (ADR-034) */
725
+ declare const COMPUTE_VCPU_IDLE_RATE_MICRODOLLARS = 50;
726
+ /** RAM rate: $0.010/GB-hr = $0.000167/GB-min = 167 microdollars/GB-min (ADR-034) */
727
+ declare const COMPUTE_RAM_RATE_MICRODOLLARS = 167;
728
+ /** Build minute prices by machine type in microdollars per minute (ADR-034) */
729
+ declare const BUILD_MINUTE_PRICES: Record<string, number>;
730
+ /** Build minute size multipliers for quota tracking (ADR-034) */
731
+ declare const BUILD_SIZE_MULTIPLIERS: Record<string, number>;
732
+ /** Build minutes included per month by plan tier (ADR-034) */
733
+ declare const BUILD_MINUTES_INCLUDED: Record<string, number>;
734
+ /**
735
+ * @deprecated Use BUILD_MINUTE_PRICES.standard instead (ADR-034).
736
+ * Kept for backward compatibility with existing billing pipelines.
737
+ *
738
+ * CI compute-minute price in microdollars.
739
+ * Now references the standard build machine rate from ADR-034.
740
+ */
741
+ declare const CI_BUILD_MINUTE_PRICE_MICRODOLLARS: number;
742
+ /**
743
+ * @deprecated Use BUILD_MINUTES_INCLUDED[plan] instead (ADR-034).
744
+ * Kept for backward compatibility. Maps to the `team` tier as the
745
+ * previous default (2,000 free minutes).
746
+ */
747
+ declare const CI_FREE_MINUTES_PER_MONTH: number;
748
+ /**
749
+ * Size multipliers for CI compute-minute accounting (legacy GitHub labels).
750
+ *
751
+ * Keys are **GitHub Actions runner labels** (not build machine type names).
752
+ * These labels arrive on workflow_job webhooks and are stored as-is in
753
+ * githubCiJobs.resourceClass. The billing pipeline maps them to multipliers
754
+ * here; the build pipeline maps them to BuildMachineType via
755
+ * normalizeBuildMachineType() in build-machine.ts.
756
+ *
757
+ * @see BUILD_SIZE_MULTIPLIERS for canonical build machine multipliers (ADR-034).
758
+ */
759
+ declare const CI_SIZE_MULTIPLIERS: Record<string, number>;
760
+ /** macOS runner per-size multipliers (ADR-035: per-tier billing) */
761
+ declare const CI_MACOS_SIZE_MULTIPLIERS: Record<string, number>;
762
+ /** @deprecated Use CI_MACOS_SIZE_MULTIPLIERS[size] instead. */
763
+ declare const CI_MACOS_MULTIPLIER: number;
764
+ type ServiceMetrics = typeof SERVICE_METRICS;
765
+ type KvMetric = keyof typeof SERVICE_METRICS.kv;
766
+ type RealtimeMetric = keyof typeof SERVICE_METRICS.realtime;
767
+ /** Credit expiry period in months */
768
+ declare const CREDIT_EXPIRY_MONTHS = 12;
769
+ /** Maximum payment retry attempts before suspending account */
770
+ declare const MAX_PAYMENT_ATTEMPTS = 3;
771
+ /** Roles that can access billing pages */
772
+ declare const BILLING_ALLOWED_ROLES: readonly ["super_admin", "admin", "billing"];
773
+ type BillingAllowedRole = (typeof BILLING_ALLOWED_ROLES)[number];
774
+ /** Check if a role has billing access */
775
+ declare function hasBillingAccess(role: string): boolean;
776
+
777
+ /**
778
+ * Console SDK Key Utilities
779
+ *
780
+ * The Platform Console is Customer Zero — it uses the exact same key format
781
+ * as every other customer: pk_{env}_{ref}_{hex} / sk_{env}_{ref}_{hex}.
782
+ *
783
+ * No special key construction. No legacy app_* format. No special lookup paths.
784
+ *
785
+ * Keys are set via environment variables, just like any customer app:
786
+ * NEXT_PUBLIC_SYLPHX_KEY = pk_prod_nlbaz63pd2gz_97ef4f90c48e7378b0f00a1e2cb8c15e
787
+ * SYLPHX_SECRET_KEY = sk_prod_nlbaz63pd2gz_edea406b7988099f5826c143b0f6bd94...
788
+ */
789
+ /** Console project slug — must match bootstrap.ts PLATFORM_CONSOLE_APP.slug */
790
+ declare const CONSOLE_APP_SLUG = "sylphx-console";
791
+ /**
792
+ * Determine environment prefix from build/runtime environment.
793
+ * Used by sdk-cookies.ts for cookie naming until it migrates to SDK-native getCookieNames().
794
+ * NOTE: still actively consumed by sdk-cookies.ts and sdk-login.ts — remove only after
795
+ * those modules parse the env prefix from NEXT_PUBLIC_SYLPHX_KEY directly.
796
+ */
797
+ declare function getEnvPrefix(): 'dev' | 'stg' | 'prod';
798
+
799
+ /**
800
+ * Platform Plan Tiers — SSOT
801
+ *
802
+ * Defines the Sylphx Platform plan tier system (ADR-034).
803
+ * NOTE: This is for *platform* plans (what the organization pays Sylphx for).
804
+ * It is separate from `plans` (which are in-app subscription products
805
+ * that customers create for their own end-users).
806
+ *
807
+ * All prices in cents (USD). Credits in microdollars (1 USD = 1,000,000 µ$).
808
+ *
809
+ * ADR-034 tiers: Free → Pro ($20/mo) → Team ($20/user/mo) → Enterprise (custom)
810
+ * The 'starter' tier is deprecated but kept in the type union for backward
811
+ * compatibility with existing database rows and API consumers.
812
+ */
813
+ /**
814
+ * Platform plan identifiers.
815
+ * 'starter' is deprecated (ADR-034) — retained for backward compat with existing records.
816
+ */
817
+ type PlatformPlanId = 'free' | 'starter' | 'pro' | 'team' | 'enterprise';
818
+ type BuildMachineTier = 'standard' | 'large' | 'xlarge';
819
+ interface PlatformPlanLimits {
820
+ /** Max projects across all environments */
821
+ maxProjects: number | null;
822
+ /** Max organization members */
823
+ maxMembers: number | null;
824
+ /** Max custom domains */
825
+ maxCustomDomains: number | null;
826
+ /** Max concurrent CI runners */
827
+ maxConcurrentRunners: number | null;
828
+ /** Max concurrent macOS CI runners */
829
+ maxMacosRunners: number | null;
830
+ /** Max managed databases */
831
+ maxDatabases: number | null;
832
+ /** CI job max duration in seconds */
833
+ ciMaxJobDurationSeconds: number;
834
+ /** API rate limit (requests per minute) */
835
+ apiRateLimitPerMin: number;
836
+ /** Audit log retention in days (0 = off) */
837
+ auditLogDays: number;
838
+ /** Max replicas per service (null = custom/negotiated) */
839
+ maxReplicas: number | null;
840
+ /** Included build minutes per billing period */
841
+ includedBuildMinutes: number;
842
+ /** Included outbound bandwidth in GB per billing period */
843
+ includedBandwidthGb: number;
844
+ /** Log retention in days */
845
+ logRetentionDays: number;
846
+ /** Build machine tier determining build speed */
847
+ buildMachineTier: BuildMachineTier;
848
+ }
849
+ interface PlatformPlanFeatures {
850
+ /** Custom domain support */
851
+ customDomains: boolean;
852
+ /** SSO / SAML support */
853
+ sso: boolean;
854
+ /** Priority CI queue */
855
+ priorityCi: boolean;
856
+ /** macOS CI runners */
857
+ macosCi: boolean;
858
+ /** Shared / Priority / Dedicated */
859
+ support: 'community' | 'email' | 'priority' | 'dedicated';
860
+ /** SLA uptime guarantee string (e.g. '99.9%') */
861
+ sla: string | null;
862
+ /** Role-based access control */
863
+ rbac: boolean;
864
+ /** Advanced analytics / insights */
865
+ advancedAnalytics: boolean;
866
+ /** White-label branding removal */
867
+ whiteLabel: boolean;
868
+ }
869
+ interface PlatformPlanDefinition {
870
+ id: PlatformPlanId;
871
+ name: string;
872
+ /** Monthly price in cents (0 = free, null = custom) */
873
+ priceMonthly: number | null;
874
+ /** Annual price in cents, ~20% discount (null = custom or N/A) */
875
+ priceAnnual: number | null;
876
+ /** Included platform compute credits per billing period (microdollars) */
877
+ includedCreditsMicrodollars: number;
878
+ /** Whether price is per seat (per member) — Team plan */
879
+ perSeat?: boolean;
880
+ features: PlatformPlanFeatures;
881
+ limits: PlatformPlanLimits;
882
+ /** Marketing bullet points for pricing cards */
883
+ highlights: string[];
884
+ /** Optional badge label (e.g. "Most Popular") */
885
+ badge?: string;
886
+ /** CTA button text */
887
+ cta: string;
888
+ /** Whether this is a custom/enterprise plan with contact sales flow */
889
+ isCustom?: boolean;
890
+ /**
891
+ * Deprecated plan — no longer available for new subscriptions.
892
+ * Existing subscribers are grandfathered until they change plans.
893
+ */
894
+ deprecated?: boolean;
895
+ }
896
+ declare const PLATFORM_PLANS: Record<PlatformPlanId, PlatformPlanDefinition>;
897
+ /** Active (non-deprecated) plan IDs for display in pricing UI */
898
+ declare const PLATFORM_PLAN_ORDER: PlatformPlanId[];
899
+ /**
900
+ * Full plan order including deprecated tiers.
901
+ * Useful for admin screens and migration tooling that must handle legacy plans.
902
+ */
903
+ declare const PLATFORM_PLAN_ORDER_ALL: PlatformPlanId[];
904
+ /** Check whether a plan is deprecated and should not be offered to new subscribers */
905
+ declare function isPlanDeprecated(planId: PlatformPlanId): boolean;
906
+ /** Get only active (non-deprecated) plan definitions, in display order */
907
+ declare function getActivePlans(): PlatformPlanDefinition[];
908
+ /** Convert microdollars to human-readable dollar string (e.g. "$5") */
909
+ declare function microsToDollars(microdollars: number): string;
910
+ /** Convert cents to human-readable dollar string (e.g. "$19") */
911
+ declare function centsToDollars(cents: number): string;
912
+ /** Get monthly price display string */
913
+ declare function getPlanMonthlyPrice(plan: PlatformPlanDefinition, annual?: boolean): string;
914
+
915
+ /**
916
+ * Instance Type Catalog — SSOT
917
+ *
918
+ * Defines the compute instance types available for Sylphx platform workloads.
919
+ * Each instance type maps to Kubernetes resource requests/limits for kata-clh
920
+ * (Cloud Hypervisor) microVMs, along with billing rates and plan eligibility.
921
+ *
922
+ * Rates are in microdollars (1 USD = 1,000,000 µ$) per minute.
923
+ *
924
+ * Memory overcommit (ADR-028): CLH uses demand paging (mmap without MAP_POPULATE).
925
+ * Host physical RAM is allocated on-demand as guest pages are touched, NOT pre-allocated
926
+ * at VM boot. Verified 2026-03-30: a pod with limits=4Gi only consumed +8Mi host RAM
927
+ * when idle. Memory requests are set to 50% of limits (2x overcommit) for efficient
928
+ * scheduler bin-packing. CPU requests are 25% of limits (4x overcommit).
929
+ *
930
+ * ADR-034 T-shirt sizing: canonical names are xs/sm/md/lg/xl/2xl/4xl.
931
+ * Legacy names (starter-1x, standard-1x, etc.) are kept as aliases for backward
932
+ * compatibility with existing database values and API consumers.
933
+ */
934
+
935
+ type InstanceTypeId = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl' | '4xl' | 'starter-1x' | 'standard-1x' | 'standard-2x' | 'performance-m' | 'performance-l' | 'performance-xl';
936
+ interface InstanceTypeDefinition {
937
+ id: InstanceTypeId;
938
+ name: string;
939
+ /** Kubernetes CPU limit (e.g. '2000m') */
940
+ cpuLimit: string;
941
+ /** Kubernetes memory limit (e.g. '8Gi') */
942
+ memoryLimit: string;
943
+ /** Kubernetes CPU request (e.g. '500m') */
944
+ cpuRequest: string;
945
+ /** Kubernetes memory request (50% of limit — CLH demand paging, ADR-028) */
946
+ memoryRequest: string;
947
+ /** Billing vCPU count for metering denormalization */
948
+ vcpus: number;
949
+ /** Billing memory in MiB for metering denormalization */
950
+ memoryMib: number;
951
+ /** Rate per vCPU per minute in microdollars */
952
+ vcpuMinuteRateMicrodollars: number;
953
+ /** Rate per GiB per minute in microdollars */
954
+ gbMinuteRateMicrodollars: number;
955
+ /** Platform plans that may provision this instance type */
956
+ allowedPlans: PlatformPlanId[];
957
+ /**
958
+ * Maximum KEDA ScaledObject replica count for this instance type tier.
959
+ * Caps the ScaledObject maxReplicaCount to prevent runaway scaling
960
+ * on smaller tiers. Users can set a lower per-service max via scalingConfig.max,
961
+ * but never exceed this ceiling.
962
+ */
963
+ maxReplicas: number;
964
+ /** Marketing bullet points for instance type cards */
965
+ highlights: string[];
966
+ /** Whether this instance type is deprecated (legacy name) */
967
+ deprecated?: boolean;
968
+ }
969
+ /**
970
+ * Maps legacy instance type names to their canonical T-shirt size equivalents (ADR-034).
971
+ *
972
+ * Database values and API consumers may still use old names — this mapping lets
973
+ * resolveInstanceType() transparently return the canonical definition without
974
+ * requiring a data migration.
975
+ */
976
+ declare const INSTANCE_TYPE_ALIASES: Record<string, string>;
977
+ /**
978
+ * Resolve a potentially-aliased instance type ID to its canonical T-shirt size.
979
+ * Returns the input unchanged if it is already canonical or unknown.
980
+ *
981
+ * Use for display/UI and when accepting user input for NEW configurations.
982
+ * Do NOT use in runtime paths (billing, K8s reconciler) — both old and new names
983
+ * exist in INSTANCE_TYPES with their original specs, so direct lookup is correct
984
+ * and avoids changing billing/resource behavior for existing services.
985
+ */
986
+ declare function resolveCanonicalInstanceType(id: string): string;
987
+ declare const INSTANCE_TYPES: Record<InstanceTypeId, InstanceTypeDefinition>;
988
+ /** Ordered list of canonical instance type IDs for display (smallest to largest) */
989
+ declare const INSTANCE_TYPE_ORDER: InstanceTypeId[];
990
+ /**
991
+ * @deprecated Use INSTANCE_TYPE_ORDER instead.
992
+ * Ordered list of legacy instance type IDs — kept for backward compat.
993
+ */
994
+ declare const LEGACY_INSTANCE_TYPE_ORDER: InstanceTypeId[];
995
+ /** Get the default instance type for a given platform plan */
996
+ declare function getDefaultInstanceType(plan: PlatformPlanId): InstanceTypeId;
997
+ /** Get all canonical (non-deprecated) instance types available for a given platform plan, in display order */
998
+ declare function getAvailableInstanceTypes(plan: PlatformPlanId): InstanceTypeDefinition[];
999
+ /** Resolve Kubernetes resource spec for a given instance type (accepts aliases) */
1000
+ declare function resolveResources(id: InstanceTypeId): {
1001
+ requests: {
1002
+ cpu: string;
1003
+ memory: string;
1004
+ };
1005
+ limits: {
1006
+ cpu: string;
1007
+ memory: string;
1008
+ };
1009
+ };
1010
+ /** Resolve the KEDA ScaledObject maxReplicaCount ceiling for a given instance type */
1011
+ declare function resolveMaxReplicas(id: InstanceTypeId): number;
1012
+ /** Default KEDA maxReplicaCount when no instance type is resolved (legacy/unmanaged services) */
1013
+ declare const DEFAULT_MAX_REPLICAS = 10;
1014
+ /** Type guard: check if an arbitrary string is a valid InstanceTypeId (including legacy aliases) */
1015
+ declare function isValidInstanceType(id: string): id is InstanceTypeId;
1016
+ /** Validate that an instance type exists and is permitted for the given plan */
1017
+ declare function validateInstanceTypeForPlan(id: string, plan: PlatformPlanId): {
1018
+ valid: boolean;
1019
+ error?: string;
1020
+ };
1021
+
264
1022
  /**
265
1023
  * SDK Debug Mode
266
1024
  *
@@ -875,11 +1633,22 @@ declare function isRetryableError(error: unknown): boolean;
875
1633
  /**
876
1634
  * Extract error message from any error type
877
1635
  */
878
- declare function getErrorMessage(error: unknown): string;
1636
+ declare function getErrorMessage(error: unknown, fallback?: string): string;
879
1637
  /**
880
1638
  * Get error code from any error type
881
1639
  */
882
1640
  declare function getErrorCode(error: unknown): SylphxErrorCode;
1641
+ interface ErrorDetails {
1642
+ readonly message: string;
1643
+ readonly code?: string;
1644
+ readonly name?: string;
1645
+ readonly stack?: string;
1646
+ readonly status?: number;
1647
+ readonly cause?: unknown;
1648
+ }
1649
+ declare function getErrorDetails(error: unknown, fallbackMessage?: string): ErrorDetails;
1650
+ declare function getSafeErrorMessage(error: unknown, fallback?: string): string;
1651
+ declare function isChallengeRequired(err: unknown): boolean;
883
1652
  /**
884
1653
  * Convert any error to SylphxError
885
1654
  */
@@ -1811,438 +2580,479 @@ interface PaginatedResponse<T> {
1811
2580
  }
1812
2581
 
1813
2582
  /**
1814
- * Auth Functions
1815
- *
1816
- * Pure functions for authentication - no hidden state.
1817
- * Each function takes config as the first parameter.
1818
- *
1819
- * Uses REST API at /api/sdk/auth/* for all operations.
2583
+ * DPoP — Demonstration of Proof-of-Possession (RFC 9449 / ADR-089 Phase 5.1e).
1820
2584
  *
1821
- * Types are re-exported from `@sylphx/contract` (ADR-084). The contract is
1822
- * the single source of truth for every wire shape — this module only adds
1823
- * SDK-specific ergonomics (User brand swap, introspection result, invite
1824
- * envelopes, org-token claims).
2585
+ * Client-side helpers for sender-constrained access tokens. Built on
2586
+ * `crypto.subtle` with no runtime dependencies.
1825
2587
  */
2588
+ declare const dpop: {
2589
+ /**
2590
+ * Generate a fresh ES256 key pair. Private key is non-extractable
2591
+ * (`extractable: false`) so it can be stored but never serialised.
2592
+ */
2593
+ readonly generateKeyPair: () => Promise<{
2594
+ readonly privateKey: CryptoKey;
2595
+ readonly publicKey: CryptoKey;
2596
+ readonly thumbprint: string;
2597
+ }>;
2598
+ /**
2599
+ * Sign a DPoP proof JWT. When `accessToken` is provided, the proof
2600
+ * includes `ath = base64url(sha256(accessToken))` so the resource
2601
+ * server can bind the proof to the token being presented.
2602
+ */
2603
+ readonly generateProof: (opts: {
2604
+ readonly privateKey: CryptoKey;
2605
+ readonly publicKey: CryptoKey;
2606
+ readonly method: string;
2607
+ readonly uri: string;
2608
+ readonly accessToken?: string;
2609
+ readonly nonce?: string;
2610
+ }) => Promise<string>;
2611
+ };
1826
2612
 
1827
- type LoginRequest = LoginRequest$1;
1828
- type LoginResponse = LoginResponse$1;
1829
- type RegisterRequest = RegisterRequest$1;
1830
- type RegisterResponse = RegisterResponse$1;
1831
- type ResendEmailVerificationRequest = ResendEmailVerificationRequest$1;
1832
- type ResendEmailVerificationResponse = ResendEmailVerificationResponse$1;
1833
2613
  /**
1834
- * Token response contract's `AuthTokensResponse.user` (optional `AuthUser`)
1835
- * is re-mapped to the SDK's broader `User` type so legacy callers keep the
1836
- * familiar brand. `AuthUser` and `User` are structurally identical, but
1837
- * the SDK surface has wider reach (cookies, middleware, React hooks) and
1838
- * renaming is out of scope for ADR-084 cleanup.
2614
+ * OAuth token endpoint contract helpers.
2615
+ *
2616
+ * Keeps RFC 6749/8628 request encoding, success decoding, and error decoding
2617
+ * type-bound to `@sylphx/contract` while using SDK-local runtime guards so the
2618
+ * published Promise SDK does not import Effect internals.
1839
2619
  */
1840
- type TokenResponse = Omit<AuthTokensResponse, 'user'> & {
1841
- user: User;
2620
+
2621
+ type OAuthTokenResult = OAuthTokenResponse;
2622
+ type OAuthClientCredentialsResult = OAuthClientCredentialsResponse;
2623
+ type OAuthTokenEndpointError = OAuthTokenErrorResponse['error'];
2624
+ type OAuthPollError = OAuthTokenEndpointError | 'oauth_error';
2625
+ type OAuthPollResult = {
2626
+ readonly ok: true;
2627
+ readonly tokens: OAuthTokenResult;
2628
+ } | {
2629
+ readonly ok: false;
2630
+ readonly error: OAuthPollError;
2631
+ readonly status: number;
1842
2632
  };
1843
- type TwoFactorVerifyRequest = TwoFactorVerifyRequest$1;
2633
+
1844
2634
  /**
1845
- * `GET /auth/me` contract's `UserFullProfile` already includes the
1846
- * optional `emailVerified` flag the backend returns, so the SDK can just
1847
- * alias the contract type directly.
2635
+ * Platform refresh-token rotation and logout SDK namespace.
1848
2636
  */
1849
- type MeResponse = UserFullProfile$1;
2637
+
2638
+ type PlatformRefreshInput = RefreshTokenInput;
2639
+ type PlatformRefreshResult = RefreshTokenResult;
2640
+ type PlatformLogoutInput = LogoutInput;
2641
+ declare const platformAuth: {
2642
+ readonly refresh: (opts: {
2643
+ readonly baseUrl: string;
2644
+ readonly refreshToken: string;
2645
+ readonly userAgent?: string;
2646
+ /**
2647
+ * Path prefix between `baseUrl` and the resource path. Defaults
2648
+ * to `/api/v1` for back-compat with the admin-override host
2649
+ * (`sylphx.com`). Pass `/v1` when targeting the canonical host
2650
+ * (`api.sylphx.com`) per Rule 17.
2651
+ */
2652
+ readonly urlPrefix?: string;
2653
+ }) => Promise<PlatformRefreshResult>;
2654
+ readonly logout: (opts: {
2655
+ readonly baseUrl: string;
2656
+ readonly refreshToken: string;
2657
+ readonly userAgent?: string;
2658
+ /** See `refresh.urlPrefix`. */
2659
+ readonly urlPrefix?: string;
2660
+ }) => Promise<void>;
2661
+ };
2662
+
1850
2663
  /**
1851
- * Token introspection result (RFC 7662)
2664
+ * Platform impersonation SDK namespace.
2665
+ *
2666
+ * Covers the ADR-089 Phase 3b legacy helpers and Phase 5.9 WebAuthn
2667
+ * step-up + target-consent workflow.
1852
2668
  */
1853
- interface TokenIntrospectionResult {
1854
- /** Whether the token is active/valid */
1855
- active: boolean;
1856
- /** Token type (access_token or refresh_token) */
1857
- token_type?: 'access_token' | 'refresh_token';
1858
- /** User ID */
1859
- sub?: string;
1860
- /** User email */
1861
- email?: string;
1862
- /** User name */
1863
- name?: string;
1864
- /** App ID */
1865
- client_id?: string;
1866
- /** Audience */
1867
- aud?: string;
1868
- /** Issuer */
1869
- iss?: string;
1870
- /** Expiration time (Unix timestamp) */
1871
- exp?: number;
1872
- /** Issued at time (Unix timestamp) */
1873
- iat?: number;
1874
- /** User role */
1875
- role?: string;
1876
- /** Email verification status */
1877
- email_verified?: boolean;
2669
+ interface ImpersonationStartResult {
2670
+ readonly success: true;
2671
+ readonly token: string;
2672
+ readonly sessionId: string;
2673
+ readonly expiresAt: string;
1878
2674
  }
1879
- /**
1880
- * Token revocation options
1881
- */
1882
- interface RevokeTokenOptions {
1883
- /** Revoke all tokens for a user in this app */
1884
- revokeAll?: boolean;
1885
- /** User ID (required when revoking all) */
1886
- userId?: string;
2675
+ interface ImpersonationEndResult {
2676
+ readonly success: boolean;
2677
+ readonly sessionsEnded: number;
1887
2678
  }
1888
- interface SessionResult {
1889
- user: {
1890
- id: string;
1891
- email: string;
1892
- name: string | null;
1893
- image: string | null;
1894
- emailVerified: boolean;
1895
- } | null;
2679
+ interface ImpersonationInfo {
2680
+ readonly isImpersonation: true;
2681
+ readonly adminUserId: string;
2682
+ readonly adminEmail: string;
2683
+ readonly adminName: string | null;
2684
+ readonly impersonatedAt: string;
1896
2685
  }
1897
- /**
1898
- * Extended registration input with metadata and invitation token support.
1899
- * Use extendedSignUp() when you need to pass metadata or an invitation token.
1900
- */
1901
- interface RegisterInput {
1902
- email: string;
1903
- password: string;
1904
- name?: string;
1905
- metadata?: Record<string, unknown>;
1906
- invitationToken?: string;
2686
+ interface ImpersonationActive {
2687
+ readonly sessionId: string;
2688
+ readonly adminUserId: string;
2689
+ readonly adminEmail: string;
2690
+ readonly adminName: string | null;
2691
+ readonly targetUserId: string;
2692
+ readonly targetEmail: string;
2693
+ readonly targetName: string | null;
2694
+ readonly impersonatedAt: string;
2695
+ readonly lastActiveAt: string;
1907
2696
  }
1908
- /**
1909
- * Org context claims present in org-scoped tokens (after switch-org).
1910
- *
1911
- * The JWT carries the role key only. Permissions are resolved server-side
1912
- * via Redis-cached role→permissions lookup (WorkOS pattern). This keeps
1913
- * tokens small and ensures permission changes take effect without token refresh.
1914
- */
1915
- interface OrgTokenPayload {
1916
- org_id: string;
1917
- org_slug: string;
1918
- /** RBAC role key (e.g. "hr_manager", "admin"). Permissions resolved server-side. */
1919
- org_role: string;
2697
+ interface ImpersonationStartChallengeInput {
2698
+ readonly baseUrl: string;
2699
+ readonly accessToken: string;
2700
+ readonly targetUserId: string;
2701
+ readonly reason: string;
2702
+ readonly userAgent?: string;
1920
2703
  }
1921
- interface OrgScopedTokenResponse {
1922
- /** Org-scoped access token. */
1923
- token: string;
1924
- /** Org-scoped access token, matching the SDK's token naming convention. */
1925
- accessToken: string;
1926
- /** Token lifetime in seconds, when provided by the runtime. */
1927
- expiresIn?: number;
1928
- /** Bearer token type, when provided by the runtime. */
1929
- tokenType?: string;
1930
- /** User envelope returned by the runtime for session hydration. */
1931
- user?: User;
2704
+ interface ImpersonationChallenge {
2705
+ readonly requestId: string;
2706
+ readonly challengeKey: string;
2707
+ readonly webauthnOptions: {
2708
+ readonly challenge: string;
2709
+ readonly rpId?: string;
2710
+ readonly allowCredentials: ReadonlyArray<{
2711
+ readonly id: string;
2712
+ readonly type: 'public-key';
2713
+ readonly transports?: readonly string[];
2714
+ }>;
2715
+ readonly userVerification: 'required';
2716
+ readonly timeout: number;
2717
+ };
1932
2718
  }
1933
- /**
1934
- * Invite a user request payload.
1935
- */
1936
- interface InviteUserRequest {
1937
- email: string;
1938
- metadata?: Record<string, unknown>;
1939
- redirectUrl?: string;
2719
+ interface ImpersonationStartStepupInput {
2720
+ readonly baseUrl: string;
2721
+ readonly accessToken: string;
2722
+ readonly requestId: string;
2723
+ readonly challengeKey: string;
2724
+ readonly assertion: unknown;
2725
+ readonly emergencyBypass?: boolean;
2726
+ readonly userAgent?: string;
2727
+ }
2728
+ type ImpersonationStartStepupResult = {
2729
+ readonly branch: 'emergency';
2730
+ readonly requestId: string;
2731
+ readonly token: string;
2732
+ readonly sessionId: string;
2733
+ readonly expiresAt: string;
2734
+ } | {
2735
+ readonly branch: 'awaiting-consent';
2736
+ readonly requestId: string;
2737
+ readonly consentDeadline: string;
2738
+ };
2739
+ type ImpersonationConsentDecision = 'approve' | 'deny';
2740
+ type ImpersonationConsentResponse = {
2741
+ readonly branch: 'approved';
2742
+ readonly requestId: string;
2743
+ readonly token: string;
2744
+ readonly sessionId: string;
2745
+ readonly expiresAt: string;
2746
+ } | {
2747
+ readonly branch: 'denied';
2748
+ readonly requestId: string;
2749
+ };
2750
+ interface ImpersonationRequestRow {
2751
+ readonly id: string;
2752
+ readonly operatorId: string;
2753
+ readonly targetUserId: string;
2754
+ readonly reason: string;
2755
+ readonly status: 'awaiting-stepup' | 'awaiting-consent' | 'active' | 'denied' | 'expired' | 'ended' | 'revoked';
2756
+ readonly emergencyBypass: boolean;
2757
+ readonly sessionId: string | null;
2758
+ readonly consentDeadline: string | null;
2759
+ readonly startedAt: string | null;
2760
+ readonly endedAt: string | null;
2761
+ readonly createdAt: string;
1940
2762
  }
2763
+ declare const impersonation: {
2764
+ readonly start: (opts: {
2765
+ readonly baseUrl: string;
2766
+ readonly accessToken: string;
2767
+ readonly targetUserId: string;
2768
+ readonly ipAddress?: string;
2769
+ readonly userAgent?: string;
2770
+ }) => Promise<ImpersonationStartResult>;
2771
+ readonly end: (opts: {
2772
+ readonly baseUrl: string;
2773
+ readonly accessToken: string;
2774
+ readonly sessionId?: string;
2775
+ readonly userAgent?: string;
2776
+ }) => Promise<ImpersonationEndResult>;
2777
+ readonly info: (opts: {
2778
+ readonly baseUrl: string;
2779
+ readonly accessToken: string;
2780
+ readonly sessionId: string;
2781
+ readonly userAgent?: string;
2782
+ }) => Promise<ImpersonationInfo | null>;
2783
+ readonly active: (opts: {
2784
+ readonly baseUrl: string;
2785
+ readonly accessToken: string;
2786
+ readonly userAgent?: string;
2787
+ }) => Promise<readonly ImpersonationActive[]>;
2788
+ readonly startChallenge: (opts: ImpersonationStartChallengeInput) => Promise<ImpersonationChallenge>;
2789
+ readonly startStepup: (opts: ImpersonationStartStepupInput) => Promise<ImpersonationStartStepupResult>;
2790
+ readonly respondConsent: (opts: {
2791
+ readonly baseUrl: string;
2792
+ readonly accessToken: string;
2793
+ readonly requestId: string;
2794
+ readonly decision: ImpersonationConsentDecision;
2795
+ readonly userAgent?: string;
2796
+ }) => Promise<ImpersonationConsentResponse>;
2797
+ readonly listRequests: (opts: {
2798
+ readonly baseUrl: string;
2799
+ readonly accessToken: string;
2800
+ readonly filter?: {
2801
+ readonly operatorId?: string;
2802
+ readonly targetUserId?: string;
2803
+ readonly status?: ImpersonationRequestRow["status"];
2804
+ readonly limit?: number;
2805
+ };
2806
+ readonly userAgent?: string;
2807
+ }) => Promise<readonly ImpersonationRequestRow[]>;
2808
+ readonly endSession: (opts: {
2809
+ readonly baseUrl: string;
2810
+ readonly accessToken: string;
2811
+ readonly requestId: string;
2812
+ readonly userAgent?: string;
2813
+ }) => Promise<{
2814
+ success: true;
2815
+ requestId: string;
2816
+ sessionId: string | null;
2817
+ }>;
2818
+ };
2819
+
1941
2820
  /**
1942
- * Response from inviteUser.
2821
+ * Platform JWT verification and cookie-session resolution.
2822
+ *
2823
+ * This module owns the SDK's hot-path Platform auth helpers: cached JWKS
2824
+ * verification for bearer tokens and cached cookie-based user resolution.
1943
2825
  */
1944
- interface InviteUserResponse {
1945
- invitationToken: string;
1946
- expiresAt: string;
1947
- }
1948
2826
  /**
1949
- * Sign in with email and password
1950
- *
1951
- * @example
1952
- * ```typescript
1953
- * const result = await signIn(config, { email: 'user@example.com', password: 'secret' })
1954
- * if (result.requiresTwoFactor) {
1955
- * // Handle 2FA flow
1956
- * } else {
1957
- * // Save tokens
1958
- * const authenticatedConfig = withToken(config, result.accessToken!)
1959
- * }
1960
- * ```
2827
+ * Reset the platform-JWKS cache. Tests should call this between cases
2828
+ * to avoid state bleed. Production code relies on the TTL-based
2829
+ * expiry.
1961
2830
  */
1962
- declare function signIn(config: SylphxConfig, input: LoginRequest): Promise<LoginResponse>;
2831
+ declare function resetPlatformJwksCache(): void;
2832
+ interface PlatformAccessTokenClaims {
2833
+ readonly sub: string;
2834
+ readonly pid?: string;
2835
+ readonly email: string;
2836
+ readonly name?: string;
2837
+ readonly picture?: string;
2838
+ readonly email_verified: boolean;
2839
+ readonly app_id: string;
2840
+ readonly role: string;
2841
+ readonly org_id?: string;
2842
+ readonly org_slug?: string;
2843
+ readonly org_role?: string;
2844
+ readonly iat?: number;
2845
+ readonly exp?: number;
2846
+ /**
2847
+ * RFC 7800 confirmation claim — present when the token is sender-
2848
+ * constrained. Today we emit this for DPoP-bound tokens (RFC 9449)
2849
+ * where `cnf.jkt` is the SHA-256 thumbprint of the client's DPoP
2850
+ * public key.
2851
+ *
2852
+ * Resource servers (e.g. apps/api Management plane) that want to
2853
+ * enforce DPoP MUST:
2854
+ * 1. Look up `oauth_clients.dpop_bound_access_tokens` on the
2855
+ * issuing client to know whether DPoP is required.
2856
+ * 2. If required AND `cnf.jkt` is absent, reject 401.
2857
+ * 3. If `cnf.jkt` is present, verify the inbound `DPoP` header's
2858
+ * proof JWT and assert its public-key thumbprint matches `jkt`.
2859
+ *
2860
+ * Pre-Wave-5.3 this field was stripped from `verifyAccessToken`'s
2861
+ * return value, making resource-side enforcement impossible without
2862
+ * decoding the JWT a second time. Exposing it preserves the wire
2863
+ * format and unlocks the resource-server DPoP middleware.
2864
+ */
2865
+ readonly cnf?: {
2866
+ readonly jkt?: string;
2867
+ };
2868
+ }
1963
2869
  /**
1964
- * Sign up with email and password
2870
+ * `verifyAccessToken` local JWT verification against cached JWKS.
2871
+ *
2872
+ * Designed for the Platform API's hot-path auth middleware: JWKS is
2873
+ * fetched once per process (1h TTL), signature/iss/aud/exp
2874
+ * verification is local `jose` — no per-request HTTPS hop.
1965
2875
  *
1966
2876
  * @example
1967
2877
  * ```typescript
1968
- * const result = await signUp(config, {
1969
- * email: 'user@example.com',
1970
- * password: 'secret',
1971
- * name: 'John Doe',
2878
+ * const claims = await auth.verifyAccessToken(bearer, {
2879
+ * baseUrl: 'https://your-app.api.sylphx.com/v1',
2880
+ * audience: 'platform',
1972
2881
  * })
1973
- * // User needs to verify email
1974
2882
  * ```
1975
2883
  */
1976
- declare function signUp(config: SylphxConfig, input: RegisterRequest): Promise<RegisterResponse>;
2884
+ declare function verifyAccessToken(token: string, opts: {
2885
+ readonly baseUrl: string;
2886
+ readonly audience: string;
2887
+ }): Promise<PlatformAccessTokenClaims>;
2888
+ interface PlatformUserRecord {
2889
+ readonly id: string;
2890
+ readonly email: string;
2891
+ readonly name: string | null;
2892
+ readonly image: string | null;
2893
+ readonly emailVerified: boolean;
2894
+ readonly role: string;
2895
+ readonly twoFactorEnabled: boolean;
2896
+ }
2897
+ interface PlatformUserResolution {
2898
+ readonly user: PlatformUserRecord;
2899
+ readonly sessionId: string;
2900
+ }
2901
+ declare function resetPlatformCookieCache(): void;
1977
2902
  /**
1978
- * Sign out (revoke tokens)
1979
- *
1980
- * @example
1981
- * ```typescript
1982
- * await signOut(config)
1983
- * ```
2903
+ * `cookies` namespace Platform cookie / session resolution for the
2904
+ * Platform API's hot-path auth middleware (ADR-089 Phase 3b).
1984
2905
  */
1985
- declare function signOut(config: SylphxConfig): Promise<void>;
2906
+ declare const cookies: {
2907
+ /**
2908
+ * Resolve a platform user from a forwarded `Cookie:` header.
2909
+ *
2910
+ * Delegates to BaaS `/auth/platform-sessions/whoami`. Caches each
2911
+ * unique cookie string for 30s to avoid hammering BaaS on every
2912
+ * SSR request.
2913
+ *
2914
+ * @example
2915
+ * ```typescript
2916
+ * const result = await auth.cookies.resolvePlatformUser({
2917
+ * baseUrl: 'https://your-app.api.sylphx.com/v1',
2918
+ * cookieHeader: req.headers.get('cookie') ?? '',
2919
+ * })
2920
+ * if (!result) // unauthenticated
2921
+ * ```
2922
+ */
2923
+ readonly resolvePlatformUser: (opts: {
2924
+ readonly baseUrl: string;
2925
+ readonly cookieHeader: string;
2926
+ readonly userAgent?: string;
2927
+ }) => Promise<PlatformUserResolution | null>;
2928
+ };
2929
+
1986
2930
  /**
1987
- * Refresh access token
2931
+ * Platform OAuth namespace.
1988
2932
  *
1989
- * @example
1990
- * ```typescript
1991
- * const tokens = await refreshToken(config, refreshTokenString)
1992
- * const newConfig = withToken(config, tokens.accessToken)
1993
- * ```
2933
+ * Backs `auth.oauth.*` while keeping OAuth AS protocol handling out of the
2934
+ * monolithic auth module. Public exports are re-exported from `auth.ts`.
1994
2935
  */
1995
- declare function refreshToken(config: SylphxConfig, token: string): Promise<TokenResponse>;
2936
+
2937
+ type OAuthIntrospectResult = OAuthIntrospectResponse;
2938
+ interface MintAccessTokenClaims {
2939
+ readonly sub: string;
2940
+ readonly email: string;
2941
+ readonly name?: string;
2942
+ readonly email_verified: boolean;
2943
+ readonly app_id: string;
2944
+ readonly role: string;
2945
+ readonly org_id?: string;
2946
+ readonly org_slug?: string;
2947
+ readonly org_role?: string;
2948
+ readonly picture?: string;
2949
+ readonly pid?: string;
2950
+ }
2951
+ interface MintAccessTokenResult {
2952
+ readonly accessToken: string;
2953
+ readonly expiresIn: number;
2954
+ }
2955
+ interface OAuthClientCallOpts {
2956
+ readonly baseUrl: string;
2957
+ readonly clientId: string;
2958
+ readonly clientSecret?: string;
2959
+ readonly token: string;
2960
+ readonly tokenTypeHint?: 'access_token' | 'refresh_token';
2961
+ readonly userAgent?: string;
2962
+ }
1996
2963
  /**
1997
- * Verify email with token
2964
+ * `oauth` namespace Platform OAuth operations backed by BaaS.
1998
2965
  *
1999
- * @example
2000
- * ```typescript
2001
- * await verifyEmail(config, token)
2002
- * ```
2966
+ * Phase 3b adds `mintAccessToken` for the refresh handler migration;
2967
+ * Phase 5.1 layered in full authorization-server verbs
2968
+ * (`/oauth/token`, `/oauth/revoke`, `/oauth/introspect`).
2003
2969
  */
2004
- declare function verifyEmail(config: SylphxConfig, token: string): Promise<void>;
2970
+ declare const oauth: {
2971
+ /**
2972
+ * Mint a platform-audience access token from supplied claims.
2973
+ *
2974
+ * Service-to-service call — authenticated via
2975
+ * `SYLPHX_INTERNAL_TOKEN` shared secret until ADR-068's
2976
+ * SPIFFE SVID mTLS platform-auth flip makes workload identity the
2977
+ * only accepted internal caller credential.
2978
+ */
2979
+ readonly mintAccessToken: (opts: {
2980
+ readonly baseUrl: string;
2981
+ readonly internalToken: string;
2982
+ readonly claims: MintAccessTokenClaims;
2983
+ readonly userAgent?: string;
2984
+ }) => Promise<MintAccessTokenResult>;
2985
+ readonly exchangeAuthorizationCode: (opts: {
2986
+ readonly baseUrl: string;
2987
+ readonly clientId: string;
2988
+ readonly clientSecret?: string;
2989
+ readonly code: string;
2990
+ readonly redirectUri: string;
2991
+ readonly codeVerifier: string;
2992
+ }) => Promise<OAuthTokenResult>;
2993
+ readonly refreshAccessToken: (opts: {
2994
+ readonly baseUrl: string;
2995
+ readonly clientId: string;
2996
+ readonly clientSecret?: string;
2997
+ readonly refreshToken: string;
2998
+ readonly scope?: string;
2999
+ }) => Promise<OAuthTokenResult>;
3000
+ readonly pollDeviceToken: (opts: {
3001
+ readonly baseUrl: string;
3002
+ readonly clientId: string;
3003
+ readonly deviceCode: string;
3004
+ }) => Promise<OAuthPollResult>;
3005
+ readonly clientCredentialsToken: (opts: {
3006
+ readonly baseUrl: string;
3007
+ readonly clientId: string;
3008
+ readonly clientSecret: string;
3009
+ readonly scope?: string;
3010
+ }) => Promise<OAuthClientCredentialsResult>;
3011
+ readonly revokeToken: (opts: OAuthClientCallOpts) => Promise<void>;
3012
+ readonly introspectToken: (opts: OAuthClientCallOpts) => Promise<OAuthIntrospectResult>;
3013
+ };
3014
+
2005
3015
  /**
2006
- * Request password reset email
3016
+ * Platform password management SDK namespace.
2007
3017
  *
2008
- * @example
2009
- * ```typescript
2010
- * await forgotPassword(config, 'user@example.com', {
2011
- * redirectUrl: 'https://app.example.com/reset-password'
2012
- * })
2013
- * ```
3018
+ * Backed by `/auth/platform-password/*` on the BaaS runtime. Crypto
3019
+ * primitives and breach checks stay server-side; callers only pass tokens
3020
+ * and plaintext password inputs over the established HTTPS boundary.
2014
3021
  */
2015
- declare function forgotPassword(config: SylphxConfig, email: string, options?: {
2016
- redirectUrl?: string;
2017
- }): Promise<void>;
3022
+
3023
+ type PlatformPasswordStatusResult = PlatformPasswordStatusResponse;
3024
+ type PlatformPasswordSetInput = PlatformPasswordSetRequest;
3025
+ type PlatformPasswordSetResult = PlatformPasswordSetResponse;
3026
+ type PlatformPasswordChangeInput = PlatformPasswordChangeRequest;
3027
+ type PlatformPasswordChangeResult = PlatformPasswordChangeResponse;
3028
+ declare const password: {
3029
+ readonly status: (opts: {
3030
+ readonly baseUrl: string;
3031
+ readonly accessToken: string;
3032
+ readonly userAgent?: string;
3033
+ }) => Promise<PlatformPasswordStatusResult>;
3034
+ readonly set: (opts: {
3035
+ readonly baseUrl: string;
3036
+ readonly accessToken: string;
3037
+ readonly password: string;
3038
+ readonly userAgent?: string;
3039
+ }) => Promise<PlatformPasswordSetResult>;
3040
+ readonly change: (opts: {
3041
+ readonly baseUrl: string;
3042
+ readonly accessToken: string;
3043
+ readonly currentPassword: string;
3044
+ readonly newPassword: string;
3045
+ readonly userAgent?: string;
3046
+ }) => Promise<PlatformPasswordChangeResult>;
3047
+ };
3048
+
2018
3049
  /**
2019
- * Request a verification email resend.
3050
+ * Platform session management SDK namespace.
2020
3051
  *
2021
- * The Platform response is intentionally privacy-preserving: it never
2022
- * indicates whether the email exists or is already verified.
2023
- *
2024
- * @example
2025
- * ```typescript
2026
- * await resendVerificationEmail(config, 'user@example.com')
2027
- * ```
3052
+ * Backed by `/auth/platform-sessions/*` on the BaaS runtime. These helpers
3053
+ * accept platform-audience access tokens, not project `pk_`/`sk_` credentials.
2028
3054
  */
2029
- declare function resendVerificationEmail(config: SylphxConfig, email: string): Promise<void>;
2030
- /**
2031
- * Reset password with token
2032
- *
2033
- * @example
2034
- * ```typescript
2035
- * await resetPassword(config, { token, password: 'newpassword' })
2036
- * ```
2037
- */
2038
- declare function resetPassword(config: SylphxConfig, input: {
2039
- token: string;
2040
- password: string;
2041
- }): Promise<void>;
2042
- /**
2043
- * Get current session (requires authenticated config)
2044
- *
2045
- * @example
2046
- * ```typescript
2047
- * const session = await getSession(authenticatedConfig)
2048
- * if (session.user) {
2049
- * console.log(`Logged in as ${session.user.email}`)
2050
- * }
2051
- * ```
2052
- */
2053
- declare function getSession(config: SylphxConfig): Promise<SessionResult>;
2054
- /**
2055
- * Verify 2FA code (when signIn returns requiresTwoFactor: true)
2056
- *
2057
- * @example
2058
- * ```typescript
2059
- * const result = await signIn(config, credentials)
2060
- * if (result.requiresTwoFactor) {
2061
- * const tokens = await verifyTwoFactor(config, result.userId!, code)
2062
- * }
2063
- * ```
2064
- */
2065
- declare function verifyTwoFactor(config: SylphxConfig, userId: string, code: string): Promise<TokenResponse>;
2066
- /**
2067
- * Introspect a token to check its validity (RFC 7662)
2068
- *
2069
- * Use this to verify token status without decoding. Essential for:
2070
- * - Checking if a token has been revoked
2071
- * - Validating tokens at the edge
2072
- * - Security-critical operations
2073
- *
2074
- * @example
2075
- * ```typescript
2076
- * const result = await introspectToken(config, accessToken)
2077
- * if (!result.active) {
2078
- * // Token is invalid, revoked, or expired
2079
- * await refreshTokens()
2080
- * }
2081
- * ```
2082
- */
2083
- declare function introspectToken(config: SylphxConfig, token: string, tokenTypeHint?: 'access_token' | 'refresh_token'): Promise<TokenIntrospectionResult>;
2084
- /**
2085
- * Revoke a token (RFC 7009)
2086
- *
2087
- * Use cases:
2088
- * - Sign out user from specific device
2089
- * - Security response to compromised token
2090
- * - User-initiated session termination
2091
- *
2092
- * @example
2093
- * ```typescript
2094
- * // Revoke single refresh token
2095
- * await revokeToken(config, refreshToken)
2096
- *
2097
- * // Revoke all tokens for a user (logout everywhere)
2098
- * await revokeToken(config, '', { revokeAll: true, userId: 'user-123' })
2099
- * ```
2100
- */
2101
- declare function revokeToken(config: SylphxConfig, token: string, options?: RevokeTokenOptions): Promise<void>;
2102
- /**
2103
- * Revoke all tokens for a user (logout from all devices)
2104
- *
2105
- * Convenience wrapper around revokeToken with revokeAll option.
2106
- *
2107
- * @example
2108
- * ```typescript
2109
- * // After password change, revoke all sessions
2110
- * await revokeAllTokens(config, userId)
2111
- * ```
2112
- */
2113
- declare function revokeAllTokens(config: SylphxConfig, userId: string): Promise<void>;
2114
- /**
2115
- * Sign up with extended input (metadata + invitation token support).
2116
- *
2117
- * Use this instead of signUp() when you need to:
2118
- * - Pass metadata on registration (e.g., org context, role, referral info)
2119
- * - Register with an invitation token
2120
- *
2121
- * @example
2122
- * ```typescript
2123
- * const result = await extendedSignUp(config, {
2124
- * email: 'user@example.com',
2125
- * password: 'secret',
2126
- * name: 'John Doe',
2127
- * metadata: { orgId: 'org-123', role: 'employee' },
2128
- * invitationToken: 'inv_...',
2129
- * })
2130
- * ```
2131
- */
2132
- declare function extendedSignUp(config: SylphxConfig, input: RegisterInput): Promise<RegisterResponse>;
2133
- /**
2134
- * Invite a user to sign up for this project.
2135
- * Server-side only (requires secretKey).
2136
- * Sends an email invitation; user signs up via signUp() or extendedSignUp() with the invitation token.
2137
- *
2138
- * @example
2139
- * ```typescript
2140
- * const invite = await inviteUser(config, {
2141
- * email: 'newemployee@company.com',
2142
- * metadata: { role: 'employee', orgId: 'org-123' },
2143
- * redirectUrl: 'https://app.example.com/signup',
2144
- * })
2145
- * console.log(invite.invitationToken, invite.expiresAt)
2146
- * ```
2147
- */
2148
- declare function inviteUser(config: SylphxConfig, input: InviteUserRequest): Promise<InviteUserResponse>;
2149
- /**
2150
- * Exchange current user token for an org-scoped token.
2151
- * The returned access_token JWT includes org_id, org_slug, org_role claims.
2152
- *
2153
- * @example
2154
- * const { token } = await getOrgScopedToken(withToken(config, currentToken), 'org_xxx')
2155
- */
2156
- declare function getOrgScopedToken(config: SylphxConfig, orgId: string): Promise<OrgScopedTokenResponse>;
2157
- /**
2158
- * @deprecated Use getOrgScopedToken(config, orgId). Kept as the shorter
2159
- * organization switch alias for existing SDK callers.
2160
- */
2161
- declare function switchOrg(config: SylphxConfig, orgId: string): Promise<OrgScopedTokenResponse>;
2162
- type DeviceInitInput = DeviceInitRequest;
2163
- type DeviceGrant = DeviceInitResponse;
2164
- type DevicePollResult = DevicePollResponse;
2165
- type DeviceApproveInput = DeviceApproveRequest;
2166
- type DeviceApproveResult = DeviceApproveResponse;
2167
- type DeviceDenyInput = DeviceDenyRequest;
2168
- type DeviceDenyResult = DeviceDenyResponse;
2169
- /**
2170
- * `device` namespace — RFC 8628 device authorization grant.
2171
- *
2172
- * Used by headless clients (CLI, TV apps, IoT) to authorise via a
2173
- * companion browser instead of reading credentials from env vars.
2174
- */
2175
- declare const device: {
2176
- /**
2177
- * Start a device authorization grant.
2178
- *
2179
- * Returns a `DeviceGrant` with `verification_uri_complete` (open this
2180
- * in the user's browser) and `device_code` (use for polling).
2181
- *
2182
- * @example
2183
- * ```typescript
2184
- * const grant = await device.init({
2185
- * baseUrl: 'https://your-app.api.sylphx.com/v1',
2186
- * clientId: 'sylphx-cli',
2187
- * scope: ['org:read', 'project:*'],
2188
- * })
2189
- * openBrowser(grant.verification_uri_complete)
2190
- * ```
2191
- */
2192
- readonly init: (opts: {
2193
- readonly baseUrl: string;
2194
- readonly clientId: string;
2195
- readonly scope?: readonly string[];
2196
- readonly userAgent?: string;
2197
- }) => Promise<DeviceGrant>;
2198
- /**
2199
- * Poll a pending grant. Returns `status: 'pending' | 'approved' |
2200
- * 'denied' | 'expired'`. On `approved`, the result carries the OAuth
2201
- * pair (access_token + refresh_token).
2202
- *
2203
- * Callers MUST respect the `interval` returned by `init()` — polling
2204
- * faster than that may return 429 slow_down (RFC 8628 §5.5).
2205
- */
2206
- readonly poll: (opts: {
2207
- readonly baseUrl: string;
2208
- readonly deviceCode: string;
2209
- readonly userAgent?: string;
2210
- }) => Promise<DevicePollResult>;
2211
- /**
2212
- * Browser leg — the approving user confirms the grant.
2213
- *
2214
- * Requires a valid platform-issued access token (`Authorization:
2215
- * Bearer <accessToken>`) proving the user is logged in on the
2216
- * Console. Typically called by the Console's `/device` verification
2217
- * page server-side, forwarding the user's session JWT.
2218
- */
2219
- readonly approve: (opts: {
2220
- readonly baseUrl: string;
2221
- readonly userCode: string;
2222
- readonly accessToken: string;
2223
- readonly userAgent?: string;
2224
- }) => Promise<DeviceApproveResult>;
2225
- /**
2226
- * Browser leg — the user declines the grant.
2227
- *
2228
- * Requires a valid platform-issued access token just like `approve`.
2229
- */
2230
- readonly deny: (opts: {
2231
- readonly baseUrl: string;
2232
- readonly userCode: string;
2233
- readonly accessToken: string;
2234
- readonly userAgent?: string;
2235
- }) => Promise<DeviceDenyResult>;
2236
- };
2237
- type OAuthIntrospectResult = OAuthIntrospectResponse;
2238
- interface OAuthClientCallOpts {
2239
- readonly baseUrl: string;
2240
- readonly clientId: string;
2241
- readonly clientSecret?: string;
2242
- readonly token: string;
2243
- readonly tokenTypeHint?: 'access_token' | 'refresh_token';
2244
- readonly userAgent?: string;
2245
- }
3055
+
2246
3056
  type PlatformSessionsListResult = PlatformSessionsListResponse;
2247
3057
  type PlatformSessionRevokeInput = PlatformSessionRevokeRequest;
2248
3058
  type PlatformSessionRevokeResult = PlatformSessionRevokeResponse;
@@ -2250,110 +3060,28 @@ type PlatformSessionRevokeOtherResult = PlatformSessionRevokeOtherResponse;
2250
3060
  type PlatformSessionRevokeAllResult = PlatformSessionRevokeAllResponse;
2251
3061
  type PlatformSessionRenameInput = PlatformSessionRenameRequest;
2252
3062
  type PlatformSessionRenameResult = PlatformSessionRenameResponse;
2253
- /**
2254
- * `sessions` namespace — Platform-plane (Console / CLI) session
2255
- * management. Backed by `/auth/platform-sessions/*` on the BaaS
2256
- * runtime (ADR-089 Phase 2b). See module header for the full rationale.
2257
- */
2258
3063
  declare const sessions: {
2259
- /**
2260
- * List every active platform session for the authenticated user.
2261
- *
2262
- * Ordering: most-recently-active first.
2263
- *
2264
- * @example
2265
- * ```typescript
2266
- * const { sessions } = await auth.sessions.list({
2267
- * baseUrl: 'https://your-app.api.sylphx.com/v1',
2268
- * accessToken: platformJwt,
2269
- * })
2270
- * ```
2271
- */
2272
3064
  readonly list: (opts: {
2273
3065
  readonly baseUrl: string;
2274
3066
  readonly accessToken: string;
2275
3067
  readonly userAgent?: string;
2276
3068
  }) => Promise<PlatformSessionsListResult>;
2277
- /**
2278
- * Revoke a specific platform session by id.
2279
- *
2280
- * `sessionId` accepts either the prefixed TypeID (`sess_*`) or the
2281
- * raw UUID — the BaaS side normalises via `parseIdOrError`.
2282
- *
2283
- * @example
2284
- * ```typescript
2285
- * await auth.sessions.revoke({
2286
- * baseUrl,
2287
- * accessToken,
2288
- * sessionId: 'sess_01hxyz...',
2289
- * })
2290
- * ```
2291
- */
2292
3069
  readonly revoke: (opts: {
2293
3070
  readonly baseUrl: string;
2294
3071
  readonly accessToken: string;
2295
3072
  readonly sessionId: string;
2296
3073
  readonly userAgent?: string;
2297
3074
  }) => Promise<PlatformSessionRevokeResult>;
2298
- /**
2299
- * Revoke every platform session except the one presenting the
2300
- * current access token. Used by "sign me out of all other devices".
2301
- *
2302
- * When the caller's JWT has no `sid` claim (pure-Bearer CLI/CI
2303
- * flows), this degenerates to `revokeAll` — every session is
2304
- * wiped — because there's no "current" row to keep.
2305
- *
2306
- * @example
2307
- * ```typescript
2308
- * const { revokedCount } = await auth.sessions.revokeOther({
2309
- * baseUrl,
2310
- * accessToken,
2311
- * })
2312
- * ```
2313
- */
2314
3075
  readonly revokeOther: (opts: {
2315
3076
  readonly baseUrl: string;
2316
3077
  readonly accessToken: string;
2317
3078
  readonly userAgent?: string;
2318
3079
  }) => Promise<PlatformSessionRevokeOtherResult>;
2319
- /**
2320
- * Revoke every platform session for the user, including the
2321
- * caller's own. Used by "sign me out everywhere" — after a
2322
- * password change, a compromise scare, or GDPR-style erasure.
2323
- *
2324
- * The response includes the count of sessions that were
2325
- * revoked so the caller can surface it in a toast or audit UI.
2326
- *
2327
- * @example
2328
- * ```typescript
2329
- * const { count } = await auth.sessions.revokeAll({
2330
- * baseUrl,
2331
- * accessToken,
2332
- * })
2333
- * ```
2334
- */
2335
3080
  readonly revokeAll: (opts: {
2336
3081
  readonly baseUrl: string;
2337
3082
  readonly accessToken: string;
2338
3083
  readonly userAgent?: string;
2339
3084
  }) => Promise<PlatformSessionRevokeAllResult>;
2340
- /**
2341
- * Rename a platform session (device label).
2342
- *
2343
- * `sessionId` accepts either the prefixed TypeID or the raw UUID;
2344
- * `name` is a user-supplied string (≤100 chars) surfaced in the
2345
- * "Active sessions" Console UI.
2346
- *
2347
- * @example
2348
- * ```typescript
2349
- * await auth.sessions.rename({
2350
- * baseUrl,
2351
- * accessToken,
2352
- * sessionId,
2353
- * name: 'MacBook (work)',
2354
- * })
2355
- * ```
2356
- */
2357
3085
  readonly rename: (opts: {
2358
3086
  readonly baseUrl: string;
2359
3087
  readonly accessToken: string;
@@ -2362,148 +3090,14 @@ declare const sessions: {
2362
3090
  readonly userAgent?: string;
2363
3091
  }) => Promise<PlatformSessionRenameResult>;
2364
3092
  };
2365
- type PlatformRefreshInput = RefreshTokenInput;
2366
- type PlatformRefreshResult = RefreshTokenResult;
2367
- type PlatformLogoutInput = LogoutInput;
2368
- /**
2369
- * `platformAuth` namespace — Platform-plane refresh-token + logout
2370
- * operations for CLI / Console operators. Body-authenticated via the
2371
- * presented refresh token (no cookie, no Bearer).
2372
- */
2373
- declare const platformAuth: {
2374
- /**
2375
- * Rotate a Platform refresh token. The presented token is consumed
2376
- * single-use; the response carries a fresh access JWT plus the
2377
- * rotated refresh token that supersedes it.
2378
- *
2379
- * On reuse-detection / expiry the server returns 401 — the SDK
2380
- * preserves the upstream message so callers can pattern-match
2381
- * `"reuse"` per RFC 6819 §5.2.2.3 and scrub local credentials.
2382
- *
2383
- * @example
2384
- * ```typescript
2385
- * const tokens = await auth.platformAuth.refresh({
2386
- * baseUrl: 'https://sylphx.com',
2387
- * refreshToken: stored.refreshToken,
2388
- * })
2389
- * ```
2390
- */
2391
- readonly refresh: (opts: {
2392
- readonly baseUrl: string;
2393
- readonly refreshToken: string;
2394
- readonly userAgent?: string;
2395
- /**
2396
- * Path prefix between `baseUrl` and the resource path. Defaults
2397
- * to `/api/v1` for back-compat with the admin-override host
2398
- * (`sylphx.com`). Pass `/v1` when targeting the canonical host
2399
- * (`api.sylphx.com`) per Rule 17.
2400
- */
2401
- readonly urlPrefix?: string;
2402
- }) => Promise<PlatformRefreshResult>;
2403
- /**
2404
- * Revoke a Platform refresh token (logout). Server-side revocation
2405
- * failure is the caller's call to surface — local-credential cleanup
2406
- * is the CLI's responsibility (logout must succeed offline).
2407
- *
2408
- * @example
2409
- * ```typescript
2410
- * await auth.platformAuth.logout({
2411
- * baseUrl: 'https://sylphx.com',
2412
- * refreshToken: stored.refreshToken,
2413
- * })
2414
- * ```
2415
- */
2416
- readonly logout: (opts: {
2417
- readonly baseUrl: string;
2418
- readonly refreshToken: string;
2419
- readonly userAgent?: string;
2420
- /** See `refresh.urlPrefix`. */
2421
- readonly urlPrefix?: string;
2422
- }) => Promise<void>;
2423
- };
2424
- type PlatformPasswordStatusResult = PlatformPasswordStatusResponse;
2425
- type PlatformPasswordSetInput = PlatformPasswordSetRequest;
2426
- type PlatformPasswordSetResult = PlatformPasswordSetResponse;
2427
- type PlatformPasswordChangeInput = PlatformPasswordChangeRequest;
2428
- type PlatformPasswordChangeResult = PlatformPasswordChangeResponse;
3093
+
2429
3094
  /**
2430
- * `password` namespace Platform-plane (Console / CLI) password
2431
- * management. Backed by `/auth/platform-password/*` on the BaaS
2432
- * runtime (ADR-089 Phase 2c). See module header for the full rationale.
3095
+ * Platform user GDPR export and erasure SDK namespace.
3096
+ *
3097
+ * These helpers are backed by `/auth/platform-user/*` on the BaaS runtime
3098
+ * and keep account data operations separate from generic auth/session helpers.
2433
3099
  */
2434
- declare const password: {
2435
- /**
2436
- * Check whether the authenticated platform user has a password set.
2437
- *
2438
- * Returns `{ hasPassword: true }` for users that signed up with
2439
- * email+password (or later called `set`), `{ hasPassword: false }`
2440
- * for OAuth-only users (e.g. signed up via Google/GitHub).
2441
- *
2442
- * @example
2443
- * ```typescript
2444
- * const { hasPassword } = await auth.password.status({
2445
- * baseUrl: 'https://your-app.api.sylphx.com/v1',
2446
- * accessToken: platformJwt,
2447
- * })
2448
- * ```
2449
- */
2450
- readonly status: (opts: {
2451
- readonly baseUrl: string;
2452
- readonly accessToken: string;
2453
- readonly userAgent?: string;
2454
- }) => Promise<PlatformPasswordStatusResult>;
2455
- /**
2456
- * Set an initial password for an OAuth-only user.
2457
- *
2458
- * Fails with 400 if the user already has a password (use `change`
2459
- * instead), if the password is <8 characters, or if HIBP reports
2460
- * the password as breached. BaaS invalidates every other session
2461
- * for the user (keeping the caller's current one) after a
2462
- * successful set.
2463
- *
2464
- * @example
2465
- * ```typescript
2466
- * await auth.password.set({
2467
- * baseUrl,
2468
- * accessToken,
2469
- * password: 'correct-horse-battery-staple',
2470
- * })
2471
- * ```
2472
- */
2473
- readonly set: (opts: {
2474
- readonly baseUrl: string;
2475
- readonly accessToken: string;
2476
- readonly password: string;
2477
- readonly userAgent?: string;
2478
- }) => Promise<PlatformPasswordSetResult>;
2479
- /**
2480
- * Change an existing password.
2481
- *
2482
- * Verifies `currentPassword` server-side; a mismatch returns 401.
2483
- * OAuth-only users (no existing password) get 400 — use `set`
2484
- * instead. New password must be ≥8 characters and must not be in
2485
- * HIBP's breach database. BaaS invalidates every other session
2486
- * for the user (keeping the caller's current one) after a
2487
- * successful change.
2488
- *
2489
- * @example
2490
- * ```typescript
2491
- * await auth.password.change({
2492
- * baseUrl,
2493
- * accessToken,
2494
- * currentPassword: 'old-plaintext',
2495
- * newPassword: 'new-plaintext',
2496
- * })
2497
- * ```
2498
- */
2499
- readonly change: (opts: {
2500
- readonly baseUrl: string;
2501
- readonly accessToken: string;
2502
- readonly currentPassword: string;
2503
- readonly newPassword: string;
2504
- readonly userAgent?: string;
2505
- }) => Promise<PlatformPasswordChangeResult>;
2506
- };
3100
+
2507
3101
  type PlatformUserExportResult = AuthUserExportResponse;
2508
3102
  type PlatformUserDeleteInput = AuthUserDeleteRequest;
2509
3103
  type PlatformUserDeleteResult = AuthUserDeleteResponse;
@@ -2521,15 +3115,6 @@ declare const user: {
2521
3115
  * row, sessions, OAuth accounts, login history, security alerts,
2522
3116
  * organization memberships, subscriptions, per-project memberships,
2523
3117
  * and storage file metadata. Shape varies with customer provisioning.
2524
- *
2525
- * @example
2526
- * ```typescript
2527
- * const data = await auth.user.exportData({
2528
- * baseUrl: 'https://your-app.api.sylphx.com/v1',
2529
- * accessToken: platformJwt,
2530
- * })
2531
- * downloadAsJson(data, 'my-sylphx-data.json')
2532
- * ```
2533
3118
  */
2534
3119
  readonly exportData: (opts: {
2535
3120
  readonly baseUrl: string;
@@ -2540,29 +3125,7 @@ declare const user: {
2540
3125
  * Permanently delete the authenticated user's account (GDPR Article
2541
3126
  * 17 — right to erasure). Cascades through every provisioned project
2542
3127
  * DB, cancels Stripe subscriptions, deletes S3 blobs, and anonymises
2543
- * billing transactions. Emits a `user.deleted` event so downstream
2544
- * systems can clean up their own state.
2545
- *
2546
- * Returns `{ success: true, deletedData: [...] }` on success where
2547
- * `deletedData` lists the resource kinds that were erased.
2548
- *
2549
- * @remarks
2550
- * This operation is irreversible. Production callers SHOULD require
2551
- * a challenge step (2FA / password confirm / WebAuthn) before
2552
- * invoking this — the BaaS route does NOT perform challenge
2553
- * verification in Phase 2d. ADR-089 Phase 5.11 lands passkey-primary
2554
- * with WebAuthn-required step-up and will add the check at the
2555
- * BaaS boundary.
2556
- *
2557
- * @example
2558
- * ```typescript
2559
- * const result = await auth.user.deleteAccount({
2560
- * baseUrl,
2561
- * accessToken,
2562
- * reason: 'user_request',
2563
- * })
2564
- * if (result.success) signOutAndRedirect('/goodbye')
2565
- * ```
3128
+ * billing transactions.
2566
3129
  */
2567
3130
  readonly deleteAccount: (opts: {
2568
3131
  readonly baseUrl: string;
@@ -2573,35 +3136,13 @@ declare const user: {
2573
3136
  /**
2574
3137
  * Async GDPR Article 20 export job API (ADR-089 Phase 5.5).
2575
3138
  *
2576
- * `user.exportData` above is the Phase 2d synchronous shortcut
2577
- * kept for backward compat but production callers SHOULD prefer the
2578
- * async flow: large users routinely exceed a single HTTP deadline
2579
- * during enumeration.
2580
- *
2581
- * Typical flow:
2582
- *
2583
- * ```ts
2584
- * const job = await auth.user.exports.initiate({ baseUrl, accessToken })
2585
- * // Poll until terminal:
2586
- * while (true) {
2587
- * const cur = await auth.user.exports.status({ baseUrl, accessToken, id: job.id })
2588
- * if (cur.status === 'complete') break
2589
- * if (cur.status === 'failed') throw new Error(cur.errorMessage ?? 'export failed')
2590
- * await new Promise(r => setTimeout(r, 2000))
2591
- * }
2592
- * const blob = await auth.user.exports.download({ baseUrl, accessToken, id: job.id })
2593
- * saveAs(blob, 'sylphx-export.json')
2594
- * ```
2595
- *
2596
- * Rate limit: 1 `initiate` per 24h per user. Polling + downloading
2597
- * are NOT rate-limited through that bucket (they're cheap reads).
3139
+ * `user.exportData` is the Phase 2d synchronous shortcut; production
3140
+ * callers should prefer the async flow for large accounts.
2598
3141
  */
2599
3142
  readonly exports: {
2600
3143
  /**
2601
- * Kick off an export job. Returns the job row in `pending` status
2602
- * with a 202-Accepted semantic — the HTTP layer has accepted the
2603
- * request but the payload is not yet materialized. Poll
2604
- * `status({ id })` until `status === 'complete'`.
3144
+ * Kick off an export job. Poll `status({ id })` until
3145
+ * `status === 'complete'`.
2605
3146
  */
2606
3147
  readonly initiate: (opts: {
2607
3148
  readonly baseUrl: string;
@@ -2611,9 +3152,6 @@ declare const user: {
2611
3152
  }) => Promise<DataExportJob>;
2612
3153
  /**
2613
3154
  * Read the current state of an in-flight or completed export job.
2614
- * Returns 404 (via thrown `SylphxError`) if the job id is unknown
2615
- * OR owned by a different user — cross-user probes can't
2616
- * distinguish the two.
2617
3155
  */
2618
3156
  readonly status: (opts: {
2619
3157
  readonly baseUrl: string;
@@ -2623,12 +3161,8 @@ declare const user: {
2623
3161
  }) => Promise<DataExportJob>;
2624
3162
  /**
2625
3163
  * Download the completed export payload. The BaaS route returns a
2626
- * 302 to a freshly-signed object-storage URL; we follow the redirect
2627
- * (standard `fetch` default) and resolve to the raw `Blob`.
2628
- *
2629
- * The integrity headers `X-Sylphx-Export-Sha256` + `X-Sylphx-Export-Size`
2630
- * are available on the final response — CLI consumers SHOULD verify
2631
- * the SHA-256 client-side before handing the archive to the user.
3164
+ * 302 to a freshly-signed object-storage URL; `fetch` follows it
3165
+ * and resolves to the raw `Blob`.
2632
3166
  */
2633
3167
  readonly download: (opts: {
2634
3168
  readonly baseUrl: string;
@@ -2643,617 +3177,444 @@ declare const user: {
2643
3177
  };
2644
3178
  };
2645
3179
  /**
2646
- * Wire shape of a data-export job. `status` progresses through
2647
- * pending → running → (complete|failed); terminal rows carry `completedAt`,
2648
- * complete rows additionally carry `sizeBytes` + `sha256`, failed rows
2649
- * carry `errorMessage`. `downloadUrl` is always null in this projection
2650
- * — use `user.exports.download()` to obtain a freshly-signed URL.
3180
+ * Wire shape of a data-export job. `status` progresses through pending,
3181
+ * running, complete, or failed.
3182
+ */
3183
+ interface DataExportJob {
3184
+ readonly id: string;
3185
+ readonly status: 'pending' | 'running' | 'complete' | 'failed';
3186
+ readonly format: 'json' | 'json-ld';
3187
+ readonly requestedAt: string;
3188
+ readonly completedAt: string | null;
3189
+ readonly downloadUrl: string | null;
3190
+ readonly sizeBytes: number | null;
3191
+ readonly sha256: string | null;
3192
+ readonly errorMessage: string | null;
3193
+ }
3194
+
3195
+ /**
3196
+ * Auth Functions
3197
+ *
3198
+ * Pure functions for authentication - no hidden state.
3199
+ * Each function takes config as the first parameter.
3200
+ *
3201
+ * Uses REST API at /api/sdk/auth/* for all operations.
3202
+ *
3203
+ * Types are re-exported from `@sylphx/contract` (ADR-084). The contract is
3204
+ * the single source of truth for every wire shape — this module only adds
3205
+ * SDK-specific ergonomics (User brand swap, introspection result, invite
3206
+ * envelopes, org-token claims).
3207
+ */
3208
+
3209
+ type LoginRequest = LoginRequest$1;
3210
+ type LoginResponse = LoginResponse$1;
3211
+ type RegisterRequest = RegisterRequest$1;
3212
+ type RegisterResponse = RegisterResponse$1;
3213
+ type ResendEmailVerificationRequest = ResendEmailVerificationRequest$1;
3214
+ type ResendEmailVerificationResponse = ResendEmailVerificationResponse$1;
3215
+ /**
3216
+ * Token response — contract's `AuthTokensResponse.user` (optional `AuthUser`)
3217
+ * is re-mapped to the SDK's broader `User` type so legacy callers keep the
3218
+ * familiar brand. `AuthUser` and `User` are structurally identical, but
3219
+ * the SDK surface has wider reach (cookies, middleware, React hooks) and
3220
+ * renaming is out of scope for ADR-084 cleanup.
3221
+ */
3222
+ type TokenResponse = Omit<AuthTokensResponse, 'user'> & {
3223
+ user: User;
3224
+ };
3225
+ type TwoFactorVerifyRequest = TwoFactorVerifyRequest$1;
3226
+ /**
3227
+ * `GET /auth/me` — contract's `UserFullProfile` already includes the
3228
+ * optional `emailVerified` flag the backend returns, so the SDK can just
3229
+ * alias the contract type directly.
3230
+ */
3231
+ type MeResponse = UserFullProfile$1;
3232
+ /**
3233
+ * Token introspection result (RFC 7662)
3234
+ */
3235
+ interface TokenIntrospectionResult {
3236
+ /** Whether the token is active/valid */
3237
+ active: boolean;
3238
+ /** Token type (access_token or refresh_token) */
3239
+ token_type?: 'access_token' | 'refresh_token';
3240
+ /** User ID */
3241
+ sub?: string;
3242
+ /** User email */
3243
+ email?: string;
3244
+ /** User name */
3245
+ name?: string;
3246
+ /** App ID */
3247
+ client_id?: string;
3248
+ /** Audience */
3249
+ aud?: string;
3250
+ /** Issuer */
3251
+ iss?: string;
3252
+ /** Expiration time (Unix timestamp) */
3253
+ exp?: number;
3254
+ /** Issued at time (Unix timestamp) */
3255
+ iat?: number;
3256
+ /** User role */
3257
+ role?: string;
3258
+ /** Email verification status */
3259
+ email_verified?: boolean;
3260
+ }
3261
+ /**
3262
+ * Token revocation options
3263
+ */
3264
+ interface RevokeTokenOptions {
3265
+ /** Revoke all tokens for a user in this app */
3266
+ revokeAll?: boolean;
3267
+ /** User ID (required when revoking all) */
3268
+ userId?: string;
3269
+ }
3270
+ interface SessionResult {
3271
+ user: {
3272
+ id: string;
3273
+ email: string;
3274
+ name: string | null;
3275
+ image: string | null;
3276
+ emailVerified: boolean;
3277
+ } | null;
3278
+ }
3279
+ /**
3280
+ * Extended registration input with metadata and invitation token support.
3281
+ * Use extendedSignUp() when you need to pass metadata or an invitation token.
3282
+ */
3283
+ interface RegisterInput {
3284
+ email: string;
3285
+ password: string;
3286
+ name?: string;
3287
+ metadata?: Record<string, unknown>;
3288
+ invitationToken?: string;
3289
+ }
3290
+ /**
3291
+ * Org context claims present in org-scoped tokens (after switch-org).
3292
+ *
3293
+ * The JWT carries the role key only. Permissions are resolved server-side
3294
+ * via cached role→permissions lookup (WorkOS pattern). This keeps
3295
+ * tokens small and ensures permission changes take effect without token refresh.
3296
+ */
3297
+ interface OrgTokenPayload {
3298
+ org_id: string;
3299
+ org_slug: string;
3300
+ /** RBAC role key (e.g. "hr_manager", "admin"). Permissions resolved server-side. */
3301
+ org_role: string;
3302
+ }
3303
+ interface OrgScopedTokenResponse {
3304
+ /** Org-scoped access token. */
3305
+ token: string;
3306
+ /** Org-scoped access token, matching the SDK's token naming convention. */
3307
+ accessToken: string;
3308
+ /** Token lifetime in seconds, when provided by the runtime. */
3309
+ expiresIn?: number;
3310
+ /** Bearer token type, when provided by the runtime. */
3311
+ tokenType?: string;
3312
+ /** User envelope returned by the runtime for session hydration. */
3313
+ user?: User;
3314
+ }
3315
+ /**
3316
+ * Invite a user request payload.
3317
+ */
3318
+ interface InviteUserRequest {
3319
+ email: string;
3320
+ metadata?: Record<string, unknown>;
3321
+ redirectUrl?: string;
3322
+ }
3323
+ /**
3324
+ * Response from inviteUser.
3325
+ */
3326
+ interface InviteUserResponse {
3327
+ invitationToken: string;
3328
+ expiresAt: string;
3329
+ }
3330
+ /**
3331
+ * Sign in with email and password
3332
+ *
3333
+ * @example
3334
+ * ```typescript
3335
+ * const result = await signIn(config, { email: 'user@example.com', password: 'secret' })
3336
+ * if (result.requiresTwoFactor) {
3337
+ * // Handle 2FA flow
3338
+ * } else {
3339
+ * // Save tokens
3340
+ * const authenticatedConfig = withToken(config, result.accessToken!)
3341
+ * }
3342
+ * ```
3343
+ */
3344
+ declare function signIn(config: SylphxConfig, input: LoginRequest): Promise<LoginResponse>;
3345
+ /**
3346
+ * Sign up with email and password
3347
+ *
3348
+ * @example
3349
+ * ```typescript
3350
+ * const result = await signUp(config, {
3351
+ * email: 'user@example.com',
3352
+ * password: 'secret',
3353
+ * name: 'John Doe',
3354
+ * })
3355
+ * // User needs to verify email
3356
+ * ```
3357
+ */
3358
+ declare function signUp(config: SylphxConfig, input: RegisterRequest): Promise<RegisterResponse>;
3359
+ /**
3360
+ * Sign out (revoke tokens)
3361
+ *
3362
+ * @example
3363
+ * ```typescript
3364
+ * await signOut(config)
3365
+ * ```
3366
+ */
3367
+ declare function signOut(config: SylphxConfig): Promise<void>;
3368
+ /**
3369
+ * Refresh access token
3370
+ *
3371
+ * @example
3372
+ * ```typescript
3373
+ * const tokens = await refreshToken(config, refreshTokenString)
3374
+ * const newConfig = withToken(config, tokens.accessToken)
3375
+ * ```
3376
+ */
3377
+ declare function refreshToken(config: SylphxConfig, token: string): Promise<TokenResponse>;
3378
+ /**
3379
+ * Verify email with token
3380
+ *
3381
+ * @example
3382
+ * ```typescript
3383
+ * await verifyEmail(config, token)
3384
+ * ```
3385
+ */
3386
+ declare function verifyEmail(config: SylphxConfig, token: string): Promise<void>;
3387
+ /**
3388
+ * Request password reset email
3389
+ *
3390
+ * @example
3391
+ * ```typescript
3392
+ * await forgotPassword(config, 'user@example.com', {
3393
+ * redirectUrl: 'https://app.example.com/reset-password'
3394
+ * })
3395
+ * ```
3396
+ */
3397
+ declare function forgotPassword(config: SylphxConfig, email: string, options?: {
3398
+ redirectUrl?: string;
3399
+ }): Promise<void>;
3400
+ /**
3401
+ * Request a verification email resend.
3402
+ *
3403
+ * The Platform response is intentionally privacy-preserving: it never
3404
+ * indicates whether the email exists or is already verified.
3405
+ *
3406
+ * @example
3407
+ * ```typescript
3408
+ * await resendVerificationEmail(config, 'user@example.com')
3409
+ * ```
3410
+ */
3411
+ declare function resendVerificationEmail(config: SylphxConfig, email: string): Promise<void>;
3412
+ /**
3413
+ * Reset password with token
3414
+ *
3415
+ * @example
3416
+ * ```typescript
3417
+ * await resetPassword(config, { token, password: 'newpassword' })
3418
+ * ```
3419
+ */
3420
+ declare function resetPassword(config: SylphxConfig, input: {
3421
+ token: string;
3422
+ password: string;
3423
+ }): Promise<void>;
3424
+ /**
3425
+ * Get current session (requires authenticated config)
3426
+ *
3427
+ * @example
3428
+ * ```typescript
3429
+ * const session = await getSession(authenticatedConfig)
3430
+ * if (session.user) {
3431
+ * console.log(`Logged in as ${session.user.email}`)
3432
+ * }
3433
+ * ```
3434
+ */
3435
+ declare function getSession(config: SylphxConfig): Promise<SessionResult>;
3436
+ /**
3437
+ * Verify 2FA code (when signIn returns requiresTwoFactor: true)
3438
+ *
3439
+ * @example
3440
+ * ```typescript
3441
+ * const result = await signIn(config, credentials)
3442
+ * if (result.requiresTwoFactor) {
3443
+ * const tokens = await verifyTwoFactor(config, result.userId!, code)
3444
+ * }
3445
+ * ```
3446
+ */
3447
+ declare function verifyTwoFactor(config: SylphxConfig, userId: string, code: string): Promise<TokenResponse>;
3448
+ /**
3449
+ * Introspect a token to check its validity (RFC 7662)
3450
+ *
3451
+ * Use this to verify token status without decoding. Essential for:
3452
+ * - Checking if a token has been revoked
3453
+ * - Validating tokens at the edge
3454
+ * - Security-critical operations
3455
+ *
3456
+ * @example
3457
+ * ```typescript
3458
+ * const result = await introspectToken(config, accessToken)
3459
+ * if (!result.active) {
3460
+ * // Token is invalid, revoked, or expired
3461
+ * await refreshTokens()
3462
+ * }
3463
+ * ```
3464
+ */
3465
+ declare function introspectToken(config: SylphxConfig, token: string, tokenTypeHint?: 'access_token' | 'refresh_token'): Promise<TokenIntrospectionResult>;
3466
+ /**
3467
+ * Revoke a token (RFC 7009)
3468
+ *
3469
+ * Use cases:
3470
+ * - Sign out user from specific device
3471
+ * - Security response to compromised token
3472
+ * - User-initiated session termination
3473
+ *
3474
+ * @example
3475
+ * ```typescript
3476
+ * // Revoke single refresh token
3477
+ * await revokeToken(config, refreshToken)
3478
+ *
3479
+ * // Revoke all tokens for a user (logout everywhere)
3480
+ * await revokeToken(config, '', { revokeAll: true, userId: 'user-123' })
3481
+ * ```
2651
3482
  */
2652
- interface DataExportJob {
2653
- readonly id: string;
2654
- readonly status: 'pending' | 'running' | 'complete' | 'failed';
2655
- readonly format: 'json' | 'json-ld';
2656
- readonly requestedAt: string;
2657
- readonly completedAt: string | null;
2658
- readonly downloadUrl: string | null;
2659
- readonly sizeBytes: number | null;
2660
- readonly sha256: string | null;
2661
- readonly errorMessage: string | null;
2662
- }
3483
+ declare function revokeToken(config: SylphxConfig, token: string, options?: RevokeTokenOptions): Promise<void>;
2663
3484
  /**
2664
- * Reset the platform-JWKS cache. Tests should call this between cases
2665
- * to avoid state bleed. Production code relies on the TTL-based
2666
- * expiry.
3485
+ * Revoke all tokens for a user (logout from all devices)
3486
+ *
3487
+ * Convenience wrapper around revokeToken with revokeAll option.
3488
+ *
3489
+ * @example
3490
+ * ```typescript
3491
+ * // After password change, revoke all sessions
3492
+ * await revokeAllTokens(config, userId)
3493
+ * ```
2667
3494
  */
2668
- declare function resetPlatformJwksCache(): void;
2669
- interface PlatformAccessTokenClaims {
2670
- readonly sub: string;
2671
- readonly pid?: string;
2672
- readonly email: string;
2673
- readonly name?: string;
2674
- readonly picture?: string;
2675
- readonly email_verified: boolean;
2676
- readonly app_id: string;
2677
- readonly role: string;
2678
- readonly org_id?: string;
2679
- readonly org_slug?: string;
2680
- readonly org_role?: string;
2681
- readonly iat?: number;
2682
- readonly exp?: number;
2683
- /**
2684
- * RFC 7800 confirmation claim — present when the token is sender-
2685
- * constrained. Today we emit this for DPoP-bound tokens (RFC 9449)
2686
- * where `cnf.jkt` is the SHA-256 thumbprint of the client's DPoP
2687
- * public key.
2688
- *
2689
- * Resource servers (e.g. apps/api Management plane) that want to
2690
- * enforce DPoP MUST:
2691
- * 1. Look up `oauth_clients.dpop_bound_access_tokens` on the
2692
- * issuing client to know whether DPoP is required.
2693
- * 2. If required AND `cnf.jkt` is absent, reject 401.
2694
- * 3. If `cnf.jkt` is present, verify the inbound `DPoP` header's
2695
- * proof JWT and assert its public-key thumbprint matches `jkt`.
2696
- *
2697
- * Pre-Wave-5.3 this field was stripped from `verifyAccessToken`'s
2698
- * return value, making resource-side enforcement impossible without
2699
- * decoding the JWT a second time. Exposing it preserves the wire
2700
- * format and unlocks the resource-server DPoP middleware.
2701
- */
2702
- readonly cnf?: {
2703
- readonly jkt?: string;
2704
- };
2705
- }
3495
+ declare function revokeAllTokens(config: SylphxConfig, userId: string): Promise<void>;
2706
3496
  /**
2707
- * `verifyAccessToken` local JWT verification against cached JWKS.
3497
+ * Sign up with extended input (metadata + invitation token support).
2708
3498
  *
2709
- * Designed for the Platform API's hot-path auth middleware: JWKS is
2710
- * fetched once per process (1h TTL), signature/iss/aud/exp
2711
- * verification is local `jose` no per-request HTTPS hop.
3499
+ * Use this instead of signUp() when you need to:
3500
+ * - Pass metadata on registration (e.g., org context, role, referral info)
3501
+ * - Register with an invitation token
2712
3502
  *
2713
3503
  * @example
2714
3504
  * ```typescript
2715
- * const claims = await auth.verifyAccessToken(bearer, {
2716
- * baseUrl: 'https://your-app.api.sylphx.com/v1',
2717
- * audience: 'platform',
3505
+ * const result = await extendedSignUp(config, {
3506
+ * email: 'user@example.com',
3507
+ * password: 'secret',
3508
+ * name: 'John Doe',
3509
+ * metadata: { orgId: 'org-123', role: 'employee' },
3510
+ * invitationToken: 'inv_...',
2718
3511
  * })
2719
3512
  * ```
2720
3513
  */
2721
- declare function verifyAccessToken(token: string, opts: {
2722
- readonly baseUrl: string;
2723
- readonly audience: string;
2724
- }): Promise<PlatformAccessTokenClaims>;
2725
- interface PlatformUserRecord {
2726
- readonly id: string;
2727
- readonly email: string;
2728
- readonly name: string | null;
2729
- readonly image: string | null;
2730
- readonly emailVerified: boolean;
2731
- readonly role: string;
2732
- readonly twoFactorEnabled: boolean;
2733
- }
2734
- interface PlatformUserResolution {
2735
- readonly user: PlatformUserRecord;
2736
- readonly sessionId: string;
2737
- }
2738
- declare function resetPlatformCookieCache(): void;
3514
+ declare function extendedSignUp(config: SylphxConfig, input: RegisterInput): Promise<RegisterResponse>;
2739
3515
  /**
2740
- * `cookies` namespace Platform cookie / session resolution for the
2741
- * Platform API's hot-path auth middleware (ADR-089 Phase 3b).
3516
+ * Invite a user to sign up for this project.
3517
+ * Server-side only (requires secretKey).
3518
+ * Sends an email invitation; user signs up via signUp() or extendedSignUp() with the invitation token.
3519
+ *
3520
+ * @example
3521
+ * ```typescript
3522
+ * const invite = await inviteUser(config, {
3523
+ * email: 'newemployee@company.com',
3524
+ * metadata: { role: 'employee', orgId: 'org-123' },
3525
+ * redirectUrl: 'https://app.example.com/signup',
3526
+ * })
3527
+ * console.log(invite.invitationToken, invite.expiresAt)
3528
+ * ```
2742
3529
  */
2743
- declare const cookies: {
2744
- /**
2745
- * Resolve a platform user from a forwarded `Cookie:` header.
2746
- *
2747
- * Delegates to BaaS `/auth/platform-sessions/whoami`. Caches each
2748
- * unique cookie string for 30s to avoid hammering BaaS on every
2749
- * SSR request.
2750
- *
2751
- * @example
2752
- * ```typescript
2753
- * const result = await auth.cookies.resolvePlatformUser({
2754
- * baseUrl: 'https://your-app.api.sylphx.com/v1',
2755
- * cookieHeader: req.headers.get('cookie') ?? '',
2756
- * })
2757
- * if (!result) // unauthenticated
2758
- * ```
2759
- */
2760
- readonly resolvePlatformUser: (opts: {
2761
- readonly baseUrl: string;
2762
- readonly cookieHeader: string;
2763
- readonly userAgent?: string;
2764
- }) => Promise<PlatformUserResolution | null>;
2765
- };
2766
- interface MintAccessTokenClaims {
2767
- readonly sub: string;
2768
- readonly email: string;
2769
- readonly name?: string;
2770
- readonly email_verified: boolean;
2771
- readonly app_id: string;
2772
- readonly role: string;
2773
- readonly org_id?: string;
2774
- readonly org_slug?: string;
2775
- readonly org_role?: string;
2776
- readonly picture?: string;
2777
- readonly pid?: string;
2778
- }
2779
- interface MintAccessTokenResult {
2780
- readonly accessToken: string;
2781
- readonly expiresIn: number;
2782
- }
3530
+ declare function inviteUser(config: SylphxConfig, input: InviteUserRequest): Promise<InviteUserResponse>;
2783
3531
  /**
2784
- * `oauth` namespace Platform OAuth operations backed by BaaS.
2785
- *
2786
- * Phase 3b adds `mintAccessToken` for the refresh handler migration;
2787
- * Phase 5.1 layered in full authorization-server verbs
2788
- * (`/oauth/token`, `/oauth/revoke`, `/oauth/introspect`).
3532
+ * Exchange current user token for an org-scoped token.
3533
+ * The returned access_token JWT includes org_id, org_slug, org_role claims.
2789
3534
  *
2790
- * TODO(ADR-084-wave-5): migrate `exchangeAuthorizationCode` +
2791
- * `refreshAccessToken` off raw `fetch` onto the `@sylphx/contract` schema
2792
- * pipeline. The OAuth endpoints are new (not migrations of existing
2793
- * `@hono/zod-openapi` routes), so they can land contract-first without
2794
- * rippling into the other 62 hand-written SDK modules the baseline
2795
- * tracks. Blocked on Wave 5 scoping (contract-package OAuth schemas
2796
- * need to model the RFC 6749 error envelope + PKCE/DPoP binding — see
2797
- * packages/contract/src/endpoints/auth.ts for the existing auth-domain
2798
- * precedent). Until then, these two methods stay on explicit fetch().
3535
+ * @example
3536
+ * const { token } = await getOrgScopedToken(withToken(config, currentToken), 'org_xxx')
2799
3537
  */
2800
- declare const oauth: {
2801
- /**
2802
- * Mint a platform-audience access token from supplied claims.
2803
- *
2804
- * Service-to-service call — authenticated via
2805
- * `SYLPHX_INTERNAL_TOKEN` shared secret. Phase 6 will migrate this
2806
- * to SPIFFE SVID mTLS (ADR-068).
2807
- *
2808
- * TODO: Phase 6 — prefer SPIFFE SVID over shared-secret auth.
2809
- *
2810
- * @example
2811
- * ```typescript
2812
- * const { accessToken, expiresIn } = await auth.oauth.mintAccessToken({
2813
- * baseUrl: 'https://your-app.api.sylphx.com/v1',
2814
- * internalToken: process.env.SYLPHX_INTERNAL_TOKEN!,
2815
- * claims: { sub: user.id, email: user.email, app_id: 'platform', role: 'member', email_verified: true },
2816
- * })
2817
- * ```
2818
- */
2819
- readonly mintAccessToken: (opts: {
2820
- readonly baseUrl: string;
2821
- readonly internalToken: string;
2822
- readonly claims: MintAccessTokenClaims;
2823
- readonly userAgent?: string;
2824
- }) => Promise<MintAccessTokenResult>;
2825
- /**
2826
- * Exchange an OAuth 2.0 authorization_code for an access + refresh token
2827
- * pair (ADR-089 Phase 5.1b — RFC 6749 §4.1.3). PKCE S256 mandatory per
2828
- * OAuth 2.1 baseline.
2829
- *
2830
- * @example
2831
- * ```typescript
2832
- * const { verifier, challenge } = await generatePkce()
2833
- * // user redirected to /oauth/authorize?...&code_challenge=<challenge>
2834
- * // ...user approves, browser hits your redirect_uri with ?code=<code>
2835
- * const tokens = await auth.oauth.exchangeAuthorizationCode({
2836
- * baseUrl: 'https://api.sylphx.com/v1',
2837
- * clientId: 'sylphx-console',
2838
- * clientSecret: process.env.CONSOLE_CLIENT_SECRET,
2839
- * code,
2840
- * redirectUri: 'https://console.sylphx.com/auth/callback',
2841
- * codeVerifier: verifier,
2842
- * })
2843
- * ```
2844
- */
2845
- readonly exchangeAuthorizationCode: (opts: {
2846
- readonly baseUrl: string;
2847
- readonly clientId: string;
2848
- readonly clientSecret?: string;
2849
- readonly code: string;
2850
- readonly redirectUri: string;
2851
- readonly codeVerifier: string;
2852
- }) => Promise<OAuthTokenResult>;
2853
- /**
2854
- * Refresh a platform access token using a refresh_token
2855
- * (ADR-089 Phase 5.1b — RFC 6749 §6). Rotation is mandatory — the
2856
- * presented refresh token is consumed and a new one returned.
2857
- *
2858
- * @example
2859
- * ```typescript
2860
- * const tokens = await auth.oauth.refreshAccessToken({
2861
- * baseUrl: 'https://api.sylphx.com/v1',
2862
- * clientId: 'sylphx-console',
2863
- * clientSecret: process.env.CONSOLE_CLIENT_SECRET,
2864
- * refreshToken: stored.refresh_token,
2865
- * })
2866
- * ```
2867
- */
2868
- readonly refreshAccessToken: (opts: {
2869
- readonly baseUrl: string;
2870
- readonly clientId: string;
2871
- readonly clientSecret?: string;
2872
- readonly refreshToken: string;
2873
- readonly scope?: string;
2874
- }) => Promise<OAuthTokenResult>;
2875
- /**
2876
- * Poll the OAuth token endpoint for a device-code grant (ADR-089 Phase
2877
- * 5.1c — RFC 8628 §3.4). The preferred way to exchange an approved
2878
- * device grant for tokens — returns an RFC 6749 error envelope on the
2879
- * `{pending, slow_down, denied, expired}` states so callers can
2880
- * distinguish precisely without parsing Phase 2a's `/auth/device/poll`
2881
- * status string.
2882
- *
2883
- * Returns `{ ok: true, tokens }` on success or `{ ok: false, error }`
2884
- * for every RFC-defined polling outcome. Callers MUST honour the
2885
- * polling `interval` returned by `/auth/device` — polling faster yields
2886
- * `{ ok: false, error: 'slow_down' }`.
2887
- *
2888
- * @example
2889
- * ```typescript
2890
- * while (true) {
2891
- * await sleep(interval * 1000)
2892
- * const r = await auth.oauth.pollDeviceToken({
2893
- * baseUrl: 'https://api.sylphx.com/v1',
2894
- * clientId: 'sylphx-cli',
2895
- * deviceCode,
2896
- * })
2897
- * if (r.ok) return r.tokens
2898
- * if (r.error === 'authorization_pending' || r.error === 'slow_down') continue
2899
- * throw new Error(r.error) // access_denied | expired_token
2900
- * }
2901
- * ```
2902
- */
2903
- readonly pollDeviceToken: (opts: {
2904
- readonly baseUrl: string;
2905
- readonly clientId: string;
2906
- readonly deviceCode: string;
2907
- }) => Promise<OAuthPollResult>;
2908
- /**
2909
- * Mint a service-principal access token via the `client_credentials`
2910
- * grant (ADR-089 Phase 5.1c — RFC 6749 §4.4). Requires a confidential
2911
- * client (public clients cannot use this grant). No refresh token is
2912
- * issued per §4.4.3 — callers re-run this exchange on expiry.
2913
- *
2914
- * Typical use: CI integrations, server-to-server automation that has
2915
- * no human owner and cannot run a device flow.
2916
- *
2917
- * @example
2918
- * ```typescript
2919
- * const { access_token } = await auth.oauth.clientCredentialsToken({
2920
- * baseUrl: 'https://api.sylphx.com/v1',
2921
- * clientId: process.env.SYLPHX_CLIENT_ID!,
2922
- * clientSecret: process.env.SYLPHX_CLIENT_SECRET!,
2923
- * scope: 'tenants:provision',
2924
- * })
2925
- * ```
2926
- */
2927
- readonly clientCredentialsToken: (opts: {
2928
- readonly baseUrl: string;
2929
- readonly clientId: string;
2930
- readonly clientSecret: string;
2931
- readonly scope?: string;
2932
- }) => Promise<OAuthClientCredentialsResult>;
3538
+ declare function getOrgScopedToken(config: SylphxConfig, orgId: string): Promise<OrgScopedTokenResponse>;
3539
+ /**
3540
+ * @deprecated Use getOrgScopedToken(config, orgId). Kept as the shorter
3541
+ * organization switch alias for existing SDK callers.
3542
+ */
3543
+ declare function switchOrg(config: SylphxConfig, orgId: string): Promise<OrgScopedTokenResponse>;
3544
+ type DeviceInitInput = DeviceInitRequest;
3545
+ type DeviceGrant = DeviceInitResponse;
3546
+ type DevicePollResult = DevicePollResponse;
3547
+ type DeviceApproveInput = DeviceApproveRequest;
3548
+ type DeviceApproveResult = DeviceApproveResponse;
3549
+ type DeviceDenyInput = DeviceDenyRequest;
3550
+ type DeviceDenyResult = DeviceDenyResponse;
3551
+ /**
3552
+ * `device` namespace — RFC 8628 device authorization grant.
3553
+ *
3554
+ * Used by headless clients (CLI, TV apps, IoT) to authorise via a
3555
+ * companion browser instead of reading credentials from env vars.
3556
+ */
3557
+ declare const device: {
2933
3558
  /**
2934
- * Revoke an OAuth access or refresh token (RFC 7009 — ADR-089 Phase 5.1d).
3559
+ * Start a device authorization grant.
2935
3560
  *
2936
- * Per §2.2 this always resolves successfully — the server returns 200
2937
- * whether the token existed, was already revoked, or belonged to a
2938
- * different client. Only true protocol-level failures (malformed
2939
- * request, bad client credentials) throw.
3561
+ * Returns a `DeviceGrant` with `verification_uri_complete` (open this
3562
+ * in the user's browser) and `device_code` (use for polling).
2940
3563
  *
2941
3564
  * @example
2942
3565
  * ```typescript
2943
- * await auth.oauth.revokeToken({
3566
+ * const grant = await device.init({
2944
3567
  * baseUrl: 'https://your-app.api.sylphx.com/v1',
2945
3568
  * clientId: 'sylphx-cli',
2946
- * token: refreshToken,
2947
- * tokenTypeHint: 'refresh_token',
3569
+ * scope: ['org:read', 'project:*'],
2948
3570
  * })
3571
+ * openBrowser(grant.verification_uri_complete)
2949
3572
  * ```
2950
3573
  */
2951
- readonly revokeToken: (opts: OAuthClientCallOpts) => Promise<void>;
3574
+ readonly init: (opts: {
3575
+ readonly baseUrl: string;
3576
+ readonly clientId: string;
3577
+ readonly scope?: readonly string[];
3578
+ readonly userAgent?: string;
3579
+ }) => Promise<DeviceGrant>;
2952
3580
  /**
2953
- * Introspect an OAuth access or refresh token (RFC 7662 — ADR-089 Phase 5.1d).
2954
- *
2955
- * Returns `{ active: false }` for expired / revoked / unknown /
2956
- * not-owned tokens (without revealing which); `{ active: true, ... }`
2957
- * with full claims for live ones. Only protocol-level failures
2958
- * (4xx on the revocation envelope itself) throw.
3581
+ * Poll a pending grant. Returns `status: 'pending' | 'approved' |
3582
+ * 'denied' | 'expired'`. On `approved`, the result carries the OAuth
3583
+ * pair (access_token + refresh_token).
2959
3584
  *
2960
- * @example
2961
- * ```typescript
2962
- * const result = await auth.oauth.introspectToken({
2963
- * baseUrl: 'https://your-app.api.sylphx.com/v1',
2964
- * clientId: 'gateway',
2965
- * clientSecret: process.env.GATEWAY_SECRET,
2966
- * token: accessToken,
2967
- * })
2968
- * if (!result.active) throw new Error('token not accepted')
2969
- * ```
2970
- */
2971
- readonly introspectToken: (opts: OAuthClientCallOpts) => Promise<OAuthIntrospectResult>;
2972
- };
2973
- /**
2974
- * `dpop` namespace — client-side helpers for RFC 9449 sender-constrained
2975
- * tokens. Built on `crypto.subtle` (no new npm deps).
2976
- *
2977
- * @example
2978
- * ```typescript
2979
- * // At login:
2980
- * const kp = await dpop.generateKeyPair()
2981
- * // Exchange device code at /oauth/token, attaching proof:
2982
- * const tokenProof = await dpop.generateProof({
2983
- * privateKey: kp.privateKey,
2984
- * publicKey: kp.publicKey,
2985
- * method: 'POST',
2986
- * uri: 'https://api.sylphx.com/v1/oauth/token',
2987
- * })
2988
- * // later, calling a resource:
2989
- * const resProof = await dpop.generateProof({
2990
- * privateKey: kp.privateKey,
2991
- * publicKey: kp.publicKey,
2992
- * method: 'GET',
2993
- * uri: 'https://api.sylphx.com/v1/me',
2994
- * accessToken,
2995
- * })
2996
- * fetch('/v1/me', {
2997
- * headers: { Authorization: `DPoP ${accessToken}`, DPoP: resProof },
2998
- * })
2999
- * ```
3000
- */
3001
- declare const dpop: {
3002
- /**
3003
- * Generate a fresh ES256 key pair. Private key is non-extractable
3004
- * (`extractable: false`) so it can be stored but never serialised —
3005
- * the only legal operation is `sign`. Clients that need to
3006
- * hibernate the keypair across restarts must use a host-provided
3007
- * secure store (Keychain, Credential Manager, IndexedDB + CryptoKey
3008
- * wrapping).
3009
- */
3010
- readonly generateKeyPair: () => Promise<{
3011
- readonly privateKey: CryptoKey;
3012
- readonly publicKey: CryptoKey;
3013
- readonly thumbprint: string;
3014
- }>;
3015
- /**
3016
- * Sign a DPoP proof JWT. When `accessToken` is provided, the proof
3017
- * includes `ath = base64url(sha256(accessToken))` so the resource
3018
- * server can bind the proof to the token being presented (RFC 9449
3019
- * §4.3 step 11).
3585
+ * Callers MUST respect the `interval` returned by `init()` — polling
3586
+ * faster than that may return 429 slow_down (RFC 8628 §5.5).
3020
3587
  */
3021
- readonly generateProof: (opts: {
3022
- readonly privateKey: CryptoKey;
3023
- readonly publicKey: CryptoKey;
3024
- readonly method: string;
3025
- readonly uri: string;
3026
- readonly accessToken?: string;
3027
- readonly nonce?: string;
3028
- }) => Promise<string>;
3029
- };
3030
- interface OAuthTokenResult {
3031
- readonly access_token: string;
3032
- readonly token_type: 'Bearer';
3033
- readonly expires_in: number;
3034
- readonly refresh_token: string;
3035
- readonly scope: string;
3036
- }
3037
- /**
3038
- * client_credentials token response (RFC 6749 §4.4.3). Distinct from
3039
- * {@link OAuthTokenResult} because §4.4.3 forbids issuing a refresh
3040
- * token — callers re-run the grant on expiry rather than rotating.
3041
- */
3042
- interface OAuthClientCredentialsResult {
3043
- readonly access_token: string;
3044
- readonly token_type: 'Bearer';
3045
- readonly expires_in: number;
3046
- readonly scope: string;
3047
- }
3048
- /**
3049
- * RFC 8628 §3.5 polling outcomes surfaced by {@link oauth.pollDeviceToken}.
3050
- * Callers pattern-match on `error` to choose the next action:
3051
- * - `authorization_pending` + `slow_down` — keep polling (respect interval).
3052
- * - `access_denied` — user declined; abort.
3053
- * - `expired_token` — grant timed out; re-run `/auth/device`.
3054
- * - others — unexpected; surface to the user.
3055
- */
3056
- type OAuthPollError = 'authorization_pending' | 'slow_down' | 'access_denied' | 'expired_token' | 'invalid_grant' | 'invalid_client' | 'invalid_request' | 'unauthorized_client' | 'oauth_error';
3057
- type OAuthPollResult = {
3058
- readonly ok: true;
3059
- readonly tokens: OAuthTokenResult;
3060
- } | {
3061
- readonly ok: false;
3062
- readonly error: OAuthPollError;
3063
- readonly status: number;
3064
- };
3065
- interface ImpersonationStartResult {
3066
- readonly success: true;
3067
- readonly token: string;
3068
- readonly sessionId: string;
3069
- readonly expiresAt: string;
3070
- }
3071
- interface ImpersonationEndResult {
3072
- readonly success: boolean;
3073
- readonly sessionsEnded: number;
3074
- }
3075
- interface ImpersonationInfo {
3076
- readonly isImpersonation: true;
3077
- readonly adminUserId: string;
3078
- readonly adminEmail: string;
3079
- readonly adminName: string | null;
3080
- readonly impersonatedAt: string;
3081
- }
3082
- interface ImpersonationActive {
3083
- readonly sessionId: string;
3084
- readonly adminUserId: string;
3085
- readonly adminEmail: string;
3086
- readonly adminName: string | null;
3087
- readonly targetUserId: string;
3088
- readonly targetEmail: string;
3089
- readonly targetName: string | null;
3090
- readonly impersonatedAt: string;
3091
- readonly lastActiveAt: string;
3092
- }
3093
- interface ImpersonationStartChallengeInput {
3094
- readonly baseUrl: string;
3095
- readonly accessToken: string;
3096
- readonly targetUserId: string;
3097
- readonly reason: string;
3098
- readonly userAgent?: string;
3099
- }
3100
- interface ImpersonationChallenge {
3101
- readonly requestId: string;
3102
- readonly challengeKey: string;
3103
- readonly webauthnOptions: {
3104
- readonly challenge: string;
3105
- readonly rpId?: string;
3106
- readonly allowCredentials: ReadonlyArray<{
3107
- readonly id: string;
3108
- readonly type: 'public-key';
3109
- readonly transports?: readonly string[];
3110
- }>;
3111
- readonly userVerification: 'required';
3112
- readonly timeout: number;
3113
- };
3114
- }
3115
- interface ImpersonationStartStepupInput {
3116
- readonly baseUrl: string;
3117
- readonly accessToken: string;
3118
- readonly requestId: string;
3119
- readonly challengeKey: string;
3120
- readonly assertion: unknown;
3121
- readonly emergencyBypass?: boolean;
3122
- readonly userAgent?: string;
3123
- }
3124
- type ImpersonationStartStepupResult = {
3125
- readonly branch: 'emergency';
3126
- readonly requestId: string;
3127
- readonly token: string;
3128
- readonly sessionId: string;
3129
- readonly expiresAt: string;
3130
- } | {
3131
- readonly branch: 'awaiting-consent';
3132
- readonly requestId: string;
3133
- readonly consentDeadline: string;
3134
- };
3135
- type ImpersonationConsentDecision = 'approve' | 'deny';
3136
- type ImpersonationConsentResponse = {
3137
- readonly branch: 'approved';
3138
- readonly requestId: string;
3139
- readonly token: string;
3140
- readonly sessionId: string;
3141
- readonly expiresAt: string;
3142
- } | {
3143
- readonly branch: 'denied';
3144
- readonly requestId: string;
3145
- };
3146
- interface ImpersonationRequestRow {
3147
- readonly id: string;
3148
- readonly operatorId: string;
3149
- readonly targetUserId: string;
3150
- readonly reason: string;
3151
- readonly status: 'awaiting-stepup' | 'awaiting-consent' | 'active' | 'denied' | 'expired' | 'ended' | 'revoked';
3152
- readonly emergencyBypass: boolean;
3153
- readonly sessionId: string | null;
3154
- readonly consentDeadline: string | null;
3155
- readonly startedAt: string | null;
3156
- readonly endedAt: string | null;
3157
- readonly createdAt: string;
3158
- }
3159
- /**
3160
- * `impersonation` namespace — admin user impersonation for the
3161
- * Platform plane. Phase 3b shipped the minimal one-shot surface
3162
- * (`start/end/info/active`); Phase 5.9 layers on WebAuthn step-up
3163
- * (ADR-089 P15 / S27), target-user consent, notification SLO, and
3164
- * CAEP integration via the new `startChallenge` + `startStepup` +
3165
- * `respondConsent` + `listRequests` + `endSession` methods.
3166
- *
3167
- * Migration from Phase 3b → 5.9:
3168
- * - Old `start({targetUserId})` → new two-step flow:
3169
- * 1. `startChallenge({targetUserId, reason})` returns WebAuthn
3170
- * options + challengeKey.
3171
- * 2. `startStepup({requestId, challengeKey, assertion})` verifies
3172
- * the passkey and either mints the session (emergency bypass)
3173
- * or transitions to awaiting-consent.
3174
- * 3. Target calls `respondConsent(id, 'approve' | 'deny')`.
3175
- * - Old `end({sessionId})` still works (legacy). New
3176
- * `endSession(requestId)` preferred for sessions tracked via
3177
- * `impersonation_requests`.
3178
- */
3179
- declare const impersonation: {
3180
- readonly start: (opts: {
3181
- readonly baseUrl: string;
3182
- readonly accessToken: string;
3183
- readonly targetUserId: string;
3184
- readonly ipAddress?: string;
3185
- readonly userAgent?: string;
3186
- }) => Promise<ImpersonationStartResult>;
3187
- readonly end: (opts: {
3188
- readonly baseUrl: string;
3189
- readonly accessToken: string;
3190
- readonly sessionId?: string;
3191
- readonly userAgent?: string;
3192
- }) => Promise<ImpersonationEndResult>;
3193
- readonly info: (opts: {
3194
- readonly baseUrl: string;
3195
- readonly accessToken: string;
3196
- readonly sessionId: string;
3197
- readonly userAgent?: string;
3198
- }) => Promise<ImpersonationInfo | null>;
3199
- readonly active: (opts: {
3588
+ readonly poll: (opts: {
3200
3589
  readonly baseUrl: string;
3201
- readonly accessToken: string;
3590
+ readonly deviceCode: string;
3202
3591
  readonly userAgent?: string;
3203
- }) => Promise<readonly ImpersonationActive[]>;
3204
- /**
3205
- * Phase 5.9 step 1 of 2 — request a WebAuthn assertion challenge.
3206
- * Returns the pending-request id plus options ready for
3207
- * `navigator.credentials.get(...)`. Caller is expected to post the
3208
- * resulting assertion to {@link impersonation.startStepup}.
3209
- */
3210
- readonly startChallenge: (opts: ImpersonationStartChallengeInput) => Promise<ImpersonationChallenge>;
3211
- /**
3212
- * Phase 5.9 step 2 of 2 — complete the WebAuthn step-up. Returns
3213
- * either the active session (emergency bypass) or the
3214
- * consent deadline (regular flow). Phase 3b `start` is superseded
3215
- * by this method; old callers should migrate to
3216
- * `startChallenge` → `startStepup`.
3217
- */
3218
- readonly startStepup: (opts: ImpersonationStartStepupInput) => Promise<ImpersonationStartStepupResult>;
3592
+ }) => Promise<DevicePollResult>;
3219
3593
  /**
3220
- * Target user's consent decision. Approve mints the session token;
3221
- * deny transitions the request to `denied`.
3594
+ * Browser leg the approving user confirms the grant.
3595
+ *
3596
+ * Requires a valid platform-issued access token (`Authorization:
3597
+ * Bearer <accessToken>`) proving the user is logged in on the
3598
+ * Console. Typically called by the Console's `/device` verification
3599
+ * page server-side, forwarding the user's session JWT.
3222
3600
  */
3223
- readonly respondConsent: (opts: {
3224
- readonly baseUrl: string;
3225
- readonly accessToken: string;
3226
- readonly requestId: string;
3227
- readonly decision: ImpersonationConsentDecision;
3228
- readonly userAgent?: string;
3229
- }) => Promise<ImpersonationConsentResponse>;
3230
- /** List impersonation requests. Non-super_admin sees only their own. */
3231
- readonly listRequests: (opts: {
3601
+ readonly approve: (opts: {
3232
3602
  readonly baseUrl: string;
3603
+ readonly userCode: string;
3233
3604
  readonly accessToken: string;
3234
- readonly filter?: {
3235
- readonly operatorId?: string;
3236
- readonly targetUserId?: string;
3237
- readonly status?: ImpersonationRequestRow["status"];
3238
- readonly limit?: number;
3239
- };
3240
3605
  readonly userAgent?: string;
3241
- }) => Promise<readonly ImpersonationRequestRow[]>;
3606
+ }) => Promise<DeviceApproveResult>;
3242
3607
  /**
3243
- * End an active impersonation session by request id. Emits a CAEP
3244
- * `session-revoked` event via the Phase 5.Z outbox so every in-flight
3245
- * verifier invalidates the token within ≤1s.
3608
+ * Browser leg the user declines the grant.
3609
+ *
3610
+ * Requires a valid platform-issued access token just like `approve`.
3246
3611
  */
3247
- readonly endSession: (opts: {
3612
+ readonly deny: (opts: {
3248
3613
  readonly baseUrl: string;
3614
+ readonly userCode: string;
3249
3615
  readonly accessToken: string;
3250
- readonly requestId: string;
3251
3616
  readonly userAgent?: string;
3252
- }) => Promise<{
3253
- success: true;
3254
- requestId: string;
3255
- sessionId: string | null;
3256
- }>;
3617
+ }) => Promise<DeviceDenyResult>;
3257
3618
  };
3258
3619
 
3259
3620
  /**
@@ -3390,7 +3751,7 @@ interface StreamMessage<T = unknown> {
3390
3751
  /**
3391
3752
  * Realtime Functions
3392
3753
  *
3393
- * Pure functions for real-time messaging via Redis Streams.
3754
+ * Pure functions for real-time messaging via managed durable streams.
3394
3755
  * Supports channel-based pub/sub with SSE delivery to browsers.
3395
3756
  *
3396
3757
  * @example
@@ -4415,8 +4776,6 @@ interface TaskInput {
4415
4776
  interface TaskResult {
4416
4777
  /** Task ID */
4417
4778
  taskId: string;
4418
- /** QStash message ID */
4419
- messageId?: string;
4420
4779
  /** Scheduled execution time */
4421
4780
  scheduledFor?: string;
4422
4781
  }
@@ -5578,17 +5937,7 @@ type OrganizationsListResult = {
5578
5937
  offset: number;
5579
5938
  };
5580
5939
  type OrgRole = OrgSdkRole;
5581
- /**
5582
- * The contract's `CreateOrgInput` requires `{ name, slug }`; the SDK's
5583
- * previous OpenAPI-derived shape allowed omitting `slug` (server
5584
- * auto-generates from name) and accepted optional `email` / `metadata`.
5585
- * Preserve the looser SDK surface with a local `Omit` + widening.
5586
- */
5587
- type CreateOrgInput = Omit<CreateOrgInput$1, 'slug'> & {
5588
- slug?: string;
5589
- email?: string;
5590
- metadata?: Record<string, unknown>;
5591
- };
5940
+ type CreateOrgInput = CreateOrgInput$1;
5592
5941
  type UpdateOrgInput = UpdateOrgInput$1 & {
5593
5942
  metadata?: Record<string, unknown> | null;
5594
5943
  };
@@ -6224,11 +6573,11 @@ declare function getSecret(config: SylphxConfig, input: GetSecretInput): Promise
6224
6573
  * @example
6225
6574
  * ```typescript
6226
6575
  * const secrets = await getSecrets(config, {
6227
- * keys: ['DATABASE_URL', 'REDIS_URL', 'JWT_SECRET']
6576
+ * keys: ['DATABASE_URL', 'CACHE_URL', 'JWT_SECRET']
6228
6577
  * })
6229
6578
  *
6230
6579
  * const db = createPool(secrets.DATABASE_URL)
6231
- * const redis = createClient(secrets.REDIS_URL)
6580
+ * const cache = createCacheClient(secrets.CACHE_URL)
6232
6581
  * ```
6233
6582
  */
6234
6583
  declare function getSecrets(config: SylphxConfig, input: GetSecretsInput): Promise<GetSecretsResult>;
@@ -6814,7 +7163,7 @@ interface KvZMember {
6814
7163
  /**
6815
7164
  * KV (Key-Value Store) Functions
6816
7165
  *
6817
- * Pure functions for distributed key-value storage backed by Redis.
7166
+ * Pure functions for managed key-value storage.
6818
7167
  * Supports strings, hashes, lists, sorted sets, and built-in rate limiting.
6819
7168
  *
6820
7169
  * Keys are automatically namespaced per app, so no key collisions occur
@@ -7085,7 +7434,7 @@ declare function kvZrange(config: SylphxConfig, request: KvZrangeRequest): Promi
7085
7434
  score?: number;
7086
7435
  }>>;
7087
7436
  /**
7088
- * Check and consume a rate limit token using Redis sliding window.
7437
+ * Check and consume a rate limit token using the platform sliding window.
7089
7438
  *
7090
7439
  * This is a built-in rate limiter — no external service needed.
7091
7440
  *
@@ -7109,7 +7458,7 @@ interface KvScanOptions {
7109
7458
  pattern?: string;
7110
7459
  /** Cursor for pagination. Use '0' to start a new scan (default). */
7111
7460
  cursor?: string;
7112
- /** Hint to Redis for how many keys to return per iteration (1–1000). Default: 100. */
7461
+ /** Hint for how many keys to return per iteration (1–1000). Default: 100. */
7113
7462
  count?: number;
7114
7463
  }
7115
7464
  interface KvScanResult {
@@ -7121,7 +7470,7 @@ interface KvScanResult {
7121
7470
  done: boolean;
7122
7471
  }
7123
7472
  /**
7124
- * Scan keys matching a pattern using Redis SCAN (cursor-based pagination).
7473
+ * Scan keys matching a pattern using cursor-based pagination.
7125
7474
  *
7126
7475
  * Unlike `KEYS`, SCAN is safe to use in production — it iterates incrementally.
7127
7476
  * Call repeatedly with the returned `nextCursor` until `done` is true.
@@ -7516,7 +7865,7 @@ declare function captureMessage(config: SylphxConfig, message: string, options?:
7516
7865
  *
7517
7866
  * ## Architecture
7518
7867
  *
7519
- * POST /sandboxes → Platform provisions sandbox, waits for pod readiness,
7868
+ * POST /sandboxes → Platform provisions sandbox, waits for runtime readiness,
7520
7869
  * returns { endpoint, token }. All subsequent exec/files/pty operations
7521
7870
  * go DIRECTLY to the sandbox exec-server — Platform is not in the data path.
7522
7871
  *
@@ -7535,7 +7884,7 @@ declare function captureMessage(config: SylphxConfig, message: string, options?:
7535
7884
  *
7536
7885
  * const config = createServerClient(process.env.SYLPHX_SECRET_URL!)
7537
7886
  *
7538
- * // Create sandbox (Platform waits for pod ready before returning)
7887
+ * // Create sandbox (Platform waits for the runtime before returning)
7539
7888
  * const sandbox = await SandboxClient.create(config)
7540
7889
  *
7541
7890
  * // Stream exec output in real-time
@@ -7557,7 +7906,7 @@ declare function captureMessage(config: SylphxConfig, message: string, options?:
7557
7906
  */
7558
7907
 
7559
7908
  interface SandboxOptions {
7560
- /** Docker image (must be in registry.sylphx.com). Omit to use env default. */
7909
+ /** OCI image from a connected registry. Omit to use the environment default. */
7561
7910
  image?: string;
7562
7911
  /**
7563
7912
  * Request timeout for the create lifecycle call.
@@ -7569,17 +7918,8 @@ interface SandboxOptions {
7569
7918
  idleTimeoutMs?: number;
7570
7919
  /** Scratch storage size in GiB at /data, scoped to the sandbox lifecycle. */
7571
7920
  storageGi?: number;
7572
- /** CPU/memory resource spec */
7573
- resources?: {
7574
- requests?: {
7575
- cpu?: string;
7576
- memory?: string;
7577
- };
7578
- limits?: {
7579
- cpu?: string;
7580
- memory?: string;
7581
- };
7582
- };
7921
+ /** Managed machine size. Defaults to `standard`. */
7922
+ machine?: SandboxMachineSize;
7583
7923
  /** Environment variables injected into the sandbox container */
7584
7924
  env?: Record<string, string>;
7585
7925
  /**
@@ -7598,6 +7938,7 @@ interface SandboxOptions {
7598
7938
  readOnly?: boolean;
7599
7939
  }>;
7600
7940
  }
7941
+ type SandboxMachineSize = MachineSize;
7601
7942
  /** SSE event emitted by sandbox.exec() */
7602
7943
  type ExecEvent = {
7603
7944
  type: 'stdout';
@@ -7708,6 +8049,8 @@ interface SandboxRecord {
7708
8049
  id: string;
7709
8050
  status: 'starting' | 'running' | 'idle' | 'terminated' | 'error';
7710
8051
  image: string;
8052
+ /** Managed machine size selected for this sandbox. */
8053
+ machine: SandboxMachineSize | null;
7711
8054
  /** Public HTTPS endpoint: https://sbx-xxx.sandboxes.sylphx.app */
7712
8055
  endpoint: string | null;
7713
8056
  /** Per-sandbox RS256 JWT for direct exec-server authentication */
@@ -7890,14 +8233,14 @@ declare class SandboxClient {
7890
8233
  *
7891
8234
  * const config = createServerClient(process.env.SYLPHX_SECRET_URL!)
7892
8235
  *
7893
- * const run = await RunsClient.create(config, {
7894
- * image: 'registry.sylphx.com/sylphx/my-trainer:abc123',
8236
+ * const run = await RunsClient.run(config, {
8237
+ * image: 'ghcr.io/acme/my-trainer:sha-abc123',
7895
8238
  * command: ['python', 'train.py', '--fold', '0'],
7896
- * resources: { requests: { cpu: '4', memory: '8Gi' } },
8239
+ * machine: 'large',
7897
8240
  * timeoutSeconds: 3600,
7898
8241
  * })
7899
8242
  *
7900
- * const result = await worker.wait()
8243
+ * const result = await run.wait()
7901
8244
  * console.log(result.exitCode) // 0
7902
8245
  * console.log(result.stdout) // captured stdout
7903
8246
  * ```
@@ -7906,11 +8249,11 @@ declare class SandboxClient {
7906
8249
  * ```typescript
7907
8250
  * const workers = await Promise.all(
7908
8251
  * folds.map((fold) =>
7909
- * RunsClient.create(config, {
7910
- * image: 'registry.sylphx.com/sylphx/trainer:abc123',
8252
+ * RunsClient.run(config, {
8253
+ * image: 'ghcr.io/acme/trainer:sha-abc123',
7911
8254
  * command: ['python', 'train.py', '--fold', String(fold.id)],
7912
8255
  * env: { FOLD_ID: String(fold.id), DATABASE_URL: process.env.DATABASE_URL! },
7913
- * resources: { requests: { cpu: '4', memory: '8Gi' } },
8256
+ * machine: 'large',
7914
8257
  * volumeMounts: [{ volumeId: sharedCacheVolumeId, mountPath: '/cache' }],
7915
8258
  * timeoutSeconds: 7200,
7916
8259
  * }),
@@ -7923,8 +8266,8 @@ declare class SandboxClient {
7923
8266
  *
7924
8267
  * ## Architecture
7925
8268
  *
7926
- * - Workers are isolated one-shot runs (backoffLimit: 0, no restarts)
7927
- * - Images must be from registry.sylphx.com (scanned, private)
8269
+ * - Workers are isolated one-shot runs with no automatic restarts
8270
+ * - Images come from connected registries and are scanned before execution
7928
8271
  * - Volumes: org-level volume resources mounted into the run
7929
8272
  * - single-writer for one active writer at a time
7930
8273
  * - shared for concurrent runs and shared feature caches
@@ -7935,6 +8278,7 @@ declare class SandboxClient {
7935
8278
  */
7936
8279
 
7937
8280
  type RunStatus = 'pending' | 'running' | 'succeeded' | 'failed' | 'cancelled' | 'timeout';
8281
+ type RunMachineSize = MachineSize;
7938
8282
  interface RunVolumeMount {
7939
8283
  /** UUID of the volumeResource to mount (must belong to this org) */
7940
8284
  volumeId: string;
@@ -7945,25 +8289,11 @@ interface RunVolumeMount {
7945
8289
  /** Mount as read-only (default: false) */
7946
8290
  readOnly?: boolean;
7947
8291
  }
7948
- interface RunResourceSpec {
7949
- requests?: {
7950
- /** CPU request (e.g. '500m', '2', '4') */
7951
- cpu?: string;
7952
- /** Memory request (e.g. '512Mi', '4Gi', '16Gi') */
7953
- memory?: string;
7954
- };
7955
- limits?: {
7956
- /** CPU limit */
7957
- cpu?: string;
7958
- /** Memory limit */
7959
- memory?: string;
7960
- };
7961
- }
7962
8292
  interface CreateRunOptions {
7963
8293
  /**
7964
- * Docker image to run (must be from registry.sylphx.com).
8294
+ * OCI image to run from a connected registry.
7965
8295
  *
7966
- * @example 'registry.sylphx.com/sylphx/my-trainer:abc123def456'
8296
+ * @example 'ghcr.io/acme/my-trainer:sha-abc123'
7967
8297
  */
7968
8298
  image: string;
7969
8299
  /**
@@ -7979,10 +8309,10 @@ interface CreateRunOptions {
7979
8309
  */
7980
8310
  env?: Record<string, string>;
7981
8311
  /**
7982
- * CPU/memory resource spec.
7983
- * Defaults: { requests: { cpu: '500m', memory: '512Mi' }, limits: { cpu: '2', memory: '2Gi' } }
8312
+ * Managed machine size. The platform owns CPU, memory, scheduling, and isolation details.
8313
+ * Defaults to `standard`.
7984
8314
  */
7985
- resources?: RunResourceSpec;
8315
+ machine?: RunMachineSize;
7986
8316
  /**
7987
8317
  * Hard timeout in seconds (default: 3600 = 1 hour, max: 86400 = 24 hours).
7988
8318
  * The platform terminates the run when the deadline is reached (status: 'timeout').
@@ -8005,8 +8335,8 @@ interface Run {
8005
8335
  command: string[];
8006
8336
  /** Environment variables */
8007
8337
  env: Record<string, string> | null;
8008
- /** Resource spec */
8009
- resources: RunResourceSpec | null;
8338
+ /** Managed machine size selected for this run. */
8339
+ machine: RunMachineSize | null;
8010
8340
  /** Hard timeout in seconds */
8011
8341
  timeoutSeconds: number;
8012
8342
  /** Volume mounts */
@@ -8021,7 +8351,7 @@ interface Run {
8021
8351
  errorMessage: string | null;
8022
8352
  /** Duration in milliseconds (only when completed) */
8023
8353
  durationMs: number | null;
8024
- /** When the worker pod started running */
8354
+ /** When the worker runtime started */
8025
8355
  startedAt: string | null;
8026
8356
  /** When the worker completed */
8027
8357
  completedAt: string | null;
@@ -8085,7 +8415,7 @@ declare class RunHandle {
8085
8415
  *
8086
8416
  * @example
8087
8417
  * ```typescript
8088
- * const result = await worker.wait()
8418
+ * const result = await run.wait()
8089
8419
  * if (result.exitCode !== 0) {
8090
8420
  * throw new Error(`Worker failed: ${result.errorMessage ?? result.stderr}`)
8091
8421
  * }
@@ -8126,10 +8456,10 @@ declare class RunHandle {
8126
8456
  * const config = createServerClient(process.env.SYLPHX_SECRET_URL!)
8127
8457
  *
8128
8458
  * // Run a worker and wait for completion
8129
- * const result = await RunsClient.create(config, { ... }).then(w => w.wait())
8459
+ * const result = await RunsClient.run(config, { ... }).then((run) => run.wait())
8130
8460
  *
8131
8461
  * // Run N workers in parallel, wait for all
8132
- * const handles = await Promise.all(folds.map(fold => RunsClient.create(config, { ... })))
8462
+ * const handles = await Promise.all(folds.map((fold) => RunsClient.run(config, { ... })))
8133
8463
  * const results = await Promise.all(handles.map(h => h.wait()))
8134
8464
  * ```
8135
8465
  */
@@ -8142,13 +8472,13 @@ declare const RunsClient: {
8142
8472
  *
8143
8473
  * @example
8144
8474
  * ```typescript
8145
- * const run = await RunsClient.create(config, {
8146
- * image: 'registry.sylphx.com/sylphx/trainer:abc123',
8475
+ * const run = await RunsClient.run(config, {
8476
+ * image: 'ghcr.io/acme/trainer:sha-abc123',
8147
8477
  * command: ['python', 'train.py', '--fold', '3'],
8148
- * resources: { requests: { cpu: '4', memory: '16Gi' } },
8478
+ * machine: 'large',
8149
8479
  * volumeMounts: [{ volumeId: cacheVolumeId, mountPath: '/cache' }],
8150
8480
  * })
8151
- * const result = await worker.wait()
8481
+ * const result = await run.wait()
8152
8482
  * ```
8153
8483
  */
8154
8484
  run(config: SylphxConfig, options: CreateRunOptions): Promise<RunHandle>;
@@ -8170,20 +8500,20 @@ declare const RunsClient: {
8170
8500
  *
8171
8501
  * @example
8172
8502
  * ```typescript
8173
- * const { workers } = await RunsClient.list(config, { status: 'running' })
8174
- * console.log(`${workers.length} workers currently running`)
8503
+ * const { data } = await RunsClient.list(config, { status: 'running' })
8504
+ * console.log(`${data.length} runs currently running`)
8175
8505
  * ```
8176
8506
  */
8177
8507
  list(config: SylphxConfig, options?: ListRunsOptions): Promise<ListRunsResult>;
8178
8508
  /**
8179
8509
  * Spawn a worker and wait for it to complete in one call.
8180
8510
  *
8181
- * Equivalent to `(await RunsClient.create(config, options)).wait(waitOptions)`.
8511
+ * Equivalent to `(await RunsClient.run(config, options)).wait(waitOptions)`.
8182
8512
  *
8183
8513
  * @example
8184
8514
  * ```typescript
8185
8515
  * const result = await RunsClient.runAndWait(config, {
8186
- * image: 'registry.sylphx.com/sylphx/process:abc',
8516
+ * image: 'ghcr.io/acme/process:sha-abc123',
8187
8517
  * command: ['node', 'dist/process.js'],
8188
8518
  * })
8189
8519
  * if (result.exitCode !== 0) throw new Error(result.errorMessage ?? 'worker failed')
@@ -8204,13 +8534,13 @@ declare const WorkersClient: {
8204
8534
  *
8205
8535
  * @example
8206
8536
  * ```typescript
8207
- * const run = await RunsClient.create(config, {
8208
- * image: 'registry.sylphx.com/sylphx/trainer:abc123',
8537
+ * const run = await RunsClient.run(config, {
8538
+ * image: 'ghcr.io/acme/trainer:sha-abc123',
8209
8539
  * command: ['python', 'train.py', '--fold', '3'],
8210
- * resources: { requests: { cpu: '4', memory: '16Gi' } },
8540
+ * machine: 'large',
8211
8541
  * volumeMounts: [{ volumeId: cacheVolumeId, mountPath: '/cache' }],
8212
8542
  * })
8213
- * const result = await worker.wait()
8543
+ * const result = await run.wait()
8214
8544
  * ```
8215
8545
  */
8216
8546
  run(config: SylphxConfig, options: CreateRunOptions): Promise<RunHandle>;
@@ -8232,20 +8562,20 @@ declare const WorkersClient: {
8232
8562
  *
8233
8563
  * @example
8234
8564
  * ```typescript
8235
- * const { workers } = await RunsClient.list(config, { status: 'running' })
8236
- * console.log(`${workers.length} workers currently running`)
8565
+ * const { data } = await RunsClient.list(config, { status: 'running' })
8566
+ * console.log(`${data.length} runs currently running`)
8237
8567
  * ```
8238
8568
  */
8239
8569
  list(config: SylphxConfig, options?: ListRunsOptions): Promise<ListRunsResult>;
8240
8570
  /**
8241
8571
  * Spawn a worker and wait for it to complete in one call.
8242
8572
  *
8243
- * Equivalent to `(await RunsClient.create(config, options)).wait(waitOptions)`.
8573
+ * Equivalent to `(await RunsClient.run(config, options)).wait(waitOptions)`.
8244
8574
  *
8245
8575
  * @example
8246
8576
  * ```typescript
8247
8577
  * const result = await RunsClient.runAndWait(config, {
8248
- * image: 'registry.sylphx.com/sylphx/process:abc',
8578
+ * image: 'ghcr.io/acme/process:sha-abc123',
8249
8579
  * command: ['node', 'dist/process.js'],
8250
8580
  * })
8251
8581
  * if (result.exitCode !== 0) throw new Error(result.errorMessage ?? 'worker failed')
@@ -8301,6 +8631,7 @@ declare const WorkersClient: {
8301
8631
  type TriggerTargetType = 'task' | 'run' | 'http';
8302
8632
  type TriggerSourceType = 'cron' | 'event';
8303
8633
  type TriggerStatus = 'active' | 'paused' | 'deleted';
8634
+ type TriggerRunMachineSize = MachineSize;
8304
8635
  interface TaskTarget {
8305
8636
  type: 'task';
8306
8637
  taskName: string;
@@ -8318,10 +8649,7 @@ interface RunTarget {
8318
8649
  type: 'run';
8319
8650
  image: string;
8320
8651
  command: string[];
8321
- resources?: {
8322
- cpu?: string;
8323
- memory?: string;
8324
- };
8652
+ machine?: TriggerRunMachineSize;
8325
8653
  }
8326
8654
  type TriggerTarget = TaskTarget | HttpTarget | RunTarget;
8327
8655
  interface CronSource {
@@ -9343,4 +9671,4 @@ declare const functions: {
9343
9671
  };
9344
9672
  };
9345
9673
 
9346
- export { ACHIEVEMENT_TIER_CONFIG, type AIListModelsOptions, type AIListModelsResponse, type AIMessage, type AIMessageRole, type AIModel, type AIModelInfo, type AIModelsResponse, type AIProvider, type AIRateLimitInfo, type AIRateLimitResponse, type AIRequestType, type AIStreamChunk, type AITool, type AIToolCall, type AIUsageResponse, type AIUsageStats, type AccessTokenPayload, type AchievementCategory, type AchievementCriteria, type AchievementCriterion, type AchievementDefinition, type AchievementTier, type AchievementType, type AchievementUnlockEvent, type AdminUser, type AuditQueryFilter, type AuditQueryResult, AuthenticationError, AuthorizationError, type BackupCodesResult, type BatchEvent, type BatchIndexInput, type BatchIndexResult, type Breadcrumb, type BuildLog, type BuildLogHistoryResponse, type CaptureExceptionRequest, type CaptureMessageRequest, type ChallengeMethod, type ChallengeType, type ChallengeVerifyInput, type ChallengeVerifyResult, type ChatCompletionInput, type ChatCompletionResponse, type ChatInput, type ChatMessage, type ChatResult, type ChatStreamChunk, type CircuitBreakerConfig, CircuitBreakerOpenError, type CircuitState, type CommandResult, type ConsentCategory, type ConsentHistoryEntry, type ConsentHistoryResult, type ConsentPurposeDefaults, type ConsentType, type ContentPart, type CopyFileOptions, type CreateOrgInput, type CreatePermissionInput, type CreatePromoInput, type CreateRoleInput, type CreateRunOptions, type CreateTriggerOptions, type CriteriaOperator, type CronInput, type CronSchedule, type CronSource, type DatabaseConnectionInfo, type DatabaseStatus, type DatabaseStatusInfo, type DebugCategory, type DeduplicationConfig, type DeleteAccountResult, type DeleteDocumentInput, type DeployHistoryResponse, type DeployInfo, type DeployStatus, type DeviceApproveInput, type DeviceApproveResult, type DeviceDenyInput, type DeviceDenyResult, type DeviceGrant, type DeviceInitInput, type DevicePollResult, type DynamicRestClient, ERROR_CODE_STATUS, type EmailChangeInput, type EmailConfirmInput, type EmbedInput, type EmbedResult, type EmbeddingInput, type EmbeddingResponse, type LeaderboardEntry as EngagementLeaderboardEntry, type LeaderboardResult as EngagementLeaderboardResult, type EnvVar, type ErrorCode, type ErrorResponse, type EventSource, type ExceptionFrame, type ExceptionValue, type ExecEvent, type ExecOptions, type ExecResult, type FacetsResponse, type FileEvent, type FlagContext, type FlagResult, type GetConsentHistoryInput, type GetConsentsInput, type GetFacetsInput, type GetSecretInput, type GetSecretResult, type GetSecretsInput, type GetSecretsResult, type HttpTarget, type IdentifyInput, type ImpersonationActive, type ImpersonationEndResult, type ImpersonationInfo, type ImpersonationStartResult, type IndexDocumentInput, type IndexDocumentResult, type IngestLogsResult, InvalidConnectionUrlError, type InviteMemberInput, type InviteUserRequest, type InviteUserResponse, type KvExpireRequest, type KvHgetRequest, type KvHgetallRequest, type KvHsetRequest, type KvIncrRequest, type KvLpushRequest, type KvLrangeRequest, type KvMgetRequest, type KvMsetRequest, type KvRateLimitRequest, type KvRateLimitResult, type KvScanOptions, type KvScanResult, type KvSetOptions, type KvSetRequest, type KvZMember, type KvZaddRequest, type KvZrangeRequest, type LeaderboardAggregation, type LeaderboardDefinition, type LeaderboardEntry$1 as LeaderboardEntry, type LeaderboardOptions, type LeaderboardQueryOptions, type LeaderboardResetPeriod, type LeaderboardResult$1 as LeaderboardResult, type LeaderboardSortDirection, type LinkAnonymousConsentsInput, type ListFilesOptions, type ListPromosOptions, type ListPromosResult, type ListRedemptionsOptions, type ListRedemptionsResult, type ListRunsOptions, type ListRunsResult, type ListScheduledEmailsOptions, type ListSecretKeysInput, type ListTriggersResult, type ListUsersOptions, type ListUsersResult, type LogEntry, type LogLevel, type LoginHistoryEntry, type LoginRequest, type LoginResponse, type MeResponse, type MemberPermissionsResult, type MintAccessTokenClaims, type MintAccessTokenResult, type MonitoringResponse, type MonitoringSeverity, type NativeStepContext, type NativeTaskDefinition, type TaskRunStatus as NativeTaskRunStatus, NetworkError, NotFoundError, type OAuthAuthorizeInput, type OAuthAuthorizeResult, type OAuthCodeExchangeInput, type OAuthProvider, type OAuthProvidersResult, type OidcDiscoveryDocument, type OidcUserInfoResponse, type OrgRole, type OrgScopedTokenResponse, type OrgTokenPayload, type OrganizationInvitation, type OrganizationMember, type OrganizationMembership, type OrganizationsListResult, type PageInput, type PaginatedResponse, type PaginationInput, type ParsedConnectionUrl, type PasskeyRegistrationInput, type PasskeyRegistrationOptions, type PasskeySummary, type PasskeysList, type PasswordSetInput, type Permission, type PkceMethod, type Plan, type PlatformAccessTokenClaims, type PlatformFunctionsDownloadBundleResult, type PlatformLogoutInput, type PlatformPasswordChangeInput, type PlatformPasswordChangeResult, type PlatformPasswordSetInput, type PlatformPasswordSetResult, type PlatformPasswordStatusResult, type PlatformRealtimeChannel, type PlatformRealtimeCreateChannelResult, type PlatformRealtimeDeleteChannelResult, type PlatformRealtimeListChannelsResult, type PlatformRealtimeStatusResult, type PlatformRefreshInput, type PlatformRefreshResult, type PlatformSessionRenameInput, type PlatformSessionRenameResult, type PlatformSessionRevokeAllResult, type PlatformSessionRevokeInput, type PlatformSessionRevokeOtherResult, type PlatformSessionRevokeResult, type PlatformSessionsListResult, type PlatformUserDeleteInput, type PlatformUserDeleteResult, type PlatformUserExportResult, type PlatformUserRecord, type PlatformUserResolution, type ProcessEvent, type ProcessInfo, type ProcessStartOptions, type ProcessSummary, type ProjectMetadata, type PromoCode, type PromoRedemption, type PromoStatus, type PromoType, type PromoValidationPreview, type PublishEventResult, type PushCampaign, type PushCampaignStats, type PushCampaignVariant, type PushNotification, type PushNotificationPayload, type PushSegment, type PushSegmentFilter, type PushServiceWorkerConfig, type PushSubscription, type QueryLogsOptions, type QueryLogsResult, RETRYABLE_CODES, RateLimitError, type RateLimitStatusFilter, type RateLimitStatusResult, type RateLimitStrategiesFilter, type RateLimitStrategiesResult, type RateLimitStrategyDeleteInput, type RateLimitStrategyDeleteResult, type RateLimitStrategyUpsertInput, type RateLimitStrategyUpsertResult, type RealtimeEmitRequest, type RealtimeEmitResponse, type RealtimeHistoryRequest, type RealtimeHistoryResponse, type RecordActivityInput, type RecordActivityResult, type RedeemPromoInput, type RedeemPromoResult, type RedeemReferralInput, type RedeemResult, type ReferralCode, type ReferralStats, type RegisterInput, type RegisterRequest, type RegisterResponse, type ResendEmailVerificationRequest, type ResendEmailVerificationResponse, type RestClient, type RestClientConfig, type RestDynamicConfig, type RetryConfig, type RevokeTokenOptions, type Role, type RollbackDeployRequest, type Run, RunHandle, type RunLogsResult, type RunResourceSpec, type RunResult, type RunStatus, type RunTarget, type RunVolumeMount, type CreateRunOptions as RunWorkerOptions, RunsClient, SandboxClient, type SandboxFile, SandboxFiles, type SandboxOptions, SandboxProcesses, type SandboxRecord, SandboxWatch, type ScheduleEmailOptions, type ScheduledEmail, type ScheduledEmailStats, type ScheduledEmailsResult, type SearchInput, type SearchResponse, type SearchResultItem, type SearchStatsResult, type SearchType, type SecretKeyInfo, type SecurityAlert, type SecurityAlertsList, type SecurityScoreResult, type SecuritySettings, type SendEmailOptions, type SendResult, type SendTemplatedEmailOptions, type SendToUserOptions, type SessionResult, type SetConsentsInput, type SetEnvVarRequest, type SignedUrlOptions, StepCompleteSignal, StepSleepSignal, type StoredLogEntry, type StreakDefinition, type StreakFrequency, type StreakState, type StreamMessage, type SubmitScoreInput, type SubmitScoreResult, type Subscription, type SuccessResponse, type SylphxClientInput, type SylphxConfig, type SylphxConfigInput, SylphxError, type SylphxErrorCode, type SylphxErrorOptions, type TaskInput, type TaskResult, type TaskStatus, type TaskTarget, type TextCompletionInput, type TextCompletionResponse, TimeoutError, type TokenIntrospectionResult, type TokenResponse, type Tool, type ToolCall, type TrackClickInput, type TrackInput, type Trigger, type TriggerDeployRequest, type TriggerSource, type TriggerSourceType, type TriggerStatus, type TriggerTarget, type TriggerTargetType, TriggersClient, type TwoFactorEnableResult, type TwoFactorSetupResult, type TwoFactorVerifyRequest, type UpdateOrgInput, type UpdatePromoInput, type UpdateRoleInput, type UpdateTriggerOptions, type UploadCreateOptions, type UploadProgressEvent, type UpsertDocumentInput, type UpsertDocumentResult, type User, type UserAchievement, type UserConsent, type UserDataExport, type UserFullProfile, type UserOrganization, type UserProfile, type UserSecuritySettings, type UserSession, type UserSessionsList, type UserUpdateProfileInput, type ValidatePromoInput, type ValidatePromoResult, ValidationError, type VisionInput, type WatchEntry, type WatchOptions, type WebhookConfig, type WebhookConfigUpdate, type WebhookDeliveriesResult, type WebhookDelivery, type WebhookStats, RunHandle as WorkerHandle, type RunLogsResult as WorkerLogsResult, type RunResourceSpec as WorkerResourceSpec, type RunResult as WorkerResult, type Run as WorkerRun, type RunStatus as WorkerStatus, type RunVolumeMount as WorkerVolumeMount, WorkersClient, acceptAllConsents, acceptOrganizationInvitation, assignMemberRole, audit, authorizeOAuth, batchIndex, canDeleteOrganization, canManageMembers, canManageSettings, cancelScheduledEmail, cancelTask, captureException, captureExceptionRaw, captureMessage, chat, chatStream, checkFlag, complete, confirmEmailChange, cookies, createCheckout, createClient, createConfig, createCron, createDynamicRestClient, createOrganization, createPermission, createPortalSession, createPromo, createRestClient, createRole, createServerClient, createServiceWorkerScript, createStepContext, createTasksHandler, createTracker, debugError, debugLog, debugTimer, debugWarn, declineOptionalConsents, deleteCron, deleteDocument, deleteEnvVar, deleteOrganization, deletePasskey, deletePermission, deletePromo, deleteRole, deleteUser, deleteUserAccount, device, disableDebug, disableTwoFactor, disconnectOAuthProvider, dpop, embed, enableDebug, exchangeOAuthCode, exponentialBackoff, exportUserData, extendedSignUp, forgotPassword, functions, generateAnonymousId, generatePkce, getAchievement, getAchievementPoints, getAchievements, getAllFlags, getAllSecrets, getAllStreaks, getBackupCodes, getBillingBalance, getBillingUsage, getBuildLogHistory, getCircuitBreakerState, getConsentHistory, getConsentTypes, getDatabaseConnectionString, getDatabaseStatus, getDebugMode, getDeployHistory, getDeployStatus, getErrorCode, getErrorMessage, getFacets, getFlagPayload, getFlags, getLeaderboard, getMemberPermissions, getMyReferralCode, getOidcDiscoveryDocument, getOrgScopedToken, getOrganization, getOrganizationInvitations, getOrganizationMembers, getOrganizations, getPlans, getProjectMetadata, getPromo, getPushPreferences, getRealtimeHistory, getReferralLeaderboard, getReferralStats, getRestErrorMessage, getRole, getScheduledEmail, getScheduledEmailStats, getSearchStats, getSecret, getSecrets, getSecurityScore, getSession, getStreak, getSubscription, getTask, getUser, getUserByEmail, getUserConsents, getUserLeaderboardRank, getUserProfile, getUserSecurity, getVariant, getWebhookConfig, getWebhookDeliveries, getWebhookDelivery, getWebhookStats, hasAllPermissions, hasAnyPermission, hasConsent, hasError, hasPermission, hasRole, hasSecret, identify, impersonation, incrementAchievementProgress, indexDocument, ingestLogs, initPushServiceWorker, installGlobalDebugHelpers, introspectToken, inviteOrganizationMember, inviteUser, isEmailConfigured, isEnabled, isRetryableError, isSylphxError, kvDelete, kvExists, kvExpire, kvGet, kvGetJSON, kvHget, kvHgetall, kvHset, kvIncr, kvLpush, kvLrange, kvMget, kvMset, kvRateLimit, kvScan, kvSet, kvSetJSON, kvZadd, kvZrange, leaveOrganization, linkAnonymousConsents, listEnvVars, listOAuthProviders, listOrganizations, listPasskeys, listPermissions, listPromoRedemptions, listPromos, listRoles, listScheduledEmails, listSecretKeys, listSecurityAlerts, listTasks, listUserSessions, listUsers, markAllSecurityAlertsRead, markSecurityAlertRead, oauth, page, parseOAuthCallback, password, pauseCron, platformAuth, campaigns as pushCampaigns, segments as pushSegments, queryLogs, rateLimits, realtime, realtimeEmit, recordStreakActivity, recoverStreak, redeemPromo, redeemReferralCode, refreshToken, regenerateBackupCodes, regenerateReferralCode, registerPush, registerPushServiceWorker, removeOrganizationMember, renamePasskey, renameUserSession, replayWebhookDelivery, requestEmailChange, rescheduleEmail, resendVerificationEmail, resetCircuitBreaker, resetDebugModeCache, resetPassword, resetPlatformCookieCache, resetPlatformJwksCache, resumeCron, revokeAllTokens, revokeOrganizationInvitation, revokeToken, revokeUserSession, rollbackDeploy, scheduleEmail, scheduleTask, search, sendEmail, sendEmailToUser, sendPush, sendTemplatedEmail, sessions, setConsents, setEnvVar, setPassword, setupTwoFactor, signIn, signOut, signUp, startPasskeyRegistration, storage, streamToString, submitScore, suspendUser, switchOrg, toSylphxError, track, trackBatch, trackClick, triggerDeploy, unlockAchievement, unregisterPush, updateOrganization, updateOrganizationMemberRole, updatePromo, updatePushPreferences, updateRole, updateUser, updateUserMetadata, updateUserProfile, updateWebhookConfig, upsertDocument, user, userInfo, validatePromo, verifyAccessToken, verifyChallenge, verifyEmail, verifyPasskeyRegistration, verifySignature as verifyTaskSignature, verifyTwoFactor, verifyTwoFactorEnable, withToken };
9674
+ export { ACHIEVEMENT_TIER_CONFIG, type AIListModelsOptions, type AIListModelsResponse, type AIMessage, type AIMessageRole, type AIModel, type AIModelInfo, type AIModelsResponse, type AIProvider, type AIRateLimitInfo, type AIRateLimitResponse, type AIRequestType, type AIStreamChunk, type AITool, type AIToolCall, type AIUsageResponse, type AIUsageStats, type AccessTokenPayload, type AchievementCategory, type AchievementCriteria, type AchievementCriterion, type AchievementDefinition, type AchievementTier, type AchievementType, type AchievementUnlockEvent, type AdminUser, type AuditQueryFilter, type AuditQueryResult, AuthenticationError, AuthorizationError, BILLING_ALLOWED_ROLES, BUILD_MINUTES_INCLUDED, BUILD_MINUTE_PRICES, BUILD_SIZE_MULTIPLIERS, BYTES_PER_GB, type BackupCodesResult, type BatchEvent, type BatchIndexInput, type BatchIndexResult, type BillingAllowedRole, type Breadcrumb, type BuildConnectionUrlInput, type BuildLog, type BuildLogHistoryResponse, type BuildMachineTier, CI_BUILD_MINUTE_PRICE_MICRODOLLARS, CI_FREE_MINUTES_PER_MONTH, CI_MACOS_MULTIPLIER, CI_MACOS_SIZE_MULTIPLIERS, CI_SIZE_MULTIPLIERS, COMPUTE_PRICE_PER_HOUR_MICRODOLLARS, COMPUTE_RAM_RATE_MICRODOLLARS, COMPUTE_VCPU_ACTIVE_RATE_MICRODOLLARS, COMPUTE_VCPU_IDLE_RATE_MICRODOLLARS, CONSOLE_APP_SLUG, CREDENTIAL_REGEX, CREDIT_EXPIRY_MONTHS, type CaptureExceptionRequest, type CaptureMessageRequest, type ChallengeMethod, type ChallengeType, type ChallengeVerifyInput, type ChallengeVerifyResult, type ChatCompletionInput, type ChatCompletionResponse, type ChatInput, type ChatMessage, type ChatResult, type ChatStreamChunk, type CircuitBreakerConfig, CircuitBreakerOpenError, type CircuitState, type CommandResult, type ConnectionCredentialType, type ConnectionEnv, type ConsentCategory, type ConsentHistoryEntry, type ConsentHistoryResult, type ConsentPurposeDefaults, type ConsentType, type ContentPart, type CopyFileOptions, type CreateOrgInput, type CreatePermissionInput, type CreatePromoInput, type CreateRoleInput, type CreateRunOptions, type CreateTriggerOptions, type CriteriaOperator, type CronInput, type CronSchedule, type CronSource, DEFAULT_MAX_REPLICAS, DEFAULT_POINTS_REWARD, DISCOUNT_DURATION_MONTHS, DISCOUNT_PERCENT, type DatabaseConnectionInfo, type DatabaseStatus, type DatabaseStatusInfo, type DebugCategory, type DeduplicationConfig, type DeleteAccountResult, type DeleteDocumentInput, type DeployHistoryResponse, type DeployInfo, type DeployStatus, type DeviceApproveInput, type DeviceApproveResult, type DeviceDenyInput, type DeviceDenyResult, type DeviceGrant, type DeviceInitInput, type DevicePollResult, type DynamicRestClient, ERROR_CODE_STATUS, type EmailChangeInput, type EmailConfirmInput, type EmbedInput, type EmbedResult, type EmbeddingInput, type EmbeddingResponse, type LeaderboardEntry as EngagementLeaderboardEntry, type LeaderboardResult as EngagementLeaderboardResult, type EnvVar, type ErrorCode, type ErrorResponse, type EventSource, type ExceptionFrame, type ExceptionValue, type ExecEvent, type ExecOptions, type ExecResult, type ErrorDetails$1 as ExtractedErrorDetails, FREE_COMPUTE_HOURS, FREE_STORAGE_GB, type FacetsResponse, type FileEvent, type FlagContext, type FlagResult, type GetConsentHistoryInput, type GetConsentsInput, type GetFacetsInput, type GetSecretInput, type GetSecretResult, type GetSecretsInput, type GetSecretsResult, HOURS_PER_MONTH, type HttpTarget, INSTANCE_TYPES, INSTANCE_TYPE_ALIASES, INSTANCE_TYPE_ORDER, INVOICE_DUE_DAYS, type IdentifyInput, type ImpersonationActive, type ImpersonationEndResult, type ImpersonationInfo, type ImpersonationStartResult, type IndexDocumentInput, type IndexDocumentResult, type IngestLogsResult, type InstanceTypeDefinition, type InstanceTypeId, InvalidConnectionUrlError, type InviteMemberInput, type InviteUserRequest, type InviteUserResponse, KV_FREE_STORAGE_GB, type KvExpireRequest, type KvHgetRequest, type KvHgetallRequest, type KvHsetRequest, type KvIncrRequest, type KvLpushRequest, type KvLrangeRequest, type KvMetric, type KvMgetRequest, type KvMsetRequest, type KvRateLimitRequest, type KvRateLimitResult, type KvScanOptions, type KvScanResult, type KvSetOptions, type KvSetRequest, type KvZMember, type KvZaddRequest, type KvZrangeRequest, LEGACY_INSTANCE_TYPE_ORDER, type LeaderboardAggregation, type LeaderboardDefinition, type LeaderboardEntry$1 as LeaderboardEntry, type LeaderboardOptions, type LeaderboardQueryOptions, type LeaderboardResetPeriod, type LeaderboardResult$1 as LeaderboardResult, type LeaderboardSortDirection, type LinkAnonymousConsentsInput, type ListFilesOptions, type ListPromosOptions, type ListPromosResult, type ListRedemptionsOptions, type ListRedemptionsResult, type ListRunsOptions, type ListRunsResult, type ListScheduledEmailsOptions, type ListSecretKeysInput, type ListTriggersResult, type ListUsersOptions, type ListUsersResult, type LogEntry, type LogLevel, type LoginHistoryEntry, type LoginRequest, type LoginResponse, MAX_PASSWORD_LENGTH, MAX_PAYMENT_ATTEMPTS, MICRODOLLARS_PER_CENT, MIN_PASSWORD_LENGTH, type MeResponse, type MemberPermissionsResult, type MintAccessTokenClaims, type MintAccessTokenResult, type MonitoringResponse, type MonitoringSeverity, type NativeStepContext, type NativeTaskDefinition, type TaskRunStatus as NativeTaskRunStatus, NetworkError, NotFoundError, type OAuthAuthorizeInput, type OAuthAuthorizeResult, type OAuthCodeExchangeInput, type OAuthProvider, type OAuthProvidersResult, type OidcDiscoveryDocument, type OidcUserInfoResponse, type OrgRole, type OrgScopedTokenResponse, type OrgTokenPayload, type OrganizationInvitation, type OrganizationMember, type OrganizationMembership, type OrganizationsListResult, PASSWORD_REQUIREMENTS, PLATFORM_PLANS, PLATFORM_PLAN_ORDER, PLATFORM_PLAN_ORDER_ALL, PREMIUM_TRIAL_DAYS, type PageInput, type PaginatedResponse, type PaginationInput, type ParsedConnectionUrl, type ParsedUserAgent, type PasskeyRegistrationInput, type PasskeyRegistrationOptions, type PasskeySummary, type PasskeysList, type PasswordSetInput, type Permission, type PkceMethod, type Plan, type PlatformAccessTokenClaims, type PlatformFunctionsDownloadBundleResult, type PlatformLogoutInput, type PlatformPasswordChangeInput, type PlatformPasswordChangeResult, type PlatformPasswordSetInput, type PlatformPasswordSetResult, type PlatformPasswordStatusResult, type PlatformPlanDefinition, type PlatformPlanFeatures, type PlatformPlanId, type PlatformPlanLimits, type PlatformRealtimeChannel, type PlatformRealtimeCreateChannelResult, type PlatformRealtimeDeleteChannelResult, type PlatformRealtimeListChannelsResult, type PlatformRealtimeStatusResult, type PlatformRefreshInput, type PlatformRefreshResult, type PlatformSessionRenameInput, type PlatformSessionRenameResult, type PlatformSessionRevokeAllResult, type PlatformSessionRevokeInput, type PlatformSessionRevokeOtherResult, type PlatformSessionRevokeResult, type PlatformSessionsListResult, type PlatformUserDeleteInput, type PlatformUserDeleteResult, type PlatformUserExportResult, type PlatformUserRecord, type PlatformUserResolution, type ProcessEvent, type ProcessInfo, type ProcessStartOptions, type ProcessSummary, type ProjectMetadata, type PromoCode, type PromoRedemption, type PromoStatus, type PromoType, type PromoValidationPreview, type PublishEventResult, type PushCampaign, type PushCampaignStats, type PushCampaignVariant, type PushNotification, type PushNotificationPayload, type PushSegment, type PushSegmentFilter, type PushServiceWorkerConfig, type PushSubscription, type QueryLogsOptions, type QueryLogsResult, RETRYABLE_CODES, RateLimitError, type RateLimitStatusFilter, type RateLimitStatusResult, type RateLimitStrategiesFilter, type RateLimitStrategiesResult, type RateLimitStrategyDeleteInput, type RateLimitStrategyDeleteResult, type RateLimitStrategyUpsertInput, type RateLimitStrategyUpsertResult, type RealtimeEmitRequest, type RealtimeEmitResponse, type RealtimeHistoryRequest, type RealtimeHistoryResponse, type RealtimeMetric, type RecordActivityInput, type RecordActivityResult, type RedeemPromoInput, type RedeemPromoResult, type RedeemReferralInput, type RedeemResult, type ReferralCode, type ReferralStats, type RegisterInput, type RegisterRequest, type RegisterResponse, type ResendEmailVerificationRequest, type ResendEmailVerificationResponse, type RestClient, type RestClientConfig, type RestDynamicConfig, type RetryConfig, type RevokeTokenOptions, type Role, type RollbackDeployRequest, type Run, RunHandle, type RunLogsResult, type RunMachineSize, type RunResult, type RunStatus, type RunTarget, type RunVolumeMount, type CreateRunOptions as RunWorkerOptions, RunsClient, SERVICE_METRICS, STORAGE_PRICE_PER_GB_MONTH_MICRODOLLARS, SandboxClient, type SandboxFile, SandboxFiles, type SandboxMachineSize, type SandboxOptions, SandboxProcesses, type SandboxRecord, SandboxWatch, type ScheduleEmailOptions, type ScheduledEmail, type ScheduledEmailStats, type ScheduledEmailsResult, type SearchInput, type SearchResponse, type SearchResultItem, type SearchStatsResult, type SearchType, type SecretKeyInfo, type SecurityAlert, type SecurityAlertsList, type SecurityScoreResult, type SecuritySettings, type SendEmailOptions, type SendResult, type SendTemplatedEmailOptions, type SendToUserOptions, type ServiceMetrics, type SessionResult, type SetConsentsInput, type SetEnvVarRequest, type SignedUrlOptions, StepCompleteSignal, StepSleepSignal, type StoredLogEntry, type StreakDefinition, type StreakFrequency, type StreakState, type StreamMessage, type SubmitScoreInput, type SubmitScoreResult, type Subscription, type SuccessResponse, type SylphxClientInput, type SylphxConfig, type SylphxConfigInput, SylphxError, type SylphxErrorCode, type SylphxErrorOptions, TRANSFER_PRICE_PER_GB_MICRODOLLARS, type TaskInput, type TaskResult, type TaskStatus, type TaskTarget, type TextCompletionInput, type TextCompletionResponse, TimeoutError, type TokenIntrospectionResult, type TokenResponse, type Tool, type ToolCall, type TrackClickInput, type TrackInput, type Trigger, type TriggerDeployRequest, type TriggerRunMachineSize, type TriggerSource, type TriggerSourceType, type TriggerStatus, type TriggerTarget, type TriggerTargetType, TriggersClient, type TwoFactorEnableResult, type TwoFactorSetupResult, type TwoFactorVerifyRequest, type UpdateOrgInput, type UpdatePromoInput, type UpdateRoleInput, type UpdateTriggerOptions, type UploadCreateOptions, type UploadProgressEvent, type UpsertDocumentInput, type UpsertDocumentResult, type User, type UserAchievement, type UserConsent, type UserDataExport, type UserFullProfile, type UserOrganization, type UserProfile, type UserSecuritySettings, type UserSession, type UserSessionsList, type UserUpdateProfileInput, type ValidatePromoInput, type ValidatePromoResult, ValidationError, type VisionInput, type WatchEntry, type WatchOptions, type WebhookConfig, type WebhookConfigUpdate, type WebhookDeliveriesResult, type WebhookDelivery, type WebhookStats, RunHandle as WorkerHandle, type RunLogsResult as WorkerLogsResult, type RunResult as WorkerResult, type Run as WorkerRun, type RunStatus as WorkerStatus, type RunVolumeMount as WorkerVolumeMount, WorkersClient, acceptAllConsents, acceptOrganizationInvitation, assignMemberRole, audit, authorizeOAuth, batchIndex, buildConnectionUrl, calculatePercentage, canDeleteOrganization, canManageMembers, canManageSettings, cancelScheduledEmail, cancelTask, captureException, captureExceptionRaw, captureMessage, centsToDollars, chat, chatStream, checkFlag, complete, confirmEmailChange, cookies, createCheckout, createClient, createConfig, createCron, createDynamicRestClient, createOrganization, createPermission, createPortalSession, createPromo, createRestClient, createRole, createServerClient, createServiceWorkerScript, createStepContext, createTasksHandler, createTracker, debugError, debugLog, debugTimer, debugWarn, declineOptionalConsents, deleteCron, deleteDocument, deleteEnvVar, deleteOrganization, deletePasskey, deletePermission, deletePromo, deleteRole, deleteUser, deleteUserAccount, device, disableDebug, disableTwoFactor, disconnectOAuthProvider, dpop, embed, enableDebug, escapeCsvField, escapeHtml, exchangeOAuthCode, exponentialBackoff, exportUserData, extendedSignUp, getErrorDetails$1 as extractErrorDetails, getErrorMessage$1 as extractErrorMessage, forgotPassword, formatBytes, formatCents, formatCurrency, formatDate, formatDateTime, formatDuration, formatMicrodollars, formatMonthYear, formatNumber, formatPercent, formatRelativeTime, formatRelativeTimeShort, formatTime, functions, generateAnonymousId, generatePkce, generateReferralCode, generateSlug, getAchievement, getAchievementPoints, getAchievements, getActivePlans, getAllFlags, getAllSecrets, getAllStreaks, getAvailableInstanceTypes, getBackupCodes, getBaseUrl, getBillingBalance, getBillingStatusVariant, getBillingUsage, getBuildLogHistory, getCircuitBreakerState, getConsentHistory, getConsentTypes, getDatabaseConnectionString, getDatabaseStatus, getDebugMode, getDefaultInstanceType, getDeployHistory, getDeployStatus, getEnvPrefix, getErrorCode, getErrorDetails, getErrorMessage, getFacets, getFlagPayload, getFlags, getInvoiceStatusVariant, getLeaderboard, getMemberPermissions, getMyReferralCode, getOidcDiscoveryDocument, getOrgScopedToken, getOrganization, getOrganizationInvitations, getOrganizationMembers, getOrganizations, getPlanMonthlyPrice, getPlans, getProjectMetadata, getPromo, getPushPreferences, getRealtimeHistory, getReferralLeaderboard, getReferralStats, getRestErrorMessage, getRole, getSafeErrorMessage, getScheduledEmail, getScheduledEmailStats, getSearchStats, getSecret, getSecrets, getSecurityScore, getSession, getStreak, getSubscription, getTask, getUser, getUserByEmail, getUserConsents, getUserLeaderboardRank, getUserProfile, getUserSecurity, getVariant, getWebhookConfig, getWebhookDeliveries, getWebhookDelivery, getWebhookStats, hasAllPermissions, hasAnyPermission, hasBillingAccess, hasConsent, hasError, hasPermission, hasRole, hasSecret, identify, impersonation, incrementAchievementProgress, indexDocument, ingestLogs, initPushServiceWorker, installGlobalDebugHelpers, introspectToken, inviteOrganizationMember, inviteUser, isChallengeRequired, isEmailConfigured, isEnabled, isPlanDeprecated, isRetryableError, isSylphxError, isValidInstanceType, kvDelete, kvExists, kvExpire, kvGet, kvGetJSON, kvHget, kvHgetall, kvHset, kvIncr, kvLpush, kvLrange, kvMget, kvMset, kvRateLimit, kvScan, kvSet, kvSetJSON, kvZadd, kvZrange, leaveOrganization, linkAnonymousConsents, listEnvVars, listOAuthProviders, listOrganizations, listPasskeys, listPermissions, listPromoRedemptions, listPromos, listRoles, listScheduledEmails, listSecretKeys, listSecurityAlerts, listTasks, listUserSessions, listUsers, markAllSecurityAlertsRead, markSecurityAlertRead, microsToDollars, oauth, page, parseConnectionUrl, parseOAuthCallback, parseUserAgent, password, pauseCron, platformAuth, campaigns as pushCampaigns, segments as pushSegments, queryLogs, rateLimits, realtime, realtimeEmit, recordStreakActivity, recoverStreak, redeemPromo, redeemReferralCode, refreshToken, regenerateBackupCodes, regenerateReferralCode, registerPush, registerPushServiceWorker, removeOrganizationMember, renamePasskey, renameUserSession, replayWebhookDelivery, requestEmailChange, rescheduleEmail, resendVerificationEmail, resetCircuitBreaker, resetDebugModeCache, resetPassword, resetPlatformCookieCache, resetPlatformJwksCache, resolveCanonicalInstanceType, resolveMaxReplicas, resolveResources, resumeCron, revokeAllTokens, revokeOrganizationInvitation, revokeToken, revokeUserSession, rollbackDeploy, safeJsonParse, scheduleEmail, scheduleTask, search, sendEmail, sendEmailToUser, sendPush, sendTemplatedEmail, sessions, setConsents, setEnvVar, setPassword, setupTwoFactor, signIn, signOut, signUp, startPasskeyRegistration, storage, streamToString, submitScore, suspendUser, switchOrg, toSylphxError, track, trackBatch, trackClick, triggerDeploy, unlockAchievement, unregisterPush, updateOrganization, updateOrganizationMemberRole, updatePromo, updatePushPreferences, updateRole, updateUser, updateUserMetadata, updateUserProfile, updateWebhookConfig, upsertDocument, user, userInfo, validateInstanceTypeForPlan, validatePromo, verifyAccessToken, verifyChallenge, verifyEmail, verifyPasskeyRegistration, verifySignature as verifyTaskSignature, verifyTwoFactor, verifyTwoFactorEnable, withToken };