@feelflow/ffid-sdk 5.22.1 → 5.24.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.
@@ -1,5 +1,5 @@
1
- import { F as FFIDLogger, a as FFIDError, b as FFIDCacheAdapter, c as FFIDVerifyAccessTokenOptions, d as FFIDApiResponse, e as FFIDOAuthUserInfo } from '../ffid-client-DM0ZhIDV.js';
2
- export { f as FFIDAddMemberParams, g as FFIDAddMemberRequest, h as FFIDAddMemberResponse, i as FFIDAssignableMemberRole, j as FFIDCacheConfig, k as FFIDClient, l as FFIDConfig, m as FFIDListMembersResponse, n as FFIDMemberRole, o as FFIDOrganization, p as FFIDOrganizationMember, q as FFIDOtpSendResponse, r as FFIDOtpVerifyResponse, s as FFIDPasswordResetConfirmResponse, t as FFIDPasswordResetResponse, u as FFIDPasswordResetVerifyResponse, v as FFIDProfileCallOptions, w as FFIDProvisionMemberPlan, x as FFIDProvisionMemberPlanStatus, y as FFIDProvisionMemberResult, z as FFIDProvisionMemberStatus, A as FFIDProvisionOrganizationDryRun, B as FFIDProvisionOrganizationMemberInput, C as FFIDProvisionOrganizationOutcome, D as FFIDProvisionOrganizationParams, E as FFIDProvisionOrganizationResponse, G as FFIDProvisionUserDryRun, H as FFIDProvisionUserOutcome, I as FFIDProvisionUserParams, J as FFIDProvisionUserProfileInput, K as FFIDProvisionUserResponse, L as FFIDProvisionedOrganization, M as FFIDProvisionedUser, N as FFIDRemoveMemberResponse, O as FFIDResetSessionResponse, P as FFIDSubscription, Q as FFIDUpdateMemberRoleResponse, R as FFIDUpdateUserProfileRequest, S as FFIDUser, T as FFIDUserProfile, U as TokenData, V as TokenStore, W as createFFIDClient, X as createTokenStore } from '../ffid-client-DM0ZhIDV.js';
1
+ import { F as FFIDLogger, a as FFIDError, b as FFIDCacheAdapter, c as FFIDVerifyAccessTokenOptions, d as FFIDApiResponse, e as FFIDOAuthUserInfo } from '../ffid-client-DX2PTTFr.js';
2
+ export { f as FFIDAddMemberParams, g as FFIDAddMemberRequest, h as FFIDAddMemberResponse, i as FFIDAssignableMemberRole, j as FFIDCacheConfig, k as FFIDClient, l as FFIDConfig, m as FFIDListMembersResponse, n as FFIDMemberRole, o as FFIDOrganization, p as FFIDOrganizationMember, q as FFIDOtpSendResponse, r as FFIDOtpVerifyResponse, s as FFIDPasswordResetConfirmResponse, t as FFIDPasswordResetResponse, u as FFIDPasswordResetVerifyResponse, v as FFIDProfileCallOptions, w as FFIDProvisionMemberPlan, x as FFIDProvisionMemberPlanStatus, y as FFIDProvisionMemberResult, z as FFIDProvisionMemberStatus, A as FFIDProvisionOrganizationDryRun, B as FFIDProvisionOrganizationMemberInput, C as FFIDProvisionOrganizationOutcome, D as FFIDProvisionOrganizationParams, E as FFIDProvisionOrganizationResponse, G as FFIDProvisionUserDryRun, H as FFIDProvisionUserOutcome, I as FFIDProvisionUserParams, J as FFIDProvisionUserProfileInput, K as FFIDProvisionUserResponse, L as FFIDProvisionedOrganization, M as FFIDProvisionedUser, N as FFIDRemoveMemberResponse, O as FFIDResetSessionResponse, P as FFIDSubscription, Q as FFIDUpdateMemberRoleResponse, R as FFIDUpdateUserProfileRequest, S as FFIDUser, T as FFIDUserProfile, U as TokenData, V as TokenStore, W as createFFIDClient, X as createTokenStore } from '../ffid-client-DX2PTTFr.js';
3
3
  export { D as DEFAULT_API_BASE_URL, a as DEFAULT_OAUTH_SCOPES } from '../constants-D61jqRIO.js';
4
4
  import { z } from 'zod';
5
5
  import '../types-Cjb9J0rL.js';
@@ -233,4 +233,160 @@ declare function decodeConsentCookie(raw: string | null | undefined): FFIDConsen
233
233
 
234
234
  declare const CONSENT_COOKIE_NAME = "ffid_consent";
235
235
 
