@sylphx/sdk 0.28.0 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +30 -118
  3. package/dist/access.d.ts +659 -0
  4. package/dist/access.js +638 -0
  5. package/dist/access.js.map +1 -0
  6. package/dist/ai.d.ts +176 -0
  7. package/dist/ai.js +112 -0
  8. package/dist/ai.js.map +1 -0
  9. package/dist/artifacts.d.ts +165 -0
  10. package/dist/artifacts.js +129 -0
  11. package/dist/artifacts.js.map +1 -0
  12. package/dist/auth.d.ts +896 -0
  13. package/dist/auth.js +828 -0
  14. package/dist/auth.js.map +1 -0
  15. package/dist/billing.d.ts +758 -0
  16. package/dist/billing.js +553 -0
  17. package/dist/billing.js.map +1 -0
  18. package/dist/broker.d.ts +226 -0
  19. package/dist/broker.js +187 -0
  20. package/dist/broker.js.map +1 -0
  21. package/dist/build.d.ts +313 -0
  22. package/dist/build.js +271 -0
  23. package/dist/build.js.map +1 -0
  24. package/dist/common.d.ts +162 -0
  25. package/dist/common.js +41 -0
  26. package/dist/common.js.map +1 -0
  27. package/dist/config.d.ts +198 -0
  28. package/dist/config.js +168 -0
  29. package/dist/config.js.map +1 -0
  30. package/dist/connections.d.ts +354 -0
  31. package/dist/connections.js +313 -0
  32. package/dist/connections.js.map +1 -0
  33. package/dist/data.d.ts +858 -0
  34. package/dist/data.js +814 -0
  35. package/dist/data.js.map +1 -0
  36. package/dist/entitlement.d.ts +172 -0
  37. package/dist/entitlement.js +116 -0
  38. package/dist/entitlement.js.map +1 -0
  39. package/dist/events.d.ts +1324 -0
  40. package/dist/events.js +1227 -0
  41. package/dist/events.js.map +1 -0
  42. package/dist/hosting.d.ts +709 -0
  43. package/dist/hosting.js +611 -0
  44. package/dist/hosting.js.map +1 -0
  45. package/dist/index.d.ts +79 -33656
  46. package/dist/index.js +113 -0
  47. package/dist/index.js.map +1 -0
  48. package/dist/keys.d.ts +438 -0
  49. package/dist/keys.js +406 -0
  50. package/dist/keys.js.map +1 -0
  51. package/dist/methods.d.ts +2 -0
  52. package/dist/methods.js +3995 -0
  53. package/dist/methods.js.map +1 -0
  54. package/dist/network.d.ts +733 -0
  55. package/dist/network.js +711 -0
  56. package/dist/network.js.map +1 -0
  57. package/dist/notify.d.ts +1359 -0
  58. package/dist/notify.js +1282 -0
  59. package/dist/notify.js.map +1 -0
  60. package/dist/observability.d.ts +509 -0
  61. package/dist/observability.js +437 -0
  62. package/dist/observability.js.map +1 -0
  63. package/dist/release.d.ts +303 -0
  64. package/dist/release.js +214 -0
  65. package/dist/release.js.map +1 -0
  66. package/dist/runners.d.ts +262 -0
  67. package/dist/runners.js +238 -0
  68. package/dist/runners.js.map +1 -0
  69. package/dist/runtime.d.ts +88 -0
  70. package/dist/runtime.js +226 -0
  71. package/dist/runtime.js.map +1 -0
  72. package/dist/sandboxes.d.ts +1705 -0
  73. package/dist/sandboxes.js +1226 -0
  74. package/dist/sandboxes.js.map +1 -0
  75. package/dist/secrets.d.ts +508 -0
  76. package/dist/secrets.js +474 -0
  77. package/dist/secrets.js.map +1 -0
  78. package/dist/workflows.d.ts +678 -0
  79. package/dist/workflows.js +595 -0
  80. package/dist/workflows.js.map +1 -0
  81. package/package.json +33 -112
  82. package/dist/connect.d.ts +0 -2838
  83. package/dist/connect.mjs +0 -220
  84. package/dist/connect.mjs.map +0 -1
  85. package/dist/health/index.d.ts +0 -1394
  86. package/dist/health/index.mjs +0 -1394
  87. package/dist/health/index.mjs.map +0 -1
  88. package/dist/index.mjs +0 -38429
  89. package/dist/index.mjs.map +0 -1
  90. package/dist/nextjs/index.d.ts +0 -724
  91. package/dist/nextjs/index.mjs +0 -3332
  92. package/dist/nextjs/index.mjs.map +0 -1
  93. package/dist/react/index.d.ts +0 -13066
  94. package/dist/react/index.mjs +0 -35329
  95. package/dist/react/index.mjs.map +0 -1
  96. package/dist/server/index.d.ts +0 -2000
  97. package/dist/server/index.mjs +0 -3446
  98. package/dist/server/index.mjs.map +0 -1
  99. package/dist/web-analytics.d.ts +0 -90
  100. package/dist/web-analytics.mjs +0 -225
  101. package/dist/web-analytics.mjs.map +0 -1
