@feelflow/ffid-sdk 5.22.0 → 5.24.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.
@@ -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 };
@@ -1221,7 +1221,7 @@ function createNonContractMethods(deps) {
1221
1221
  }
1222
1222
 
1223
1223
  // src/client/version-check.ts
1224
- var SDK_VERSION = "5.22.0";
1224
+ var SDK_VERSION = "5.24.0";
1225
1225
  var SDK_USER_AGENT = `FFID-SDK/${SDK_VERSION} (TypeScript)`;
1226
1226
  var SDK_VERSION_HEADER = "X-FFID-SDK-Version";
1227
1227
  function sdkHeaders() {
@@ -1291,8 +1291,15 @@ function createOAuthTokenMethods(deps) {
1291
1291
  resolvedRedirectUri,
1292
1292
  tokenStore,
1293
1293
  logger,
1294
+ timeout,
1294
1295
  errorCodes
1295
1296
  } = deps;
1297
+ function withTimeout2(init) {
1298
+ if (timeout !== void 0) {
1299
+ return { ...init, signal: AbortSignal.timeout(timeout) };
1300
+ }
1301
+ return init;
1302
+ }
1296
1303
  async function exchangeCodeForTokens(code, codeVerifier, opts) {
1297
1304
  const url = `${baseUrl}${OAUTH_TOKEN_ENDPOINT}`;
1298
1305
  logger.debug("Exchanging code for tokens:", url);
@@ -1328,12 +1335,12 @@ function createOAuthTokenMethods(deps) {
1328
1335
  }
1329
1336
  let response;
1330
1337
  try {
1331
- response = await fetch(url, {
1338
+ response = await fetch(url, withTimeout2({
1332
1339
  method: "POST",
1333
1340
  credentials: "omit",
1334
1341
  headers: { "Content-Type": "application/x-www-form-urlencoded", ...sdkHeaders() },
1335
1342
  body: new URLSearchParams(body).toString()
1336
- });
1343
+ }));
1337
1344
  } catch (error) {
1338
1345
  logger.error("Network error during token exchange:", error);
1339
1346
  return {
@@ -1396,7 +1403,7 @@ function createOAuthTokenMethods(deps) {
1396
1403
  logger.debug("Refreshing access token:", url);
1397
1404
  let response;
1398
1405
  try {
1399
- response = await fetch(url, {
1406
+ response = await fetch(url, withTimeout2({
1400
1407
  method: "POST",
1401
1408
  credentials: "omit",
1402
1409
  headers: { "Content-Type": "application/x-www-form-urlencoded", ...sdkHeaders() },
@@ -1405,7 +1412,7 @@ function createOAuthTokenMethods(deps) {
1405
1412
  refresh_token: tokens.refreshToken,
1406
1413
  client_id: clientId
1407
1414
  }).toString()
1408
- });
1415
+ }));
1409
1416
  } catch (error) {
1410
1417
  logger.error("Network error during token refresh:", error);
1411
1418
  return {
@@ -1475,7 +1482,7 @@ function createOAuthTokenMethods(deps) {
1475
1482
  async function revokeOAuthToken(token, tokenTypeHint) {
1476
1483
  const url = `${baseUrl}${OAUTH_REVOKE_ENDPOINT}`;
1477
1484
  try {
1478
- const response = await fetch(url, {
1485
+ const response = await fetch(url, withTimeout2({
1479
1486
  method: "POST",
1480
1487
  credentials: "omit",
1481
1488
  headers: { "Content-Type": "application/x-www-form-urlencoded", ...sdkHeaders() },
@@ -1484,9 +1491,10 @@ function createOAuthTokenMethods(deps) {
1484
1491
  client_id: clientId,
1485
1492
  token_type_hint: tokenTypeHint
1486
1493
  }).toString()
1487
- });
1494
+ }));
1488
1495
  return response.ok;
1489
- } catch {
1496
+ } catch (err) {
1497
+ logger.debug("Token revoke request failed (client-side; e.g. timeout/network):", err);
1490
1498
  return false;
1491
1499
  }
1492
1500
  }
@@ -2887,6 +2895,7 @@ function createFFIDClient(config) {
2887
2895
  resolvedRedirectUri,
2888
2896
  tokenStore,
2889
2897
  logger,
2898
+ timeout,
2890
2899
  errorCodes: FFID_ERROR_CODES
2891
2900
  });
2892
2901
  async function fetchWithAuth(endpoint, options = {}, authOverride) {
@@ -3381,4 +3390,269 @@ function getFFIDConsentFromCookieHeader(cookieHeader) {
3381
3390
  return decodeConsentCookie(decodeURIComponent(value));
3382
3391
  }
3383
3392
 
3384
- export { ALL_DENIED_EXCEPT_NECESSARY, CONSENT_COOKIE_NAME, COOKIE_VERSION, FFID_ERROR_CODES, createFFIDClient, createKVCacheAdapter, createMemoryCacheAdapter, createTokenStore, createVerifyAccessToken, decodeConsentCookie, encodeConsentCookie, getFFIDConsentFromCookieHeader, getFFIDConsentFromCookies };
3393
+ // src/server/auth/server-state.ts
3394
+ var STATE_RANDOM_BYTES2 = 16;
3395
+ var HEX_RADIX = 16;
3396
+ function generateServerState() {
3397
+ const bytes = new Uint8Array(STATE_RANDOM_BYTES2);
3398
+ globalThis.crypto.getRandomValues(bytes);
3399
+ return Array.from(bytes, (b) => b.toString(HEX_RADIX).padStart(2, "0")).join("");
3400
+ }
3401
+
3402
+ // src/server/auth/server-oauth-token.ts
3403
+ var OAUTH_TOKEN_ENDPOINT2 = "/api/v1/oauth/token";
3404
+ var MS_PER_SECOND3 = 1e3;
3405
+ function withTimeout(init, timeout) {
3406
+ if (timeout !== void 0) {
3407
+ return { ...init, signal: AbortSignal.timeout(timeout) };
3408
+ }
3409
+ return init;
3410
+ }
3411
+ function validateTokenResponse2(r) {
3412
+ const invalid = [];
3413
+ if (!r.access_token) invalid.push("access_token");
3414
+ if (!r.refresh_token) invalid.push("refresh_token");
3415
+ if (typeof r.expires_in !== "number" || !Number.isFinite(r.expires_in) || r.expires_in <= 0) {
3416
+ invalid.push("expires_in");
3417
+ }
3418
+ 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;
3419
+ }
3420
+ function toTokens(r) {
3421
+ return {
3422
+ accessToken: r.access_token,
3423
+ refreshToken: r.refresh_token,
3424
+ expiresAt: Date.now() + r.expires_in * MS_PER_SECOND3
3425
+ };
3426
+ }
3427
+ function fail(code, message) {
3428
+ return { error: { code, message } };
3429
+ }
3430
+ async function postToken(deps, body, fallbackErrorCode) {
3431
+ const url = `${deps.apiBaseUrl}${OAUTH_TOKEN_ENDPOINT2}`;
3432
+ let response;
3433
+ try {
3434
+ response = await fetch(
3435
+ url,
3436
+ withTimeout(
3437
+ {
3438
+ method: "POST",
3439
+ credentials: "omit",
3440
+ headers: { "Content-Type": "application/x-www-form-urlencoded", ...sdkHeaders() },
3441
+ body: new URLSearchParams(body).toString()
3442
+ },
3443
+ deps.timeout
3444
+ )
3445
+ );
3446
+ } catch (error) {
3447
+ return fail(
3448
+ FFID_ERROR_CODES.NETWORK_ERROR,
3449
+ error instanceof Error ? error.message : "\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\u30A8\u30E9\u30FC\u304C\u767A\u751F\u3057\u307E\u3057\u305F"
3450
+ );
3451
+ }
3452
+ let json;
3453
+ try {
3454
+ json = await response.json();
3455
+ } catch {
3456
+ return fail(
3457
+ FFID_ERROR_CODES.PARSE_ERROR,
3458
+ `\u30C8\u30FC\u30AF\u30F3\u30EC\u30B9\u30DD\u30F3\u30B9\u306E\u89E3\u6790\u306B\u5931\u6557\u3057\u307E\u3057\u305F (status: ${response.status})`
3459
+ );
3460
+ }
3461
+ if (!response.ok) {
3462
+ const errorBody = json;
3463
+ return fail(errorBody.error ?? fallbackErrorCode, errorBody.error_description ?? "\u30C8\u30FC\u30AF\u30F3\u51E6\u7406\u306B\u5931\u6557\u3057\u307E\u3057\u305F");
3464
+ }
3465
+ const validationError = validateTokenResponse2(json);
3466
+ if (validationError) {
3467
+ return fail(fallbackErrorCode, validationError);
3468
+ }
3469
+ return { tokens: toTokens(json) };
3470
+ }
3471
+ function exchangeAuthorizationCodeServer(deps, code) {
3472
+ return postToken(
3473
+ deps,
3474
+ {
3475
+ grant_type: "authorization_code",
3476
+ code,
3477
+ client_id: deps.clientId,
3478
+ client_secret: deps.clientSecret,
3479
+ redirect_uri: deps.redirectUri
3480
+ },
3481
+ FFID_ERROR_CODES.TOKEN_EXCHANGE_ERROR
3482
+ );
3483
+ }
3484
+ function refreshTokensServer(deps, refreshToken) {
3485
+ return postToken(
3486
+ deps,
3487
+ {
3488
+ grant_type: "refresh_token",
3489
+ refresh_token: refreshToken,
3490
+ client_id: deps.clientId,
3491
+ client_secret: deps.clientSecret
3492
+ },
3493
+ FFID_ERROR_CODES.TOKEN_REFRESH_ERROR
3494
+ );
3495
+ }
3496
+
3497
+ // src/server/auth/server-auth-client.ts
3498
+ var OAUTH_AUTHORIZE_ENDPOINT2 = "/api/v1/oauth/authorize";
3499
+ var SCREEN_HINT_SIGNUP2 = "signup";
3500
+ function createServerAuthClient(config) {
3501
+ if (!config.serviceCode?.trim()) {
3502
+ throw new Error("FFID Server Auth: serviceCode \u304C\u672A\u8A2D\u5B9A\u3067\u3059");
3503
+ }
3504
+ if (!config.clientSecret?.trim()) {
3505
+ throw new Error("FFID Server Auth: clientSecret \u304C\u672A\u8A2D\u5B9A\u3067\u3059");
3506
+ }
3507
+ if (!config.redirectUri?.trim()) {
3508
+ throw new Error("FFID Server Auth: redirectUri \u304C\u672A\u8A2D\u5B9A\u3067\u3059");
3509
+ }
3510
+ if (!config.scope?.trim()) {
3511
+ throw new Error(
3512
+ "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"
3513
+ );
3514
+ }
3515
+ const apiBaseUrl = config.apiBaseUrl ?? DEFAULT_API_BASE_URL;
3516
+ const clientId = config.clientId ?? config.serviceCode;
3517
+ const deps = {
3518
+ apiBaseUrl,
3519
+ clientId,
3520
+ clientSecret: config.clientSecret,
3521
+ redirectUri: config.redirectUri,
3522
+ timeout: config.timeout
3523
+ };
3524
+ function buildAuthorizeUrl(opts) {
3525
+ const state = generateServerState();
3526
+ const params = new URLSearchParams({
3527
+ response_type: "code",
3528
+ client_id: clientId,
3529
+ scope: config.scope,
3530
+ redirect_uri: config.redirectUri,
3531
+ state
3532
+ });
3533
+ const organizationId = opts?.organizationId?.trim();
3534
+ if (organizationId) params.set("organization_id", organizationId);
3535
+ if (opts?.screenHint === SCREEN_HINT_SIGNUP2) params.set("screen_hint", SCREEN_HINT_SIGNUP2);
3536
+ if (opts?.prompt) params.set("prompt", opts.prompt);
3537
+ return { url: `${apiBaseUrl}${OAUTH_AUTHORIZE_ENDPOINT2}?${params.toString()}`, state };
3538
+ }
3539
+ async function handleCallback(input) {
3540
+ let url;
3541
+ try {
3542
+ url = typeof input.url === "string" ? new URL(input.url) : input.url;
3543
+ } catch {
3544
+ return {
3545
+ error: {
3546
+ code: FFID_ERROR_CODES.TOKEN_EXCHANGE_ERROR,
3547
+ message: "\u30B3\u30FC\u30EB\u30D0\u30C3\u30AF URL \u306E\u89E3\u6790\u306B\u5931\u6557\u3057\u307E\u3057\u305F"
3548
+ }
3549
+ };
3550
+ }
3551
+ const returnedState = url.searchParams.get("state") ?? void 0;
3552
+ if (!input.storedState || !returnedState || input.storedState !== returnedState) {
3553
+ return {
3554
+ error: {
3555
+ code: FFID_ERROR_CODES.STATE_MISMATCH_ERROR,
3556
+ 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"
3557
+ }
3558
+ };
3559
+ }
3560
+ const errorParam = url.searchParams.get("error");
3561
+ if (errorParam) {
3562
+ return {
3563
+ error: {
3564
+ code: errorParam,
3565
+ message: url.searchParams.get("error_description") ?? "\u8A8D\u53EF\u30B5\u30FC\u30D0\u30FC\u304C\u30A8\u30E9\u30FC\u3092\u8FD4\u3057\u307E\u3057\u305F"
3566
+ }
3567
+ };
3568
+ }
3569
+ const code = url.searchParams.get("code");
3570
+ if (!code) {
3571
+ return {
3572
+ error: {
3573
+ code: FFID_ERROR_CODES.TOKEN_EXCHANGE_ERROR,
3574
+ message: "authorization code \u304C\u30B3\u30FC\u30EB\u30D0\u30C3\u30AF\u306B\u542B\u307E\u308C\u3066\u3044\u307E\u305B\u3093"
3575
+ }
3576
+ };
3577
+ }
3578
+ return exchangeAuthorizationCodeServer(deps, code);
3579
+ }
3580
+ function refresh(refreshToken) {
3581
+ return refreshTokensServer(deps, refreshToken);
3582
+ }
3583
+ return { buildAuthorizeUrl, handleCallback, refresh };
3584
+ }
3585
+
3586
+ // src/server/auth/session-cookies.ts
3587
+ var FFID_SESSION_COOKIE_NAME = "ffid_session";
3588
+ var DEFAULT_PATH = "/";
3589
+ var DEFAULT_SAME_SITE = "lax";
3590
+ var HOURS_PER_DAY2 = 24;
3591
+ var DEFAULT_MAX_AGE_DAYS = 30;
3592
+ var DEFAULT_MAX_AGE_SECONDS = 60 * 60 * HOURS_PER_DAY2 * DEFAULT_MAX_AGE_DAYS;
3593
+ var BASE64_GROUP = 4;
3594
+ function base64UrlEncode2(input) {
3595
+ const bytes = new TextEncoder().encode(input);
3596
+ const binary = Array.from(bytes, (byte) => String.fromCharCode(byte)).join("");
3597
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
3598
+ }
3599
+ function base64UrlDecode(input) {
3600
+ const b64 = input.replace(/-/g, "+").replace(/_/g, "/");
3601
+ const remainder = b64.length % BASE64_GROUP;
3602
+ const padded = remainder === 0 ? b64 : b64 + "=".repeat(BASE64_GROUP - remainder);
3603
+ const bytes = Uint8Array.from(atob(padded), (char) => char.charCodeAt(0));
3604
+ return new TextDecoder().decode(bytes);
3605
+ }
3606
+ function sameSiteLabel(value) {
3607
+ return value.charAt(0).toUpperCase() + value.slice(1);
3608
+ }
3609
+ function buildSetCookie(nameValue, opts, maxAge) {
3610
+ const path = opts.path ?? DEFAULT_PATH;
3611
+ const sameSite = opts.sameSite ?? DEFAULT_SAME_SITE;
3612
+ const secure = opts.secure ?? true;
3613
+ const httpOnly = opts.httpOnly ?? true;
3614
+ const attrs = [nameValue, `Path=${path}`, `Max-Age=${maxAge}`, `SameSite=${sameSiteLabel(sameSite)}`];
3615
+ if (httpOnly) attrs.push("HttpOnly");
3616
+ if (secure) attrs.push("Secure");
3617
+ if (opts.domain) attrs.push(`Domain=${opts.domain}`);
3618
+ return attrs.join("; ");
3619
+ }
3620
+ function parseCookieHeader(header) {
3621
+ const out = {};
3622
+ for (const part of header.split(";")) {
3623
+ const eq = part.indexOf("=");
3624
+ if (eq === -1) continue;
3625
+ const key = part.slice(0, eq).trim();
3626
+ if (key) out[key] = part.slice(eq + 1).trim();
3627
+ }
3628
+ return out;
3629
+ }
3630
+ function serialize(tokens, opts = {}) {
3631
+ const value = base64UrlEncode2(JSON.stringify(tokens));
3632
+ const maxAge = opts.maxAge ?? DEFAULT_MAX_AGE_SECONDS;
3633
+ return [buildSetCookie(`${FFID_SESSION_COOKIE_NAME}=${value}`, opts, maxAge)];
3634
+ }
3635
+ function read(cookieHeader) {
3636
+ if (!cookieHeader) return null;
3637
+ const raw = parseCookieHeader(cookieHeader)[FFID_SESSION_COOKIE_NAME];
3638
+ if (!raw) return null;
3639
+ try {
3640
+ const parsed = JSON.parse(base64UrlDecode(raw));
3641
+ if (typeof parsed.accessToken !== "string" || typeof parsed.refreshToken !== "string" || typeof parsed.expiresAt !== "number") {
3642
+ return null;
3643
+ }
3644
+ return {
3645
+ accessToken: parsed.accessToken,
3646
+ refreshToken: parsed.refreshToken,
3647
+ expiresAt: parsed.expiresAt
3648
+ };
3649
+ } catch {
3650
+ return null;
3651
+ }
3652
+ }
3653
+ function clear(opts = {}) {
3654
+ return [buildSetCookie(`${FFID_SESSION_COOKIE_NAME}=`, opts, 0)];
3655
+ }
3656
+ var sessionCookies = { serialize, read, clear };
3657
+
3658
+ 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.0",
3
+ "version": "5.24.0",
4
4
  "description": "FeelFlow ID Platform SDK for React/Next.js applications",
5
5
  "keywords": [
6
6
  "feelflow",