236
- export { ALL_DENIED_EXCEPT_NECESSARY, CONSENT_COOKIE_NAME, COOKIE_VERSION, FFIDCacheAdapter, type FFIDConsentCategories, type FFIDConsentCategoryCode, type FFIDCookieStoreLike, type FFIDErrorCode, FFIDOAuthUserInfo, FFIDVerifyAccessTokenOptions, FFID_ERROR_CODES, type KVNamespaceLike, createKVCacheAdapter, createMemoryCacheAdapter, createVerifyAccessToken, decodeConsentCookie, encodeConsentCookie, getFFIDConsentFromCookieHeader, getFFIDConsentFromCookies };
236
+ /**
237
+ * Public types for the confidential / BFF server auth helpers (#4261 / #4269).
238
+ * React/DOM-free — see `src/server/auth/server-auth-client.ts`.
239
+ */
240
+
241
+ /** Configuration for {@link createServerAuthClient}. */
242
+ interface ServerAuthConfig {
243
+ /** FFID service code (== OAuth `client_id` unless `clientId` is overridden). */
244
+ serviceCode: string;
245
+ /** OAuth `client_id`. Defaults to `serviceCode`. */
246
+ clientId?: string;
247
+ /**
248
+ * confidential-client secret — a `service_api_key` (`ffid_sk_live_…`) carrying
249
+ * the `oauth:client_auth` scope (PR-A1 #4267). Read from a server-only env var;
250
+ * never sent to the browser.
251
+ */
252
+ clientSecret: string;
253
+ /** FFID API base URL. Defaults to `DEFAULT_API_BASE_URL` (`https://id.feelflow.net`). */
254
+ apiBaseUrl?: string;
255
+ /** Server callback URL, registered in the service's `allowed_redirect_uris`. */
256
+ redirectUri: string;
257
+ /** OAuth scope (space-separated), forwarded to `/oauth/authorize?scope=…`. */
258
+ scope: string;
259
+ /**
260
+ * Optional request timeout (ms) applied to token fetches via
261
+ * `AbortSignal.timeout` (#4260). Unset → no timeout (fetch default).
262
+ */
263
+ timeout?: number | undefined;
264
+ }
265
+ /** Session tokens established by the BFF flow. Persist via {@link sessionCookies}. */
266
+ interface ServerSessionTokens {
267
+ accessToken: string;
268
+ refreshToken: string;
269
+ /** Access-token expiry as epoch milliseconds. */
270
+ expiresAt: number;
271
+ }
272
+ /** Options for {@link ServerAuthClient.buildAuthorizeUrl}. */
273
+ interface BuildAuthorizeUrlOptions {
274
+ /**
275
+ * `'signup'` は `?screen_hint=signup` を転送する(OIDC `prompt=create`
276
+ * 相当の意図の FFID 独自パラメータ)。
277
+ */
278
+ screenHint?: 'signup';
279
+ /** Forwards `?organization_id=…` (trimmed; empty is ignored). */
280
+ organizationId?: string;
281
+ /** Forwards OIDC `prompt` (`select_account` / `login`) to the upstream chooser (#4027). */
282
+ prompt?: 'login' | 'select_account';
283
+ }
284
+ /** Result of {@link ServerAuthClient.buildAuthorizeUrl}. */
285
+ interface BuildAuthorizeUrlResult {
286
+ /** Authorize URL to 302 the browser to. */
287
+ url: string;
288
+ /** Random `state` — persist in an httpOnly cookie and pass back as `storedState`. */
289
+ state: string;
290
+ }
291
+ /** Input to {@link ServerAuthClient.handleCallback}. */
292
+ interface HandleCallbackInput {
293
+ /** The callback request URL (absolute). `code` / `state` are read from its query. */
294
+ url: string | URL;
295
+ /** The `state` previously stored in the httpOnly cookie (undefined if absent). */
296
+ storedState: string | undefined;
297
+ }
298
+ /**
299
+ * Discriminated result of a server token operation. Mirrors {@link FFIDApiResponse}:
300
+ * exactly one of `tokens` / `error` is present.
301
+ */
302
+ type ServerTokenResult = {
303
+ tokens: ServerSessionTokens;
304
+ error?: undefined;
305
+ } | {
306
+ tokens?: undefined;
307
+ error: FFIDError;
308
+ };
309
+ /** Framework-agnostic confidential / BFF auth client. */
310
+ interface ServerAuthClient {
311
+ /**
312
+ * Build the authorize URL and a fresh `state`. The caller stores `state` in an
313
+ * httpOnly cookie, then 302s to `url`. No `code_challenge` is sent (v1 uses
314
+ * `client_secret`, not PKCE).
315
+ */
316
+ buildAuthorizeUrl(opts?: BuildAuthorizeUrlOptions): BuildAuthorizeUrlResult;
317
+ /**
318
+ * Validate `state` (CSRF, fail-closed) then exchange `code` for tokens using
319
+ * the `client_secret` (server→server, browser never sees the secret or tokens).
320
+ */
321
+ handleCallback(input: HandleCallbackInput): Promise<ServerTokenResult>;
322
+ /** Refresh tokens (`refresh_token` grant, `client_secret`-authenticated). */
323
+ refresh(refreshToken: string): Promise<ServerTokenResult>;
324
+ }
325
+ /** Attributes for the session `Set-Cookie` (name is fixed — see {@link FFID_SESSION_COOKIE_NAME}). */
326
+ interface CookieOptions {
327
+ /** `Path` attribute. Default `/`. */
328
+ path?: string;
329
+ /** `Domain` attribute. Omitted by default (host-only cookie). */
330
+ domain?: string;
331
+ /** `SameSite` attribute. Default `lax` (required for the cross-site callback redirect). */
332
+ sameSite?: 'lax' | 'strict' | 'none';
333
+ /**
334
+ * `Secure` attribute. Default `true`. ⚠️ `false` にすると cookie が平文 HTTP
335
+ * でも送信されるようになり、本番環境では非推奨(通常は変更しないこと)。
336
+ */
337
+ secure?: boolean;
338
+ /**
339
+ * `HttpOnly` attribute. Default `true`. ⚠️ `false` にするとトークンが
340
+ * ページ JS(`document.cookie`)から読めるようになり、本モジュールの
341
+ * 機密性モデルが破れる — 通常は変更しないこと。
342
+ */
343
+ httpOnly?: boolean;
344
+ /** `Max-Age` in seconds. Default 30 days. */
345
+ maxAge?: number;
346
+ }
347
+
348
+ /** Create a confidential / BFF auth client bound to one service's credentials. */
349
+ declare function createServerAuthClient(config: ServerAuthConfig): ServerAuthClient;
350
+
351
+ /**
352
+ * httpOnly session cookie codec for the confidential / BFF flow (#4261 / #4269).
353
+ *
354
+ * v1 stores the whole {@link ServerSessionTokens} in a single base64url-JSON
355
+ * cookie (`ffid_session`). httpOnly + Secure + SameSite=Lax by default so the
356
+ * browser can never read the tokens and the cookie survives the top-level
357
+ * callback redirect. The 4 KB per-cookie limit applies; access-token encryption
358
+ * and access/refresh split are documented future extensions (設計 spec
359
+ * (docs/02-design/2026-07-08-sdk-confidential-bff-design.md) §11).
360
+ *
361
+ * React/DOM-free: pure string I/O. The caller applies the returned `Set-Cookie`
362
+ * strings (e.g. `res.headers.append('Set-Cookie', c)`).
363
+ */
364
+
365
+ /** Fixed session cookie name (read/serialize must agree — not configurable). */
366
+ declare const FFID_SESSION_COOKIE_NAME = "ffid_session";
367
+ declare function serialize(tokens: ServerSessionTokens, opts?: CookieOptions): string[];
368
+ declare function read(cookieHeader: string | undefined): ServerSessionTokens | null;
369
+ declare function clear(opts?: Omit<CookieOptions, 'maxAge'>): string[];
370
+ /** httpOnly session cookie serialize / read / clear (returns `Set-Cookie` values). */
371
+ declare const sessionCookies: {
372
+ serialize: typeof serialize;
373
+ read: typeof read;
374
+ clear: typeof clear;
375
+ };
376
+
377
+ /**
378
+ * Server-side OAuth `state` generation for the confidential / BFF flow (#4261).
379
+ *
380
+ * React/DOM-free: uses Web Crypto (`globalThis.crypto.getRandomValues`), which
381
+ * is available in Node 18+ and Edge runtimes. Unlike `src/auth/state.ts` (the
382
+ * browser flow), this never touches `window` / web storage — the caller persists
383
+ * the returned `state` in an httpOnly cookie instead.
384
+ */
385
+ /**
386
+ * Generate a cryptographically-random, URL-safe OAuth `state` (32 hex chars).
387
+ * The caller stores this in an httpOnly `Secure` `SameSite=Lax` cookie and
388
+ * validates it on the callback (CSRF defense, RFC 6749 §10.12).
389
+ */
390
+ declare function generateServerState(): string;
391
+
392
+ export { ALL_DENIED_EXCEPT_NECESSARY, type BuildAuthorizeUrlOptions, type BuildAuthorizeUrlResult, CONSENT_COOKIE_NAME, COOKIE_VERSION, type CookieOptions, FFIDCacheAdapter, type FFIDConsentCategories, type FFIDConsentCategoryCode, type FFIDCookieStoreLike, type FFIDErrorCode, FFIDOAuthUserInfo, FFIDVerifyAccessTokenOptions, FFID_ERROR_CODES, FFID_SESSION_COOKIE_NAME, type HandleCallbackInput, type KVNamespaceLike, type ServerAuthClient, type ServerAuthConfig, type ServerSessionTokens, type ServerTokenResult, createKVCacheAdapter, createMemoryCacheAdapter, createServerAuthClient, createVerifyAccessToken, decodeConsentCookie, encodeConsentCookie, generateServerState, getFFIDConsentFromCookieHeader, getFFIDConsentFromCookies, sessionCookies };
@@ -85,7 +85,9 @@ function createMemoryStore() {
85
85
  function isTokenData(value) {
86
86
  if (typeof value !== "object" || value === null) return false;
87
87
  const obj = value;
88
- return typeof obj.accessToken === "string" && typeof obj.refreshToken === "string" && typeof obj.expiresAt === "number";
88
+ return typeof obj.accessToken === "string" && typeof obj.refreshToken === "string" && // Number.isFinite also rejects NaN/Infinity (e.g. a crafted `1e999` JSON
89
+ // literal parses to Infinity and would never trip the expiry check — #4271)
90
+ typeof obj.expiresAt === "number" && Number.isFinite(obj.expiresAt);
89
91
  }
90
92
  function createTokenStore(storageType) {
91
93
  if (storageType === "memory") {
@@ -1221,7 +1223,7 @@ function createNonContractMethods(deps) {
1221
1223
  }
1222
1224
 
1223
1225
  // src/client/version-check.ts
1224
- var SDK_VERSION = "5.22.1";
1226
+ var SDK_VERSION = "5.24.1";
1225
1227
  var SDK_USER_AGENT = `FFID-SDK/${SDK_VERSION} (TypeScript)`;
1226
1228
  var SDK_VERSION_HEADER = "X-FFID-SDK-Version";
1227
1229
  function sdkHeaders() {
@@ -1276,7 +1278,7 @@ function validateTokenResponse(tokenResponse) {
1276
1278
  if (!tokenResponse.refresh_token) {
1277
1279
  invalid.push("refresh_token");
1278
1280
  }
1279
- if (typeof tokenResponse.expires_in !== "number" || tokenResponse.expires_in <= 0) {
1281
+ if (typeof tokenResponse.expires_in !== "number" || !Number.isFinite(tokenResponse.expires_in) || tokenResponse.expires_in <= 0) {
1280
1282
  invalid.push("expires_in");
1281
1283
  }
1282
1284
  if (invalid.length > 0) {
@@ -1291,8 +1293,15 @@ function createOAuthTokenMethods(deps) {
1291
1293
  resolvedRedirectUri,
1292
1294
  tokenStore,
1293
1295
  logger,
1296
+ timeout,
1294
1297
  errorCodes
1295
1298
  } = deps;
1299
+ function withTimeout2(init) {
1300
+ if (timeout !== void 0) {
1301
+ return { ...init, signal: AbortSignal.timeout(timeout) };
1302
+ }
1303
+ return init;
1304
+ }
1296
1305
  async function exchangeCodeForTokens(code, codeVerifier, opts) {
1297
1306
  const url = `${baseUrl}${OAUTH_TOKEN_ENDPOINT}`;
1298
1307
  logger.debug("Exchanging code for tokens:", url);
@@ -1328,12 +1337,12 @@ function createOAuthTokenMethods(deps) {
1328
1337
  }
1329
1338
  let response;
1330
1339
  try {
1331
- response = await fetch(url, {
1340
+ response = await fetch(url, withTimeout2({
1332
1341
  method: "POST",
1333
1342
  credentials: "omit",
1334
1343
  headers: { "Content-Type": "application/x-www-form-urlencoded", ...sdkHeaders() },
1335
1344
  body: new URLSearchParams(body).toString()
1336
- });
1345
+ }));
1337
1346
  } catch (error) {
1338
1347
  logger.error("Network error during token exchange:", error);
1339
1348
  return {
@@ -1396,7 +1405,7 @@ function createOAuthTokenMethods(deps) {
1396
1405
  logger.debug("Refreshing access token:", url);
1397
1406
  let response;
1398
1407
  try {
1399
- response = await fetch(url, {
1408
+ response = await fetch(url, withTimeout2({
1400
1409
  method: "POST",
1401
1410
  credentials: "omit",
1402
1411
  headers: { "Content-Type": "application/x-www-form-urlencoded", ...sdkHeaders() },
@@ -1405,7 +1414,7 @@ function createOAuthTokenMethods(deps) {
1405
1414
  refresh_token: tokens.refreshToken,
1406
1415
  client_id: clientId
1407
1416
  }).toString()
1408
- });
1417
+ }));
1409
1418
  } catch (error) {
1410
1419
  logger.error("Network error during token refresh:", error);
1411
1420
  return {
@@ -1475,7 +1484,7 @@ function createOAuthTokenMethods(deps) {
1475
1484
  async function revokeOAuthToken(token, tokenTypeHint) {
1476
1485
  const url = `${baseUrl}${OAUTH_REVOKE_ENDPOINT}`;
1477
1486
  try {
1478
- const response = await fetch(url, {
1487
+ const response = await fetch(url, withTimeout2({
1479
1488
  method: "POST",
1480
1489
  credentials: "omit",
1481
1490
  headers: { "Content-Type": "application/x-www-form-urlencoded", ...sdkHeaders() },
@@ -1484,9 +1493,10 @@ function createOAuthTokenMethods(deps) {
1484
1493
  client_id: clientId,
1485
1494
  token_type_hint: tokenTypeHint
1486
1495
  }).toString()
1487
- });
1496
+ }));
1488
1497
  return response.ok;
1489
- } catch {
1498
+ } catch (err) {
1499
+ logger.debug("Token revoke request failed (client-side; e.g. timeout/network):", err);
1490
1500
  return false;
1491
1501
  }
1492
1502
  }
@@ -2887,6 +2897,7 @@ function createFFIDClient(config) {
2887
2897
  resolvedRedirectUri,
2888
2898
  tokenStore,
2889
2899
  logger,
2900
+ timeout,
2890
2901
  errorCodes: FFID_ERROR_CODES
2891
2902
  });
2892
2903
  async function fetchWithAuth(endpoint, options = {}, authOverride) {
@@ -3381,4 +3392,269 @@ function getFFIDConsentFromCookieHeader(cookieHeader) {
3381
3392
  return decodeConsentCookie(decodeURIComponent(value));
3382
3393
  }
3383
3394
 
3384
- export { ALL_DENIED_EXCEPT_NECESSARY, CONSENT_COOKIE_NAME, COOKIE_VERSION, FFID_ERROR_CODES, createFFIDClient, createKVCacheAdapter, createMemoryCacheAdapter, createTokenStore, createVerifyAccessToken, decodeConsentCookie, encodeConsentCookie, getFFIDConsentFromCookieHeader, getFFIDConsentFromCookies };
3395
+ // src/server/auth/server-state.ts
3396
+ var STATE_RANDOM_BYTES2 = 16;
3397
+ var HEX_RADIX = 16;
3398
+ function generateServerState() {
3399
+ const bytes = new Uint8Array(STATE_RANDOM_BYTES2);
3400
+ globalThis.crypto.getRandomValues(bytes);
3401
+ return Array.from(bytes, (b) => b.toString(HEX_RADIX).padStart(2, "0")).join("");
3402
+ }
3403
+
3404
+ // src/server/auth/server-oauth-token.ts
3405
+ var OAUTH_TOKEN_ENDPOINT2 = "/api/v1/oauth/token";
3406
+ var MS_PER_SECOND3 = 1e3;
3407
+ function withTimeout(init, timeout) {
3408
+ if (timeout !== void 0) {
3409
+ return { ...init, signal: AbortSignal.timeout(timeout) };
3410
+ }
3411
+ return init;
3412
+ }
3413
+ function validateTokenResponse2(r) {
3414
+ const invalid = [];
3415
+ if (!r.access_token) invalid.push("access_token");
3416
+ if (!r.refresh_token) invalid.push("refresh_token");
3417
+ if (typeof r.expires_in !== "number" || !Number.isFinite(r.expires_in) || r.expires_in <= 0) {
3418
+ invalid.push("expires_in");
3419
+ }
3420
+ return invalid.length > 0 ? `\u30C8\u30FC\u30AF\u30F3\u30EC\u30B9\u30DD\u30F3\u30B9\u306B\u4E0D\u6B63\u306A\u30D5\u30A3\u30FC\u30EB\u30C9\u304C\u3042\u308A\u307E\u3059: ${invalid.join(", ")}` : null;
3421
+ }
3422
+ function toTokens(r) {
3423
+ return {
3424
+ accessToken: r.access_token,
3425
+ refreshToken: r.refresh_token,
3426
+ expiresAt: Date.now() + r.expires_in * MS_PER_SECOND3
3427
+ };
3428
+ }
3429
+ function fail(code, message) {
3430
+ return { error: { code, message } };
3431
+ }
3432
+ async function postToken(deps, body, fallbackErrorCode) {
3433
+ const url = `${deps.apiBaseUrl}${OAUTH_TOKEN_ENDPOINT2}`;
3434
+ let response;
3435
+ try {
3436
+ response = await fetch(
3437
+ url,
3438
+ withTimeout(
3439
+ {
3440
+ method: "POST",
3441
+ credentials: "omit",
3442
+ headers: { "Content-Type": "application/x-www-form-urlencoded", ...sdkHeaders() },
3443
+ body: new URLSearchParams(body).toString()
3444
+ },
3445
+ deps.timeout
3446
+ )
3447
+ );
3448
+ } catch (error) {
3449
+ return fail(
3450
+ FFID_ERROR_CODES.NETWORK_ERROR,
3451
+ error instanceof Error ? error.message : "\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\u30A8\u30E9\u30FC\u304C\u767A\u751F\u3057\u307E\u3057\u305F"
3452
+ );
3453
+ }
3454
+ let json;
3455
+ try {
3456
+ json = await response.json();
3457
+ } catch {
3458
+ return fail(
3459
+ FFID_ERROR_CODES.PARSE_ERROR,
3460
+ `\u30C8\u30FC\u30AF\u30F3\u30EC\u30B9\u30DD\u30F3\u30B9\u306E\u89E3\u6790\u306B\u5931\u6557\u3057\u307E\u3057\u305F (status: ${response.status})`
3461
+ );
3462
+ }
3463
+ if (!response.ok) {
3464
+ const errorBody = json;
3465
+ return fail(errorBody.error ?? fallbackErrorCode, errorBody.error_description ?? "\u30C8\u30FC\u30AF\u30F3\u51E6\u7406\u306B\u5931\u6557\u3057\u307E\u3057\u305F");
3466
+ }
3467
+ const validationError = validateTokenResponse2(json);
3468
+ if (validationError) {
3469
+ return fail(fallbackErrorCode, validationError);
3470
+ }
3471
+ return { tokens: toTokens(json) };
3472
+ }
3473
+ function exchangeAuthorizationCodeServer(deps, code) {
3474
+ return postToken(
3475
+ deps,
3476
+ {
3477
+ grant_type: "authorization_code",
3478
+ code,
3479
+ client_id: deps.clientId,
3480
+ client_secret: deps.clientSecret,
3481
+ redirect_uri: deps.redirectUri
3482
+ },
3483
+ FFID_ERROR_CODES.TOKEN_EXCHANGE_ERROR
3484
+ );
3485
+ }
3486
+ function refreshTokensServer(deps, refreshToken) {
3487
+ return postToken(
3488
+ deps,
3489
+ {
3490
+ grant_type: "refresh_token",
3491
+ refresh_token: refreshToken,
3492
+ client_id: deps.clientId,
3493
+ client_secret: deps.clientSecret
3494
+ },
3495
+ FFID_ERROR_CODES.TOKEN_REFRESH_ERROR
3496
+ );
3497
+ }
3498
+
3499
+ // src/server/auth/server-auth-client.ts
3500
+ var OAUTH_AUTHORIZE_ENDPOINT2 = "/api/v1/oauth/authorize";
3501
+ var SCREEN_HINT_SIGNUP2 = "signup";
3502
+ function createServerAuthClient(config) {
3503
+ if (!config.serviceCode?.trim()) {
3504
+ throw new Error("FFID Server Auth: serviceCode \u304C\u672A\u8A2D\u5B9A\u3067\u3059");
3505
+ }
3506
+ if (!config.clientSecret?.trim()) {
3507
+ throw new Error("FFID Server Auth: clientSecret \u304C\u672A\u8A2D\u5B9A\u3067\u3059");
3508
+ }
3509
+ if (!config.redirectUri?.trim()) {
3510
+ throw new Error("FFID Server Auth: redirectUri \u304C\u672A\u8A2D\u5B9A\u3067\u3059");
3511
+ }
3512
+ if (!config.scope?.trim()) {
3513
+ throw new Error(
3514
+ "FFID Server Auth: scope \u304C\u672A\u8A2D\u5B9A\u3067\u3059\u3002`DEFAULT_OAUTH_SCOPES` \u3092 import \u3059\u308B\u304B\u660E\u793A\u7684\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044"
3515
+ );
3516
+ }
3517
+ const apiBaseUrl = config.apiBaseUrl ?? DEFAULT_API_BASE_URL;
3518
+ const clientId = config.clientId ?? config.serviceCode;
3519
+ const deps = {
3520
+ apiBaseUrl,
3521
+ clientId,
3522
+ clientSecret: config.clientSecret,
3523
+ redirectUri: config.redirectUri,
3524
+ timeout: config.timeout
3525
+ };
3526
+ function buildAuthorizeUrl(opts) {
3527
+ const state = generateServerState();
3528
+ const params = new URLSearchParams({
3529
+ response_type: "code",
3530
+ client_id: clientId,
3531
+ scope: config.scope,
3532
+ redirect_uri: config.redirectUri,
3533
+ state
3534
+ });
3535
+ const organizationId = opts?.organizationId?.trim();
3536
+ if (organizationId) params.set("organization_id", organizationId);
3537
+ if (opts?.screenHint === SCREEN_HINT_SIGNUP2) params.set("screen_hint", SCREEN_HINT_SIGNUP2);
3538
+ if (opts?.prompt) params.set("prompt", opts.prompt);
3539
+ return { url: `${apiBaseUrl}${OAUTH_AUTHORIZE_ENDPOINT2}?${params.toString()}`, state };
3540
+ }
3541
+ async function handleCallback(input) {
3542
+ let url;
3543
+ try {
3544
+ url = typeof input.url === "string" ? new URL(input.url) : input.url;
3545
+ } catch {
3546
+ return {
3547
+ error: {
3548
+ code: FFID_ERROR_CODES.TOKEN_EXCHANGE_ERROR,
3549
+ message: "\u30B3\u30FC\u30EB\u30D0\u30C3\u30AF URL \u306E\u89E3\u6790\u306B\u5931\u6557\u3057\u307E\u3057\u305F"
3550
+ }
3551
+ };
3552
+ }
3553
+ const returnedState = url.searchParams.get("state") ?? void 0;
3554
+ if (!input.storedState || !returnedState || input.storedState !== returnedState) {
3555
+ return {
3556
+ error: {
3557
+ code: FFID_ERROR_CODES.STATE_MISMATCH_ERROR,
3558
+ message: "OAuth state \u304C\u4E00\u81F4\u3057\u307E\u305B\u3093\u3002CSRF \u306E\u53EF\u80FD\u6027\u304C\u3042\u308B\u305F\u3081\u8A8D\u8A3C\u3092\u4E2D\u6B62\u3057\u307E\u3057\u305F"
3559
+ }
3560
+ };
3561
+ }
3562
+ const errorParam = url.searchParams.get("error");
3563
+ if (errorParam) {
3564
+ return {
3565
+ error: {
3566
+ code: errorParam,
3567
+ message: url.searchParams.get("error_description") ?? "\u8A8D\u53EF\u30B5\u30FC\u30D0\u30FC\u304C\u30A8\u30E9\u30FC\u3092\u8FD4\u3057\u307E\u3057\u305F"
3568
+ }
3569
+ };
3570
+ }
3571
+ const code = url.searchParams.get("code");
3572
+ if (!code) {
3573
+ return {
3574
+ error: {
3575
+ code: FFID_ERROR_CODES.TOKEN_EXCHANGE_ERROR,
3576
+ message: "authorization code \u304C\u30B3\u30FC\u30EB\u30D0\u30C3\u30AF\u306B\u542B\u307E\u308C\u3066\u3044\u307E\u305B\u3093"
3577
+ }
3578
+ };
3579
+ }
3580
+ return exchangeAuthorizationCodeServer(deps, code);
3581
+ }
3582
+ function refresh(refreshToken) {
3583
+ return refreshTokensServer(deps, refreshToken);
3584
+ }
3585
+ return { buildAuthorizeUrl, handleCallback, refresh };
3586
+ }
3587
+
3588
+ // src/server/auth/session-cookies.ts
3589
+ var FFID_SESSION_COOKIE_NAME = "ffid_session";
3590
+ var DEFAULT_PATH = "/";
3591
+ var DEFAULT_SAME_SITE = "lax";
3592
+ var HOURS_PER_DAY2 = 24;
3593
+ var DEFAULT_MAX_AGE_DAYS = 30;
3594
+ var DEFAULT_MAX_AGE_SECONDS = 60 * 60 * HOURS_PER_DAY2 * DEFAULT_MAX_AGE_DAYS;
3595
+ var BASE64_GROUP = 4;
3596
+ function base64UrlEncode2(input) {
3597
+ const bytes = new TextEncoder().encode(input);
3598
+ const binary = Array.from(bytes, (byte) => String.fromCharCode(byte)).join("");
3599
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
3600
+ }
3601
+ function base64UrlDecode(input) {
3602
+ const b64 = input.replace(/-/g, "+").replace(/_/g, "/");
3603
+ const remainder = b64.length % BASE64_GROUP;
3604
+ const padded = remainder === 0 ? b64 : b64 + "=".repeat(BASE64_GROUP - remainder);
3605
+ const bytes = Uint8Array.from(atob(padded), (char) => char.charCodeAt(0));
3606
+ return new TextDecoder().decode(bytes);
3607
+ }
3608
+ function sameSiteLabel(value) {
3609
+ return value.charAt(0).toUpperCase() + value.slice(1);
3610
+ }
3611
+ function buildSetCookie(nameValue, opts, maxAge) {
3612
+ const path = opts.path ?? DEFAULT_PATH;
3613
+ const sameSite = opts.sameSite ?? DEFAULT_SAME_SITE;
3614
+ const secure = opts.secure ?? true;
3615
+ const httpOnly = opts.httpOnly ?? true;
3616
+ const attrs = [nameValue, `Path=${path}`, `Max-Age=${maxAge}`, `SameSite=${sameSiteLabel(sameSite)}`];
3617
+ if (httpOnly) attrs.push("HttpOnly");
3618
+ if (secure) attrs.push("Secure");
3619
+ if (opts.domain) attrs.push(`Domain=${opts.domain}`);
3620
+ return attrs.join("; ");
3621
+ }
3622
+ function parseCookieHeader(header) {
3623
+ const out = {};
3624
+ for (const part of header.split(";")) {
3625
+ const eq = part.indexOf("=");
3626
+ if (eq === -1) continue;
3627
+ const key = part.slice(0, eq).trim();
3628
+ if (key) out[key] = part.slice(eq + 1).trim();
3629
+ }
3630
+ return out;
3631
+ }
3632
+ function serialize(tokens, opts = {}) {
3633
+ const value = base64UrlEncode2(JSON.stringify(tokens));
3634
+ const maxAge = opts.maxAge ?? DEFAULT_MAX_AGE_SECONDS;
3635
+ return [buildSetCookie(`${FFID_SESSION_COOKIE_NAME}=${value}`, opts, maxAge)];
3636
+ }
3637
+ function read(cookieHeader) {
3638
+ if (!cookieHeader) return null;
3639
+ const raw = parseCookieHeader(cookieHeader)[FFID_SESSION_COOKIE_NAME];
3640
+ if (!raw) return null;
3641
+ try {
3642
+ const parsed = JSON.parse(base64UrlDecode(raw));
3643
+ if (typeof parsed.accessToken !== "string" || typeof parsed.refreshToken !== "string" || typeof parsed.expiresAt !== "number") {
3644
+ return null;
3645
+ }
3646
+ return {
3647
+ accessToken: parsed.accessToken,
3648
+ refreshToken: parsed.refreshToken,
3649
+ expiresAt: parsed.expiresAt
3650
+ };
3651
+ } catch {
3652
+ return null;
3653
+ }
3654
+ }
3655
+ function clear(opts = {}) {
3656
+ return [buildSetCookie(`${FFID_SESSION_COOKIE_NAME}=`, opts, 0)];
3657
+ }
3658
+ var sessionCookies = { serialize, read, clear };
3659
+
3660
+ export { ALL_DENIED_EXCEPT_NECESSARY, CONSENT_COOKIE_NAME, COOKIE_VERSION, FFID_ERROR_CODES, FFID_SESSION_COOKIE_NAME, createFFIDClient, createKVCacheAdapter, createMemoryCacheAdapter, createServerAuthClient, createTokenStore, createVerifyAccessToken, decodeConsentCookie, encodeConsentCookie, generateServerState, getFFIDConsentFromCookieHeader, getFFIDConsentFromCookies, sessionCookies };
@@ -1,4 +1,4 @@
1
- import { k as FFIDClient, e as FFIDOAuthUserInfo } from '../../ffid-client-CEJMpqRZ.cjs';
1
+ import { k as FFIDClient, e as FFIDOAuthUserInfo } from '../../ffid-client-D0Jh4bO7.cjs';
2
2
  import '../../types-Cjb9J0rL.cjs';
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { k as FFIDClient, e as FFIDOAuthUserInfo } from '../../ffid-client-DM0ZhIDV.js';
1
+ import { k as FFIDClient, e as FFIDOAuthUserInfo } from '../../ffid-client-DX2PTTFr.js';
2
2
  import '../../types-Cjb9J0rL.js';
3
3
 
4
4
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feelflow/ffid-sdk",
3
- "version": "5.22.1",
3
+ "version": "5.24.1",
4
4
  "description": "FeelFlow ID Platform SDK for React/Next.js applications",
5
5
  "keywords": [
6
6
  "feelflow",