@@ -1,724 +0,0 @@
1
- import { NextResponse, NextRequest } from 'next/server';
2
- import { AuthTokensResponse } from '@sylphx/contract';
3
-
4
- /**
5
- * Auth Functions
6
- *
7
- * Pure functions for authentication - no hidden state.
8
- * Each function takes config as the first parameter.
9
- *
10
- * Uses REST API at /api/sdk/auth/* for all operations.
11
- *
12
- * Types are re-exported from `@sylphx/contract` (ADR-084). The contract is
13
- * the single source of truth for every wire shape — this module only adds
14
- * SDK-specific ergonomics (User brand swap, introspection result, invite
15
- * envelopes, org-token claims).
16
- */
17
-
18
- /**
19
- * Token response — contract's `AuthTokensResponse.user` (optional `AuthUser`)
20
- * is re-mapped to the SDK's broader `User` type so legacy callers keep the
21
- * familiar brand. `AuthUser` and `User` are structurally identical, but
22
- * the SDK surface has wider reach (cookies, middleware, React hooks) and
23
- * renaming is out of scope for ADR-084 cleanup.
24
- */
25
- type TokenResponse = Omit<AuthTokensResponse, 'user'> & {
26
- user: User;
27
- };
28
-
29
- /**
30
- * SDK-specific types — cross-layer helpers and server-first configuration.
31
- *
32
- * Wire-shape types (API request/response envelopes) live in
33
- * `@sylphx/contract` and are re-exported per namespace from their SDK
34
- * module (e.g. `Plan` / `Subscription` from `./billing`, `ConsentType`
35
- * from `./consent`, `TokenResponse` from `./auth`). React-hook wrapper
36
- * shapes live in `./react/types` (tRPC-like convenience shapes that
37
- * are not part of the platform wire).
38
- *
39
- * History: pre-ADR-084 this file mirrored every wire shape the SDK
40
- * exposed; those aliases now come directly from `@sylphx/contract`.
41
- */
42
-
43
- /** SDK cookie/token shape. Richer authenticated surfaces live in `./react/types` `UserProfile`. */
44
- interface User {
45
- id: string;
46
- email: string;
47
- name: string | null;
48
- image?: string | null;
49
- emailVerified?: boolean;
50
- role?: string;
51
- createdAt?: string;
52
- }
53
- interface UserCookieData {
54
- user: User;
55
- /** Epoch ms when the session expires (client-side expiry check). */
56
- expiresAt: number;
57
- }
58
-
59
- /**
60
- * Cookie Management for Next.js — Single Source of Truth
61
- *
62
- * Architecture: Cookie-Centric Auth (Clerk Pattern)
63
- * ================================================
64
- *
65
- * ALL auth state lives in cookies. Zero localStorage for auth.
66
- *
67
- * Cookie Structure:
68
- * - __sylphx_{namespace}_session — HttpOnly JWT, 5 min (access token)
69
- * - __sylphx_{namespace}_refresh — HttpOnly, 30 days (refresh token)
70
- * - __sylphx_{namespace}_user — JS-readable, 5 min (user data for client hydration)
71
- *
72
- * Benefits:
73
- * 1. Single Source of Truth — no server/client state divergence
74
- * 2. XSS-safe — tokens never accessible to JavaScript
75
- * 3. Cross-tab sync — cookies shared across tabs automatically
76
- * 4. SSR works — auth() in Server Components reads cookies directly
77
- *
78
- * Security:
79
- * - Short token lifetime (5 min) like Clerk
80
- * - Server-side refresh in middleware
81
- * - SameSite=Lax for CSRF protection
82
- */
83
-
84
- /**
85
- * Get cookie names for a given namespace
86
- *
87
- * Namespace is derived from the secret key environment (dev/stg/prod).
88
- * This prevents cookies from different environments colliding.
89
- *
90
- * @example
91
- * getCookieNames('sylphx_prod')
92
- * // Returns:
93
- * // {
94
- * // SESSION: '__sylphx_prod_session',
95
- * // REFRESH: '__sylphx_prod_refresh',
96
- * // USER: '__sylphx_prod_user',
97
- * // }
98
- */
99
- declare function getCookieNames(namespace: string): {
100
- /** HttpOnly JWT access token (5 min) */
101
- SESSION: string;
102
- /** HttpOnly refresh token (30 days) */
103
- REFRESH: string;
104
- /** JS-readable user data for client hydration (5 min) */
105
- USER: string;
106
- /** HttpOnly active organization ID used to preserve org-scoped sessions */
107
- ACTIVE_ORG_ID: string;
108
- /** HttpOnly active organization slug used to preserve org-scoped sessions */
109
- ACTIVE_ORG_SLUG: string;
110
- };
111
- /**
112
- * Session token lifetime (5 minutes like Clerk)
113
- */
114
- declare const SESSION_TOKEN_LIFETIME: number;
115
- /**
116
- * Refresh token lifetime (30 days)
117
- */
118
- declare const REFRESH_TOKEN_LIFETIME: number;
119
- /**
120
- * Active organization context lifetime (30 days).
121
- *
122
- * This matches refresh-token lifetime: the org preference is session-scoped
123
- * state, not a permanent user preference. Clearing auth clears this too.
124
- */
125
- declare const ACTIVE_ORG_LIFETIME: number;
126
- /**
127
- * Cookie options for HttpOnly tokens (session, refresh)
128
- *
129
- * Security features:
130
- * - httpOnly: true — Not accessible via JavaScript (XSS protection)
131
- * - secure: true in production — Only sent over HTTPS
132
- * - sameSite: 'lax' — CSRF protection while allowing navigation
133
- */
134
- declare const SECURE_COOKIE_OPTIONS: {
135
- httpOnly: boolean;
136
- secure: boolean;
137
- sameSite: "lax";
138
- path: string;
139
- };
140
- /**
141
- * Cookie options for JS-readable user cookie
142
- *
143
- * This cookie contains only user info (no tokens) and enables:
144
- * - Client-side hydration without loading states
145
- * - Cross-tab sync via cookie visibility
146
- */
147
- declare const USER_COOKIE_OPTIONS: {
148
- httpOnly: boolean;
149
- secure: boolean;
150
- sameSite: "lax";
151
- path: string;
152
- };
153
- /**
154
- * Cookie options for active organization context.
155
- *
156
- * Active org is not a secret, but it controls which org-scoped JWT the SDK
157
- * restores after refresh. Keep it HttpOnly so browser JavaScript cannot
158
- * silently steer server-side auth context outside the official switch-org
159
- * route.
160
- */
161
- declare const ACTIVE_ORG_COOKIE_OPTIONS: {
162
- httpOnly: boolean;
163
- secure: boolean;
164
- sameSite: "lax";
165
- path: string;
166
- };
167
- /**
168
- * Auth cookies data returned by getAuthCookies
169
- */
170
- interface AuthCookiesData {
171
- /** Access token from SESSION cookie (HttpOnly) */
172
- sessionToken: string | null;
173
- /** Refresh token from REFRESH cookie (HttpOnly) */
174
- refreshToken: string | null;
175
- /** User data from USER cookie (JS-readable) */
176
- user: User | null;
177
- /** Expiry timestamp from USER cookie */
178
- expiresAt: number | null;
179
- }
180
- /**
181
- * Decode a cookie value without throwing on malformed percent-encoding.
182
- */
183
- declare function decodeCookieValue(value: string): string;
184
- /**
185
- * Read the last value for a cookie name from a raw Cookie header.
186
- *
187
- * Browsers can legitimately send duplicate cookie names when an application
188
- * has migrated between host-only and domain-scoped cookies. RFC 6265 orders
189
- * same-path duplicates by creation time, so the most recently set cookie is the
190
- * right value for auth session recovery.
191
- */
192
- declare function readCookieValueFromHeader(cookieHeader: string | null | undefined, name: string): string | null;
193
- /**
194
- * Get auth cookies from the request
195
- *
196
- * Used by auth() to read current auth state.
197
- */
198
- declare function getAuthCookies(namespace: string): Promise<AuthCookiesData>;
199
- /**
200
- * Set auth cookies from token response
201
- *
202
- * Sets all three cookies:
203
- * - SESSION: HttpOnly access token (5 min)
204
- * - REFRESH: HttpOnly refresh token (30 days)
205
- * - USER: JS-readable user data (5 min)
206
- *
207
- * @param namespace - Cookie namespace (e.g., 'sylphx_prod')
208
- * @param response - Token response from auth endpoint
209
- * @param options - Optional: custom expiresIn override
210
- */
211
- declare function setAuthCookies(namespace: string, response: TokenResponse, options?: {
212
- sessionLifetime?: number;
213
- }): Promise<void>;
214
- /**
215
- * Clear all auth cookies
216
- *
217
- * Call on sign out to remove all auth state.
218
- */
219
- declare function clearAuthCookies(namespace: string): Promise<void>;
220
- /**
221
- * Check if session is expired
222
- *
223
- * Uses a 30 second buffer to account for network latency.
224
- */
225
- declare function isSessionExpired(namespace: string): Promise<boolean>;
226
- /**
227
- * Check if we have a refresh token (can potentially refresh)
228
- */
229
- declare function hasRefreshToken(namespace: string): Promise<boolean>;
230
-
231
- /**
232
- * Set auth cookies on a NextResponse (for middleware use)
233
- *
234
- * Unlike setAuthCookies() which uses next/headers, this works with NextResponse.
235
- * Use this in middleware where you need to modify cookies on the response.
236
- */
237
- declare function setAuthCookiesMiddleware(response: NextResponse, namespace: string, tokens: TokenResponse): void;
238
- /**
239
- * Clear auth cookies on a NextResponse (for middleware use)
240
- */
241
- declare function clearAuthCookiesMiddleware(response: NextResponse, namespace: string): void;
242
- /**
243
- * Parse user cookie value (for client-side use)
244
- */
245
- declare function parseUserCookie(value: string): UserCookieData | null;
246
-
247
- interface SylphxMiddlewareConfig {
248
- /**
249
- * Routes that don't require authentication.
250
- * Supports exact paths and wildcards.
251
- *
252
- * @example ['/', '/about', '/pricing', '/blog/*']
253
- * @default ['/']
254
- */
255
- publicRoutes?: string[];
256
- /**
257
- * Routes that middleware should completely ignore.
258
- * Use for webhooks, static assets, or third-party integrations.
259
- *
260
- * @default []
261
- */
262
- ignoredRoutes?: string[];
263
- /**
264
- * URL to redirect unauthenticated users.
265
- * @default '/login'
266
- */
267
- signInUrl?: string;
268
- /**
269
- * URL to redirect after sign out.
270
- * @default '/'
271
- */
272
- afterSignOutUrl?: string;
273
- /**
274
- * URL to redirect after successful sign in.
275
- * @default '/dashboard'
276
- */
277
- afterSignInUrl?: string;
278
- /**
279
- * Auth routes prefix. Routes are mounted at:
280
- * - {prefix}/register - email/password registration handler
281
- * - {prefix}/login - credentials login handler
282
- * - {prefix}/verify-email - email verification handler
283
- * - {prefix}/oauth-providers - enabled social login providers
284
- * - {prefix}/oauth/authorize - social login start handler
285
- * - {prefix}/callback - OAuth callback handler
286
- * - {prefix}/passkey/options - passkey login challenge handler
287
- * - {prefix}/passkey/authenticate - passkey login verification handler
288
- * - {prefix}/verify-2fa - TOTP/backup-code verification handler
289
- * - {prefix}/forgot-password - password reset email handler
290
- * - {prefix}/reset-password - password reset verification handler
291
- * - {prefix}/session - safe session metadata handler
292
- * - {prefix}/signout - Sign out handler
293
- *
294
- * @default '/auth'
295
- */
296
- authPrefix?: string;
297
- /**
298
- * Same-origin BaaS proxy prefix.
299
- *
300
- * Mounted routes are allowlisted SDK-owned BaaS surfaces such as
301
- * `{prefix}/security/*` and `{prefix}/challenge/*`. The middleware converts
302
- * the HttpOnly session cookie into an upstream bearer token, so browser code
303
- * can use BaaS features without ever reading Platform access tokens.
304
- *
305
- * Set to `false` to disable the proxy.
306
- *
307
- * @default '/sylphx'
308
- */
309
- baasPrefix?: string | false;
310
- /**
311
- * Enable debug logging.
312
- * @default false
313
- */
314
- debug?: boolean;
315
- /**
316
- * Secret key for authentication.
317
- * Override to use a programmatic key instead of SYLPHX_SECRET_URL env var.
318
- *
319
- * Use case: Platform Console uses dynamically generated keys.
320
- *
321
- * @default credential parsed from process.env.SYLPHX_SECRET_URL
322
- */
323
- secretKey?: string;
324
- /**
325
- * Server connection URL for authentication.
326
- *
327
- * Format: sylphx://sk_<env>_<hex>@<tenant>.api.sylphx.com
328
- *
329
- * @default process.env.SYLPHX_SECRET_URL
330
- */
331
- secretUrl?: string;
332
- /**
333
- * Publishable key for browser-safe auth routes.
334
- *
335
- * Public auth handlers (`/auth/login`, `/auth/oauth-providers`,
336
- * `/auth/oauth/authorize`, password reset, passkeys) call runtime routes
337
- * guarded by projectAuth, which accepts pk_* only.
338
- *
339
- * @default credential parsed from process.env.SYLPHX_URL or
340
- * process.env.NEXT_PUBLIC_SYLPHX_URL
341
- */
342
- publishableKey?: string;
343
- /**
344
- * Public connection URL for browser-safe auth routes.
345
- *
346
- * Format: sylphx://pk_<env>_<hex>@<tenant>.api.sylphx.com
347
- *
348
- * @default process.env.SYLPHX_URL or process.env.NEXT_PUBLIC_SYLPHX_URL
349
- */
350
- publicUrl?: string;
351
- /**
352
- * Platform URL for API calls.
353
- * Override for self-hosted or same-origin deployments.
354
- *
355
- * @default resolved from SYLPHX_SECRET_URL, SYLPHX_URL, SYLPHX_BAAS_URL, or SYLPHX_RUNTIME_URL
356
- */
357
- platformUrl?: string;
358
- /**
359
- * Canonical public application URL used for OAuth callback URLs.
360
- *
361
- * Set this when the app is served behind a proxy, custom domain, or platform
362
- * generated hostname where the request URL may not be the user-facing origin.
363
- * Only the origin is used; callback path remains owned by `authPrefix`.
364
- *
365
- * @default request URL origin
366
- */
367
- appUrl?: string;
368
- /**
369
- * Callback to add custom headers/logic to responses.
370
- * Called for every non-auth-route request after SDK processing.
371
- *
372
- * Use case: Add security headers, tracking cookies, etc.
373
- *
374
- * @example
375
- * ```typescript
376
- * onResponse: (response, request) => {
377
- * response.headers.set('X-Custom-Header', 'value')
378
- * }
379
- * ```
380
- */
381
- onResponse?: (response: NextResponse, request: NextRequest) => void | Promise<void>;
382
- /**
383
- * Require authenticated requests to carry an active organization context.
384
- * When true, protected routes without an `org_id` JWT claim redirect to
385
- * `orgSelectionUrl`.
386
- *
387
- * @default false
388
- */
389
- orgRequired?: boolean;
390
- /**
391
- * URL for selecting an active organization when `orgRequired` is enabled.
392
- *
393
- * @default '/select-organization'
394
- */
395
- orgSelectionUrl?: string;
396
- /**
397
- * Active organization context behaviour.
398
- *
399
- * Enabled by default so Next.js apps get durable org-scoped sessions without
400
- * writing their own refresh/switch orchestration:
401
- * - `/auth/switch-org` records the selected org in SDK-owned HttpOnly cookies
402
- * - token refresh restores that org-scoped JWT when possible
403
- * - single-org users are auto-scoped after refresh
404
- *
405
- * Apps migrating from pre-SDK org cookies can list additional cookie names
406
- * for read compatibility. The SDK still writes only its own names.
407
- */
408
- organizationContext?: SylphxOrganizationContextConfig;
409
- }
410
- interface SylphxOrganizationContextConfig {
411
- /**
412
- * Preserve active organization context through refresh.
413
- * @default true
414
- */
415
- enabled?: boolean;
416
- /**
417
- * When no active org preference exists and the user has exactly one org,
418
- * automatically restore an org-scoped session token after refresh.
419
- * @default true
420
- */
421
- autoSelectSingleOrganization?: boolean;
422
- /**
423
- * Additional org-id cookie names to read during migration from existing apps.
424
- * The SDK-owned `__{namespace}_active_org_id` cookie is always read first.
425
- */
426
- additionalOrgIdCookies?: readonly string[];
427
- /**
428
- * Additional org-slug cookie names to read during migration from existing apps.
429
- * The SDK-owned `__{namespace}_active_org_slug` cookie is always read first.
430
- */
431
- additionalOrgSlugCookies?: readonly string[];
432
- }
433
-
434
- /**
435
- * Sylphx Unified Middleware — State of the Art
436
- *
437
- * ONE middleware function handles EVERYTHING:
438
- * - Auth routes (mounted automatically, zero manual API routes)
439
- * - BaaS routes (same-origin proxy, no browser bearer-token exposure)
440
- * - Token refresh (automatic, every request)
441
- * - Route protection
442
- * - Cookie management
443
- *
444
- * This follows Auth0 v4 / Clerk / Supabase patterns where middleware
445
- * handles all auth concerns. Apps don't need to create any /api/auth/* routes.
446
- *
447
- * @example
448
- * ```typescript
449
- * // middleware.ts (or proxy.ts for Next.js 16)
450
- * import { createSylphxMiddleware } from '@sylphx/sdk/nextjs'
451
- *
452
- * export default createSylphxMiddleware({
453
- * publicRoutes: ['/', '/about', '/pricing'],
454
- * })
455
- *
456
- * export const config = {
457
- * matcher: ['/((?!_next|.*\\..*).*)', '/'],
458
- * }
459
- * ```
460
- *
461
- * That's it. No /api/auth/* routes needed.
462
- */
463
-
464
- /**
465
- * Create Sylphx middleware — State of the Art
466
- *
467
- * ONE function handles everything:
468
- * - Auth routes ({authPrefix}/callback, {authPrefix}/signout)
469
- * - Token refresh (automatic, every request)
470
- * - Route protection
471
- * - Cookie management
472
- *
473
- * @example
474
- * ```typescript
475
- * // middleware.ts (or proxy.ts for Next.js 16)
476
- * import { createSylphxMiddleware } from '@sylphx/sdk/nextjs'
477
- *
478
- * export default createSylphxMiddleware({
479
- * publicRoutes: ['/', '/about', '/pricing'],
480
- * })
481
- *
482
- * export const config = {
483
- * matcher: ['/((?!_next|.*\\..*).*)', '/'],
484
- * }
485
- * ```
486
- */
487
- declare function createSylphxMiddleware(userConfig?: SylphxMiddlewareConfig): (request: NextRequest) => Promise<NextResponse>;
488
- declare const sylphxMiddleware: typeof createSylphxMiddleware;
489
- /**
490
- * Create recommended matcher config
491
- */
492
- declare function createMatcher(): {
493
- matcher: string[];
494
- };
495
- /**
496
- * Get cookie namespace from secret key (for advanced use)
497
- */
498
- declare function getNamespace(secretKey: string): string;
499
-
500
- /**
501
- * Server-side Auth Helpers for Next.js
502
- *
503
- * Use in Server Components and API Routes.
504
- *
505
- * Architecture: Cookie-Centric Single Source of Truth
506
- * ===================================================
507
- *
508
- * All auth state lives in cookies. The auth() function reads
509
- * from HttpOnly cookies and refreshes if needed.
510
- *
511
- * Cookie Structure:
512
- * - __sylphx_{namespace}_session — HttpOnly JWT (5 min)
513
- * - __sylphx_{namespace}_refresh — HttpOnly refresh token (30 days)
514
- * - __sylphx_{namespace}_user — JS-readable user data (5 min)
515
- */
516
-
517
- /**
518
- * Configure the SDK for server-side usage
519
- *
520
- * NOTE: This is optional! The SDK auto-configures from environment variables:
521
- * - SYLPHX_SECRET_URL
522
- *
523
- * Use this only if you need to override the default configuration.
524
- *
525
- * @example
526
- * ```ts
527
- * // Optional: Override default configuration
528
- * import { configureServer } from '@sylphx/sdk/nextjs'
529
- *
530
- * configureServer({
531
- * secretUrl: process.env.SYLPHX_SECRET_URL!,
532
- * })
533
- * ```
534
- */
535
- declare function configureServer(config: {
536
- secretKey?: string;
537
- secretUrl?: string;
538
- platformUrl?: string;
539
- /** Expected JWT aud (project slug). Required when platformUrl has no {slug}.api host. */
540
- audience?: string;
541
- /** JWT issuer origin; defaults to Platform issuer SSOT. */
542
- issuer?: string;
543
- }): void;
544
- /**
545
- * Auth state returned by auth()
546
- */
547
- interface AuthResult {
548
- userId: string | null;
549
- user: User | null;
550
- /** Session token (for internal use only - not exposed to client) */
551
- sessionToken: string | null;
552
- }
553
- /**
554
- * Get the current auth state (memoized per request)
555
- *
556
- * This is the primary way to check authentication in Server Components.
557
- * It reads from HttpOnly cookies and refreshes if needed.
558
- *
559
- * @example
560
- * ```ts
561
- * // In a Server Component
562
- * import { auth } from '@sylphx/platform-sdk/nextjs'
563
- *
564
- * export default async function Dashboard() {
565
- * const { userId, user } = await auth()
566
- *
567
- * if (!userId) {
568
- * redirect('/login')
569
- * }
570
- *
571
- * return <div>Hello, {user?.name}</div>
572
- * }
573
- * ```
574
- */
575
- declare const auth: () => Promise<AuthResult>;
576
- /**
577
- * Get the current user (null if not logged in)
578
- *
579
- * @example
580
- * ```ts
581
- * import { currentUser } from '@sylphx/platform-sdk/nextjs'
582
- *
583
- * export default async function Header() {
584
- * const user = await currentUser()
585
- * if (!user) return <SignIn />
586
- * return <span>Hello, {user.name}</span>
587
- * }
588
- * ```
589
- */
590
- declare function currentUser(): Promise<User | null>;
591
- /**
592
- * Get the current user ID (null if not logged in)
593
- */
594
- declare function currentUserId(): Promise<string | null>;
595
- /**
596
- * Handle OAuth callback - exchange code for tokens and set cookies
597
- *
598
- * NOTE: With createSylphxMiddleware(), this is handled automatically.
599
- * You don't need to create manual /api/auth/* routes.
600
- *
601
- * This function is exported for advanced use cases where you need
602
- * custom callback handling outside of the middleware flow.
603
- *
604
- * @example
605
- * ```ts
606
- * // Using middleware (recommended - zero manual routes)
607
- * import { createSylphxMiddleware } from '@sylphx/sdk/nextjs'
608
- * export default createSylphxMiddleware({ publicRoutes: ['/', '/about'] })
609
- *
610
- * // Middleware automatically handles /auth/callback
611
- * ```
612
- */
613
- declare function handleCallback(code: string): Promise<User>;
614
- /**
615
- * Sign out - clear cookies and optionally revoke token
616
- *
617
- * NOTE: With createSylphxMiddleware(), signout is handled automatically
618
- * at /auth/signout. No manual route needed.
619
- *
620
- * This function is exported for advanced use cases.
621
- *
622
- * @example
623
- * ```ts
624
- * // Using middleware (recommended)
625
- * // Navigate users to /auth/signout - middleware handles everything
626
- * <a href="/auth/signout">Sign Out</a>
627
- * ```
628
- */
629
- declare function signOut(): Promise<void>;
630
- /**
631
- * Sync tokens to cookies (server action)
632
- *
633
- * NOTE: With createSylphxMiddleware(), OAuth callbacks are handled
634
- * automatically at /auth/callback. This function is rarely needed.
635
- *
636
- * Use only for edge cases like custom OAuth providers not going
637
- * through the standard flow.
638
- */
639
- declare function syncAuthToCookies(tokens: TokenResponse): Promise<void>;
640
- /**
641
- * Get authorization URL for OAuth redirect
642
- */
643
- declare function getAuthorizationUrl(options?: {
644
- redirectUri?: string;
645
- mode?: 'login' | 'signup';
646
- state?: string;
647
- appId?: string;
648
- }): string;
649
- /**
650
- * Get the current session token for API calls
651
- *
652
- * This is for apps that need to call third-party APIs with the session token.
653
- * For same-origin API calls, cookies are sent automatically.
654
- *
655
- * @example
656
- * ```ts
657
- * // In an API route that needs to call external APIs
658
- * import { getSessionToken } from '@sylphx/platform-sdk/nextjs'
659
- *
660
- * export async function GET() {
661
- * const token = await getSessionToken()
662
- * if (!token) {
663
- * return new Response('Unauthorized', { status: 401 })
664
- * }
665
- *
666
- * // Call third-party API
667
- * const response = await fetch('https://api.example.com/data', {
668
- * headers: { Authorization: `Bearer ${token}` }
669
- * })
670
- * // ...
671
- * }
672
- * ```
673
- */
674
- declare function getSessionToken(): Promise<string | null>;
675
-
676
- /**
677
- * Token expiry buffer in milliseconds (30 seconds)
678
- *
679
- * Refresh tokens this many milliseconds BEFORE they expire
680
- * to account for network latency and clock skew.
681
- */
682
- declare const TOKEN_EXPIRY_BUFFER_MS = 30000;
683
- /** Session token lifetime in milliseconds (for React Query staleTime) */
684
- declare const SESSION_TOKEN_LIFETIME_MS: number;
685
-
686
- /**
687
- * Platform ID utilities for the Sylphx SDK
688
- *
689
- * Converts between raw UUIDs (used internally / in JWT sub claims) and
690
- * prefixed TypeID strings (used in all API responses and JWT pid claims).
691
- *
692
- * Uses TypeID spec v0.3.0 (Crockford base32, case-insensitive).
693
- * Also accepts legacy base58 format for backward compatibility.
694
- *
695
- * No external dependencies — pure TypeScript implementation of Crockford base32.
696
- *
697
- * @example
698
- * ```ts
699
- * import { encodeUserId, decodeUserId } from '@sylphx/sdk/nextjs'
700
- *
701
- * const prefixed = encodeUserId('018f4a3b-1c2d-7000-9abc-def012345678')
702
- * // => 'user_01h2xcejqtf2nbrexx3vqjhp41'
703
- *
704
- * const uuid = decodeUserId('user_01h2xcejqtf2nbrexx3vqjhp41')
705
- * // => '018f4a3b-1c2d-7000-9abc-def012345678'
706
- * ```
707
- */
708
- /**
709
- * Encode a raw UUID as a prefixed TypeID user ID.
710
- *
711
- * @param uuid - Raw UUID string (with or without dashes)
712
- * @returns Prefixed TypeID: `user_<crockford_base32>`
713
- */
714
- declare function encodeUserId(uuid: string): string;
715
- /**
716
- * Decode a prefixed user ID back to a raw UUID.
717
- * Accepts both TypeID (current) and base58 (legacy) formats.
718
- *
719
- * @param prefixedId - Prefixed user ID: `user_<encoded>`
720
- * @returns Raw UUID string, or null if invalid
721
- */
722
- declare function decodeUserId(prefixedId: string): string | null;
723
-
724
- export { ACTIVE_ORG_COOKIE_OPTIONS, ACTIVE_ORG_LIFETIME, type AuthCookiesData, type AuthResult, REFRESH_TOKEN_LIFETIME, SECURE_COOKIE_OPTIONS, SESSION_TOKEN_LIFETIME, SESSION_TOKEN_LIFETIME_MS, type SylphxMiddlewareConfig, type SylphxOrganizationContextConfig, TOKEN_EXPIRY_BUFFER_MS, USER_COOKIE_OPTIONS, type UserCookieData, auth, clearAuthCookies, clearAuthCookiesMiddleware, configureServer, createMatcher, createSylphxMiddleware, currentUser, currentUserId, decodeCookieValue, decodeUserId, encodeUserId, getAuthCookies, getAuthorizationUrl, getCookieNames, getNamespace, getSessionToken, handleCallback, hasRefreshToken, isSessionExpired, parseUserCookie, readCookieValueFromHeader, setAuthCookies, setAuthCookiesMiddleware, signOut, sylphxMiddleware, syncAuthToCookies };