@feelflow/ffid-sdk 12.0.0 → 12.2.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 FFIDError, a as FFIDLogger, b as FFIDCacheAdapter, c as FFIDVerifyAccessTokenOptions, d as FFIDApiResponse, e as FFIDOAuthUserInfo, f as FFIDCatalogEnvironment, g as FFIDBillingInterval, h as FFIDTaxBehavior, i as FFIDPublishedCatalog } from '../ffid-client-ByfZA9sJ.js';
2
- export { j as FFIDAddMemberParams, k as FFIDAddMemberRequest, l as FFIDAddMemberResponse, m as FFIDAllowedLogoMimeType, n as FFIDAssignableMemberRole, o as FFIDCacheConfig, p as FFIDCatalogPublication, q as FFIDCatalogPublicationStatus, r as FFIDClient, s as FFIDCompanySizeCode, t as FFIDConfig, u as FFIDIndustryCode, v as FFIDListMembersResponse, w as FFIDListingConsentInput, x as FFIDLogoWallEntry, y as FFIDLogoWallResponse, z as FFIDMemberRole, A as FFIDMemberSeatAssignmentResult, B as FFIDOrganization, C as FFIDOrganizationLogoUploadResponse, D as FFIDOrganizationMember, E as FFIDOrganizationProfile, G as FFIDOrganizationProfileErrorCode, H as FFIDOrganizationProfileResponse, I as FFIDOtpSendResponse, J as FFIDOtpVerifyResponse, K as FFIDPasswordResetConfirmResponse, L as FFIDPasswordResetResponse, M as FFIDPasswordResetVerifyResponse, N as FFIDProfileCallOptions, O as FFIDProvisionMemberPlan, P as FFIDProvisionMemberPlanStatus, Q as FFIDProvisionMemberResult, R as FFIDProvisionMemberStatus, S as FFIDProvisionOrganizationDryRun, T as FFIDProvisionOrganizationMemberInput, U as FFIDProvisionOrganizationOutcome, V as FFIDProvisionOrganizationParams, W as FFIDProvisionOrganizationResponse, X as FFIDProvisionUserDryRun, Y as FFIDProvisionUserOutcome, Z as FFIDProvisionUserParams, _ as FFIDProvisionUserProfileInput, $ as FFIDProvisionUserResponse, a0 as FFIDProvisionedOrganization, a1 as FFIDProvisionedUser, a2 as FFIDPublishedPlan, a3 as FFIDRemoveMemberResponse, a4 as FFIDResetSessionResponse, a5 as FFIDSubscription, a6 as FFIDUpdateMemberRoleResponse, a7 as FFIDUpdateUserProfileRequest, a8 as FFIDUploadOrganizationLogoParams, a9 as FFIDUpsertOrganizationProfileParams, aa as FFIDUpsertOrganizationProfileRequest, ab as FFIDUser, ac as FFIDUserProfile, ad as FFID_ALLOWED_ORGANIZATION_LOGO_MIME_TYPES, ae as FFID_CATALOG_ENVIRONMENTS, af as FFID_CATALOG_PUBLICATION_STATUSES, ag as FFID_COMPANY_SIZE_CODES, ah as FFID_INDUSTRY_CODES, ai as FFID_MAX_ORGANIZATION_LOGO_FILE_SIZE_BYTES, aj as FFID_MAX_ORGANIZATION_LOGO_FILE_SIZE_MB, ak as FFID_ORGANIZATION_PROFILE_ERROR_CODES, al as TokenData, am as TokenStore, an as createFFIDClient, ao as createTokenStore } from '../ffid-client-ByfZA9sJ.js';
1
+ import { F as FFIDError, a as FFIDLogger, b as FFIDCacheAdapter, c as FFIDVerifyAccessTokenOptions, d as FFIDApiResponse, e as FFIDOAuthUserInfo, f as FFIDCatalogEnvironment, g as FFIDBillingInterval, h as FFIDTaxBehavior, i as FFIDPublishedCatalog } from '../ffid-client-Dr2KVlIZ.js';
2
+ export { j as FFIDAddMemberParams, k as FFIDAddMemberRequest, l as FFIDAddMemberResponse, m as FFIDAllowedLogoMimeType, n as FFIDAssignableMemberRole, o as FFIDCacheConfig, p as FFIDCatalogPublication, q as FFIDCatalogPublicationStatus, r as FFIDClient, s as FFIDCompanySizeCode, t as FFIDConfig, u as FFIDIndustryCode, v as FFIDListMembersResponse, w as FFIDListingConsentInput, x as FFIDLogoWallEntry, y as FFIDLogoWallResponse, z as FFIDMemberRole, A as FFIDMemberSeatAssignmentResult, B as FFIDOrganization, C as FFIDOrganizationLogoUploadResponse, D as FFIDOrganizationMember, E as FFIDOrganizationProfile, G as FFIDOrganizationProfileErrorCode, H as FFIDOrganizationProfileResponse, I as FFIDOtpSendResponse, J as FFIDOtpVerifyResponse, K as FFIDPasswordResetConfirmResponse, L as FFIDPasswordResetResponse, M as FFIDPasswordResetVerifyResponse, N as FFIDProfileCallOptions, O as FFIDProvisionMemberPlan, P as FFIDProvisionMemberPlanStatus, Q as FFIDProvisionMemberResult, R as FFIDProvisionMemberStatus, S as FFIDProvisionOrganizationDryRun, T as FFIDProvisionOrganizationMemberInput, U as FFIDProvisionOrganizationOutcome, V as FFIDProvisionOrganizationParams, W as FFIDProvisionOrganizationResponse, X as FFIDProvisionUserDryRun, Y as FFIDProvisionUserOutcome, Z as FFIDProvisionUserParams, _ as FFIDProvisionUserProfileInput, $ as FFIDProvisionUserResponse, a0 as FFIDProvisionedOrganization, a1 as FFIDProvisionedUser, a2 as FFIDPublishedPlan, a3 as FFIDRemoveMemberResponse, a4 as FFIDResetSessionResponse, a5 as FFIDSubscription, a6 as FFIDUpdateMemberRoleResponse, a7 as FFIDUpdateUserProfileRequest, a8 as FFIDUploadOrganizationLogoParams, a9 as FFIDUpsertOrganizationProfileParams, aa as FFIDUpsertOrganizationProfileRequest, ab as FFIDUser, ac as FFIDUserProfile, ad as FFID_ALLOWED_ORGANIZATION_LOGO_MIME_TYPES, ae as FFID_CATALOG_ENVIRONMENTS, af as FFID_CATALOG_PUBLICATION_STATUSES, ag as FFID_COMPANY_SIZE_CODES, ah as FFID_INDUSTRY_CODES, ai as FFID_MAX_ORGANIZATION_LOGO_FILE_SIZE_BYTES, aj as FFID_MAX_ORGANIZATION_LOGO_FILE_SIZE_MB, ak as FFID_ORGANIZATION_PROFILE_ERROR_CODES, al as TokenData, am as TokenStore, an as createFFIDClient, ao as createTokenStore } from '../ffid-client-Dr2KVlIZ.js';
3
3
  export { D as DEFAULT_API_BASE_URL, a as DEFAULT_OAUTH_SCOPES } from '../constants-Ce2eXQtB.js';
4
4
  import { z } from 'zod';
5
5
  import '../types-Cjb9J0rL.js';
@@ -649,4 +649,147 @@ declare function computeScopeHash(input: FFIDScopeHashInput): Promise<string>;
649
649
  */
650
650
  declare function validatePublishedCatalog(catalog: unknown): asserts catalog is FFIDPublishedCatalog;
651
651
 
652
- export { ALL_DENIED_EXCEPT_NECESSARY, type BuildAuthorizeUrlOptions, type BuildAuthorizeUrlResult, CATALOG_HASH_PATTERN, CONSENT_COOKIE_NAME, COOKIE_VERSION, type CookieOptions, type FFIDAuthorizationError, type FFIDAuthorizationErrorDetails, FFIDCacheAdapter, type FFIDCanonicalJsonValue, FFIDCatalogEnvironment, FFIDCatalogHashError, type FFIDConsentCategories, type FFIDConsentCategoryCode, type FFIDCookieStoreLike, type FFIDErrorCode, type FFIDOAuthDenialReason, FFIDOAuthUserInfo, type FFIDPaymentConfiguration, FFIDPublishedCatalog, type FFIDScopeHashInput, type FFIDScopeHashPlan, FFIDTaxBehavior, type FFIDTaxConfiguration, FFIDVerifyAccessTokenOptions, FFID_ERROR_CODES, FFID_OAUTH_DENIAL_REASONS, FFID_SESSION_COOKIE_NAME, type HandleCallbackInput, type KVNamespaceLike, type ServerAuthClient, type ServerAuthConfig, type ServerSessionTokens, type ServerTokenResult, canonicalizeCatalogValue, computeFFIDCheckoutCopyHash, computeLegalDisclosureHash, computePaymentConfigurationHash, computePraxisCopyHash, computeScopeHash, computeTaxConfigurationHash, createKVCacheAdapter, createMemoryCacheAdapter, createServerAuthClient, createVerifyAccessToken, decodeConsentCookie, encodeConsentCookie, generateServerState, getFFIDAuthorizationError, getFFIDConsentFromCookieHeader, getFFIDConsentFromCookies, hashCanonicalJson, isFFIDOAuthDenialReason, sessionCookies, sha256Hex, validatePublishedCatalog };
652
+ /**
653
+ * Constants for the product-side DB token minter (#6318).
654
+ *
655
+ * A product that reaches its own Supabase through supabase-js (PostgREST)
656
+ * mints a short-lived token for the FFID user on its server and sends it as
657
+ * the `Authorization: Bearer` header. Supabase validates it against the
658
+ * product's JWT Signing Keys and RLS reads the user from `auth.jwt()`.
659
+ */
660
+ /** Only asymmetric signing is allowed; a shared secret (HS256) is rejected by policy. */
661
+ declare const FFID_DB_TOKEN_ALGORITHM: "ES256";
662
+ /** Supabase maps this claim to the Postgres role the request runs as. */
663
+ declare const FFID_DB_TOKEN_ROLE: "authenticated";
664
+ /** Same shape as the user tokens Supabase Auth issues (`aud` = `authenticated`). */
665
+ declare const FFID_DB_TOKEN_AUDIENCE: "authenticated";
666
+ /** Default lifetime: 5 minutes. The token is minted per request and never sent to the browser. */
667
+ declare const DEFAULT_DB_TOKEN_TTL_SECONDS = 300;
668
+ /** Hard ceiling: 15 minutes. Longer tokens defeat the "mint per request" model. */
669
+ declare const MAX_DB_TOKEN_TTL_SECONDS = 900;
670
+ /** Claim that carries the FFID organization id when the product scopes rows by organization. */
671
+ declare const FFID_DB_TOKEN_ORGANIZATION_CLAIM: "organization_id";
672
+ /**
673
+ * Claims the minter owns. Product-specific `claims` must not use these names,
674
+ * so a caller cannot forge a different user, role, or lifetime.
675
+ */
676
+ declare const FFID_DB_TOKEN_RESERVED_CLAIMS: readonly ["sub", "role", "aud", "iss", "iat", "exp", "nbf", "jti", "organization_id"];
677
+
678
+ /**
679
+ * Types for the product-side DB token minter (#6318).
680
+ */
681
+
682
+ /**
683
+ * Private P-256 JWK used to sign DB tokens. Generate it with
684
+ * `supabase gen signing-key --algorithm ES256`, import that private JWK into the
685
+ * product's Supabase JWT Signing Keys (Supabase keeps it non-extractable and
686
+ * publishes only the public half via JWKS), and keep the same JWK in a server
687
+ * environment variable. Nothing else may hold it.
688
+ *
689
+ * The CLI output also carries `use`, `key_ops` and `ext`; the minter strips
690
+ * those before import (WebCrypto rejects an ECDSA private key whose `key_ops`
691
+ * includes `verify`).
692
+ */
693
+ interface FFIDDbTokenSigningJwk {
694
+ kty: 'EC';
695
+ crv: 'P-256';
696
+ /** Private scalar. Its presence is what makes this a signing key. */
697
+ d: string;
698
+ x: string;
699
+ y: string;
700
+ /** Key id. Supabase matches the token header `kid` against the imported key. */
701
+ kid?: string;
702
+ alg?: string;
703
+ use?: string;
704
+ [parameter: string]: unknown;
705
+ }
706
+ interface FFIDDbTokenMinterConfig {
707
+ /**
708
+ * The private JWK, either as an object or as the JSON string stored in an
709
+ * environment variable (for example `SUPABASE_JWT_SIGNING_KEY`).
710
+ */
711
+ signingKey: string | FFIDDbTokenSigningJwk;
712
+ /** Overrides the JWK's `kid`. Required when the JWK has none. */
713
+ kid?: string;
714
+ /** Token lifetime. Default `DEFAULT_DB_TOKEN_TTL_SECONDS`, max `MAX_DB_TOKEN_TTL_SECONDS`. */
715
+ ttlSeconds?: number;
716
+ /** Optional `iss` claim. Supabase does not require it; set it when the product's policies read it. */
717
+ issuer?: string;
718
+ }
719
+ interface FFIDMintDbTokenInput {
720
+ /** FFID user id (UUID). Becomes `sub`, the value `private.current_ffid_user_id()` returns. */
721
+ userId: string;
722
+ /** FFID organization id (UUID). Becomes the `organization_id` claim. `null` means "none", like `FFIDUser.organizationId`. */
723
+ organizationId?: string | null;
724
+ /** Product-specific claims. Reserved names (`FFID_DB_TOKEN_RESERVED_CLAIMS`) are rejected. */
725
+ claims?: Record<string, unknown>;
726
+ /** Clock override for tests. Defaults to `new Date()`. An Invalid Date is rejected (`INVALID_CLOCK`). */
727
+ now?: Date;
728
+ }
729
+ interface FFIDDbTokenClaims {
730
+ sub: string;
731
+ role: typeof FFID_DB_TOKEN_ROLE;
732
+ aud: typeof FFID_DB_TOKEN_AUDIENCE;
733
+ iat: number;
734
+ exp: number;
735
+ iss?: string;
736
+ organization_id?: string;
737
+ [claim: string]: unknown;
738
+ }
739
+ interface FFIDDbToken {
740
+ /** Compact JWS to send as `Authorization: Bearer <token>` to the product's Supabase. */
741
+ token: string;
742
+ /** `exp` as a `Date`. For logging / diagnostics; the client is still created per request. */
743
+ expiresAt: Date;
744
+ /** The signed payload, for logging claim names (never log the token itself). */
745
+ claims: FFIDDbTokenClaims;
746
+ }
747
+ interface FFIDDbTokenMinter {
748
+ /** Key id written to every token header. */
749
+ readonly kid: string;
750
+ /** Effective lifetime in seconds. */
751
+ readonly ttlSeconds: number;
752
+ mint(input: FFIDMintDbTokenInput): Promise<FFIDDbToken>;
753
+ }
754
+
755
+ /**
756
+ * Creates a minter bound to one signing key. Create it once per process and
757
+ * call `mint()` per request.
758
+ *
759
+ * The key shape is checked synchronously here. The key material is imported on
760
+ * the first `mint()`; a successful import is kept for the minter's lifetime,
761
+ * a failed one is retried on the next `mint()`.
762
+ *
763
+ * @throws FFIDDbTokenError when the key shape or TTL is invalid.
764
+ */
765
+ declare function createDbTokenMinter(config: FFIDDbTokenMinterConfig): FFIDDbTokenMinter;
766
+
767
+ /**
768
+ * Errors thrown by the product-side DB token minter (#6318).
769
+ *
770
+ * These are programming / configuration errors on the product's server, never
771
+ * end-user input errors. Messages never include key material.
772
+ */
773
+ declare const FFID_DB_TOKEN_ERROR_CODES: {
774
+ /** Signing key is not a private P-256 JWK with a `kid`, or cannot be imported. */
775
+ readonly INVALID_SIGNING_KEY: "INVALID_SIGNING_KEY";
776
+ /** `ttlSeconds` is not a positive integer within `MAX_DB_TOKEN_TTL_SECONDS`. */
777
+ readonly INVALID_TTL: "INVALID_TTL";
778
+ /** `userId` is not a UUID. */
779
+ readonly INVALID_USER_ID: "INVALID_USER_ID";
780
+ /** `organizationId` is not a UUID. */
781
+ readonly INVALID_ORGANIZATION_ID: "INVALID_ORGANIZATION_ID";
782
+ /** A product claim uses a name the minter reserves (`sub`, `role`, `exp`, ...). */
783
+ readonly RESERVED_CLAIM: "RESERVED_CLAIM";
784
+ /** `now` is not a valid `Date` (an Invalid Date would sign `iat` / `exp` as null). */
785
+ readonly INVALID_CLOCK: "INVALID_CLOCK";
786
+ };
787
+ type FFIDDbTokenErrorCode = (typeof FFID_DB_TOKEN_ERROR_CODES)[keyof typeof FFID_DB_TOKEN_ERROR_CODES];
788
+ declare class FFIDDbTokenError extends Error {
789
+ readonly code: FFIDDbTokenErrorCode;
790
+ constructor(code: FFIDDbTokenErrorCode, message: string, options?: {
791
+ cause?: unknown;
792
+ });
793
+ }
794
+
795
+ export { ALL_DENIED_EXCEPT_NECESSARY, type BuildAuthorizeUrlOptions, type BuildAuthorizeUrlResult, CATALOG_HASH_PATTERN, CONSENT_COOKIE_NAME, COOKIE_VERSION, type CookieOptions, DEFAULT_DB_TOKEN_TTL_SECONDS, type FFIDAuthorizationError, type FFIDAuthorizationErrorDetails, FFIDCacheAdapter, type FFIDCanonicalJsonValue, FFIDCatalogEnvironment, FFIDCatalogHashError, type FFIDConsentCategories, type FFIDConsentCategoryCode, type FFIDCookieStoreLike, type FFIDDbToken, type FFIDDbTokenClaims, FFIDDbTokenError, type FFIDDbTokenErrorCode, type FFIDDbTokenMinter, type FFIDDbTokenMinterConfig, type FFIDDbTokenSigningJwk, type FFIDErrorCode, type FFIDMintDbTokenInput, type FFIDOAuthDenialReason, FFIDOAuthUserInfo, type FFIDPaymentConfiguration, FFIDPublishedCatalog, type FFIDScopeHashInput, type FFIDScopeHashPlan, FFIDTaxBehavior, type FFIDTaxConfiguration, FFIDVerifyAccessTokenOptions, FFID_DB_TOKEN_ALGORITHM, FFID_DB_TOKEN_AUDIENCE, FFID_DB_TOKEN_ERROR_CODES, FFID_DB_TOKEN_ORGANIZATION_CLAIM, FFID_DB_TOKEN_RESERVED_CLAIMS, FFID_DB_TOKEN_ROLE, FFID_ERROR_CODES, FFID_OAUTH_DENIAL_REASONS, FFID_SESSION_COOKIE_NAME, type HandleCallbackInput, type KVNamespaceLike, MAX_DB_TOKEN_TTL_SECONDS, type ServerAuthClient, type ServerAuthConfig, type ServerSessionTokens, type ServerTokenResult, canonicalizeCatalogValue, computeFFIDCheckoutCopyHash, computeLegalDisclosureHash, computePaymentConfigurationHash, computePraxisCopyHash, computeScopeHash, computeTaxConfigurationHash, createDbTokenMinter, createKVCacheAdapter, createMemoryCacheAdapter, createServerAuthClient, createVerifyAccessToken, decodeConsentCookie, encodeConsentCookie, generateServerState, getFFIDAuthorizationError, getFFIDConsentFromCookieHeader, getFFIDConsentFromCookies, hashCanonicalJson, isFFIDOAuthDenialReason, sessionCookies, sha256Hex, validatePublishedCatalog };
@@ -1,6 +1,7 @@
1
1
  import { DEFAULT_API_BASE_URL } from '../chunk-JEVK2XUM.js';
2
2
  export { DEFAULT_API_BASE_URL, DEFAULT_OAUTH_SCOPES } from '../chunk-JEVK2XUM.js';
3
- import { createRemoteJWKSet, jwtVerify, errors } from 'jose';
3
+ import { SignJWT, importJWK, jwtVerify, createRemoteJWKSet, errors } from 'jose';
4
+ import { z } from 'zod';
4
5
 
5
6
  // src/auth/token-store.ts
6
7
  var STORAGE_KEY = "ffid_tokens";
@@ -309,13 +310,13 @@ var HTTP_SERVER_ERROR_MIN = 500;
309
310
  var HTTP_SERVER_ERROR_LIMIT = 600;
310
311
  function createVerifyAccessToken(deps) {
311
312
  const { authMode, baseUrl, serviceCode, serviceApiKey, verifyStrategy, logger, createError, errorCodes, cache, timeout } = deps;
312
- let jwtVerify2 = null;
313
+ let jwtVerify3 = null;
313
314
  let cacheReadFailureEscalated = false;
314
315
  let cacheWriteFailureEscalated = false;
315
316
  let missingSubtleCryptoLogged = false;
316
317
  function getJwtVerifier() {
317
- if (!jwtVerify2) {
318
- jwtVerify2 = createJwtVerifier({
318
+ if (!jwtVerify3) {
319
+ jwtVerify3 = createJwtVerifier({
319
320
  baseUrl,
320
321
  serviceCode,
321
322
  logger,
@@ -325,7 +326,7 @@ function createVerifyAccessToken(deps) {
325
326
  errorCodes
326
327
  });
327
328
  }
328
- return jwtVerify2;
329
+ return jwtVerify3;
329
330
  }
330
331
  async function verifyAccessToken(accessToken, options) {
331
332
  if (authMode !== "service-key") {
@@ -573,7 +574,8 @@ function createBillingMethods(deps) {
573
574
  subscriptionId: params.subscriptionId,
574
575
  successUrl: params.successUrl,
575
576
  cancelUrl: params.cancelUrl,
576
- ...params.planId ? { planId: params.planId } : {}
577
+ ...params.planId ? { planId: params.planId } : {},
578
+ ...params.quantity !== void 0 ? { quantity: params.quantity } : {}
577
579
  })
578
580
  }
579
581
  );
@@ -1386,7 +1388,7 @@ var FFID_ORGANIZATION_PROFILE_ERROR_CODES = {
1386
1388
  };
1387
1389
 
1388
1390
  // src/client/version-check.ts
1389
- var SDK_VERSION = "12.0.0";
1391
+ var SDK_VERSION = "12.2.0";
1390
1392
  var SDK_USER_AGENT = `FFID-SDK/${SDK_VERSION} (TypeScript)`;
1391
1393
  var SDK_VERSION_HEADER = "X-FFID-SDK-Version";
1392
1394
  function sdkHeaders() {
@@ -3335,24 +3337,44 @@ function createContractWizardMethods(deps) {
3335
3337
  };
3336
3338
  }
3337
3339
 
3340
+ // src/newsletter/types.ts
3341
+ var FFID_NEWSLETTER_TYPES = ["inquiry_followup", "general"];
3342
+
3338
3343
  // src/newsletter/ffid-newsletter-client.ts
3339
3344
  var EXT_SUBSCRIBE_ENDPOINT2 = "/api/v1/ext/newsletter/subscribe";
3340
3345
  var CONFIRM_ENDPOINT = "/api/newsletter/confirm";
3341
3346
  var UNSUBSCRIBE_ENDPOINT = "/api/newsletter/unsubscribe";
3342
3347
  var DISPATCH_ENDPOINT = "/api/v1/newsletter/dispatch";
3348
+ var PUBLIC_TOKEN_TIMEOUT_MS = 3e4;
3349
+ var subscribeResponseSchema = z.object({
3350
+ ok: z.literal(true),
3351
+ requiresConfirmation: z.boolean(),
3352
+ requiresSignIn: z.boolean(),
3353
+ confirmationEmailPending: z.boolean(),
3354
+ requestId: z.uuid().optional()
3355
+ }).refine(
3356
+ (value) => [
3357
+ value.requiresConfirmation,
3358
+ value.requiresSignIn,
3359
+ value.confirmationEmailPending
3360
+ ].filter(Boolean).length <= 1
3361
+ );
3343
3362
  function trimOrEmpty(s) {
3344
3363
  return typeof s === "string" ? s.trim() : "";
3345
3364
  }
3346
3365
  async function postPublic(url, init, opts) {
3347
3366
  let response;
3348
3367
  try {
3349
- response = await fetch(url, init);
3350
- } catch (err) {
3368
+ response = await fetch(url, {
3369
+ ...init,
3370
+ credentials: "omit",
3371
+ redirect: "error",
3372
+ cache: "no-store",
3373
+ signal: AbortSignal.timeout(PUBLIC_TOKEN_TIMEOUT_MS)
3374
+ });
3375
+ } catch {
3351
3376
  return {
3352
- error: opts.createError(
3353
- "NETWORK_ERROR",
3354
- err instanceof Error ? err.message : "\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\u30A8\u30E9\u30FC\u304C\u767A\u751F\u3057\u307E\u3057\u305F"
3355
- )
3377
+ error: opts.createError("NETWORK_ERROR", opts.fallbackMessage)
3356
3378
  };
3357
3379
  }
3358
3380
  if (!response.ok) {
@@ -3379,7 +3401,7 @@ async function postPublic(url, init, opts) {
3379
3401
  }
3380
3402
  function createNewsletterMethods(deps) {
3381
3403
  const { fetchWithAuth, baseUrl, createError } = deps;
3382
- async function subscribe(params) {
3404
+ async function subscribe(params, options = {}) {
3383
3405
  const email = trimOrEmpty(params.email);
3384
3406
  const source = trimOrEmpty(params.source);
3385
3407
  if (!email) {
@@ -3396,10 +3418,19 @@ function createNewsletterMethods(deps) {
3396
3418
  )
3397
3419
  };
3398
3420
  }
3399
- return fetchWithAuth(
3421
+ if (options.idempotencyKey !== void 0 && !z.uuid().safeParse(options.idempotencyKey).success) {
3422
+ return {
3423
+ error: createError(
3424
+ "INVALID_IDEMPOTENCY_KEY",
3425
+ "idempotencyKey \u306B\u306F UUID \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044"
3426
+ )
3427
+ };
3428
+ }
3429
+ const response = await fetchWithAuth(
3400
3430
  EXT_SUBSCRIBE_ENDPOINT2,
3401
3431
  {
3402
3432
  method: "POST",
3433
+ ...options.idempotencyKey ? { headers: { "Idempotency-Key": options.idempotencyKey } } : {},
3403
3434
  body: JSON.stringify({
3404
3435
  email,
3405
3436
  types: params.types,
@@ -3408,6 +3439,23 @@ function createNewsletterMethods(deps) {
3408
3439
  })
3409
3440
  }
3410
3441
  );
3442
+ if (response.error) return response;
3443
+ const parsed = subscribeResponseSchema.safeParse(response.data);
3444
+ if (!parsed.success)
3445
+ return {
3446
+ error: createError(
3447
+ "PARSE_ERROR",
3448
+ "\u30CB\u30E5\u30FC\u30B9\u30EC\u30BF\u30FC\u767B\u9332\u306E\u5FDC\u7B54\u3092\u78BA\u8A8D\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F"
3449
+ )
3450
+ };
3451
+ if (options.idempotencyKey && parsed.data.requestId !== options.idempotencyKey)
3452
+ return {
3453
+ error: createError(
3454
+ "PARSE_ERROR",
3455
+ "\u30CB\u30E5\u30FC\u30B9\u30EC\u30BF\u30FC\u767B\u9332\u306E\u30EA\u30AF\u30A8\u30B9\u30C8\u8B58\u5225\u5B50\u3092\u78BA\u8A8D\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F"
3456
+ )
3457
+ };
3458
+ return { data: parsed.data };
3411
3459
  }
3412
3460
  async function confirm(params) {
3413
3461
  const token = trimOrEmpty(params.token);
@@ -3435,6 +3483,16 @@ function createNewsletterMethods(deps) {
3435
3483
  }
3436
3484
  const url = new URL(`${baseUrl}${UNSUBSCRIBE_ENDPOINT}`);
3437
3485
  url.searchParams.set("token", token);
3486
+ if (params.type !== void 0) {
3487
+ if (!FFID_NEWSLETTER_TYPES.includes(params.type))
3488
+ return {
3489
+ error: createError(
3490
+ "VALIDATION_ERROR",
3491
+ "\u30CB\u30E5\u30FC\u30B9\u30EC\u30BF\u30FC\u306E\u914D\u4FE1\u7A2E\u5225\u304C\u4E0D\u6B63\u3067\u3059"
3492
+ )
3493
+ };
3494
+ url.searchParams.set("type", params.type);
3495
+ }
3438
3496
  return postPublic(
3439
3497
  url.toString(),
3440
3498
  { method: "POST" },
@@ -4864,4 +4922,184 @@ function clear(opts = {}) {
4864
4922
  }
4865
4923
  var sessionCookies = { serialize, read, clear };
4866
4924
 
4867
- export { ALL_DENIED_EXCEPT_NECESSARY, CATALOG_HASH_PATTERN, CONSENT_COOKIE_NAME, COOKIE_VERSION, FFIDCatalogHashError, FFID_ALLOWED_ORGANIZATION_LOGO_MIME_TYPES, FFID_CATALOG_ENVIRONMENTS, FFID_CATALOG_PUBLICATION_STATUSES, FFID_COMPANY_SIZE_CODES, FFID_ERROR_CODES, FFID_INDUSTRY_CODES, FFID_MAX_ORGANIZATION_LOGO_FILE_SIZE_BYTES, FFID_MAX_ORGANIZATION_LOGO_FILE_SIZE_MB, FFID_OAUTH_DENIAL_REASONS, FFID_ORGANIZATION_PROFILE_ERROR_CODES, FFID_SESSION_COOKIE_NAME, canonicalizeCatalogValue, computeFFIDCheckoutCopyHash, computeLegalDisclosureHash, computePaymentConfigurationHash, computePraxisCopyHash, computeScopeHash, computeTaxConfigurationHash, createFFIDClient, createKVCacheAdapter, createMemoryCacheAdapter, createServerAuthClient, createTokenStore, createVerifyAccessToken, decodeConsentCookie, encodeConsentCookie, generateServerState, getFFIDAuthorizationError, getFFIDConsentFromCookieHeader, getFFIDConsentFromCookies, hashCanonicalJson, isFFIDOAuthDenialReason, sessionCookies, sha256Hex, validatePublishedCatalog };
4925
+ // src/server/db-token/constants.ts
4926
+ var FFID_DB_TOKEN_ALGORITHM = "ES256";
4927
+ var FFID_DB_TOKEN_ROLE = "authenticated";
4928
+ var FFID_DB_TOKEN_AUDIENCE = "authenticated";
4929
+ var DEFAULT_DB_TOKEN_TTL_SECONDS = 300;
4930
+ var MAX_DB_TOKEN_TTL_SECONDS = 900;
4931
+ var FFID_DB_TOKEN_ORGANIZATION_CLAIM = "organization_id";
4932
+ var FFID_DB_TOKEN_RESERVED_CLAIMS = [
4933
+ "sub",
4934
+ "role",
4935
+ "aud",
4936
+ "iss",
4937
+ "iat",
4938
+ "exp",
4939
+ "nbf",
4940
+ "jti",
4941
+ FFID_DB_TOKEN_ORGANIZATION_CLAIM
4942
+ ];
4943
+ var MILLISECONDS_PER_SECOND = 1e3;
4944
+
4945
+ // src/server/db-token/errors.ts
4946
+ var FFID_DB_TOKEN_ERROR_CODES = {
4947
+ /** Signing key is not a private P-256 JWK with a `kid`, or cannot be imported. */
4948
+ INVALID_SIGNING_KEY: "INVALID_SIGNING_KEY",
4949
+ /** `ttlSeconds` is not a positive integer within `MAX_DB_TOKEN_TTL_SECONDS`. */
4950
+ INVALID_TTL: "INVALID_TTL",
4951
+ /** `userId` is not a UUID. */
4952
+ INVALID_USER_ID: "INVALID_USER_ID",
4953
+ /** `organizationId` is not a UUID. */
4954
+ INVALID_ORGANIZATION_ID: "INVALID_ORGANIZATION_ID",
4955
+ /** A product claim uses a name the minter reserves (`sub`, `role`, `exp`, ...). */
4956
+ RESERVED_CLAIM: "RESERVED_CLAIM",
4957
+ /** `now` is not a valid `Date` (an Invalid Date would sign `iat` / `exp` as null). */
4958
+ INVALID_CLOCK: "INVALID_CLOCK"
4959
+ };
4960
+ var FFIDDbTokenError = class extends Error {
4961
+ code;
4962
+ constructor(code, message, options) {
4963
+ super(message, options);
4964
+ this.name = "FFIDDbTokenError";
4965
+ this.code = code;
4966
+ }
4967
+ };
4968
+
4969
+ // src/server/db-token/mint.ts
4970
+ var UUID_PATTERN2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
4971
+ var RESERVED_CLAIM_SET = new Set(FFID_DB_TOKEN_RESERVED_CLAIMS);
4972
+ var isNonEmptyString = (value) => typeof value === "string" && value.length > 0;
4973
+ var invalidKey = (reason, cause) => new FFIDDbTokenError(
4974
+ FFID_DB_TOKEN_ERROR_CODES.INVALID_SIGNING_KEY,
4975
+ `Invalid DB token signing key: ${reason}`,
4976
+ cause === void 0 ? void 0 : { cause }
4977
+ );
4978
+ var describeCause = (cause) => cause instanceof Error ? `${cause.name}: ${cause.message}` : String(cause);
4979
+ function parseSigningKey(signingKey, kidOverride) {
4980
+ let candidate = signingKey;
4981
+ if (typeof signingKey === "string") {
4982
+ if (signingKey.trim().length === 0) {
4983
+ throw invalidKey("signingKey is empty (is the environment variable set?)");
4984
+ }
4985
+ try {
4986
+ candidate = JSON.parse(signingKey);
4987
+ } catch {
4988
+ throw invalidKey("not valid JSON");
4989
+ }
4990
+ }
4991
+ if (typeof candidate !== "object" || candidate === null || Array.isArray(candidate)) {
4992
+ throw invalidKey("expected a JWK object");
4993
+ }
4994
+ const jwk = candidate;
4995
+ if (jwk.kty !== "EC" || jwk.crv !== "P-256") {
4996
+ throw invalidKey(`expected kty=EC crv=P-256 for ${FFID_DB_TOKEN_ALGORITHM}`);
4997
+ }
4998
+ if (!isNonEmptyString(jwk.d) || !isNonEmptyString(jwk.x) || !isNonEmptyString(jwk.y)) {
4999
+ throw invalidKey("expected a private key (d, x, y)");
5000
+ }
5001
+ const kid = kidOverride ?? jwk.kid;
5002
+ if (!isNonEmptyString(kid)) {
5003
+ throw invalidKey("kid is required (Supabase matches the header kid against the imported key)");
5004
+ }
5005
+ return { jwk, kid };
5006
+ }
5007
+ function resolveTtlSeconds(ttlSeconds) {
5008
+ const ttl = ttlSeconds ?? DEFAULT_DB_TOKEN_TTL_SECONDS;
5009
+ if (!Number.isInteger(ttl) || ttl < 1 || ttl > MAX_DB_TOKEN_TTL_SECONDS) {
5010
+ throw new FFIDDbTokenError(
5011
+ FFID_DB_TOKEN_ERROR_CODES.INVALID_TTL,
5012
+ `ttlSeconds must be an integer between 1 and ${MAX_DB_TOKEN_TTL_SECONDS}`
5013
+ );
5014
+ }
5015
+ return ttl;
5016
+ }
5017
+ function requireUuid(value, code, label) {
5018
+ if (typeof value !== "string" || !UUID_PATTERN2.test(value)) {
5019
+ throw new FFIDDbTokenError(FFID_DB_TOKEN_ERROR_CODES[code], `${label} must be a UUID`);
5020
+ }
5021
+ return value.toLowerCase();
5022
+ }
5023
+ function resolveNow(now) {
5024
+ if (now === void 0) return /* @__PURE__ */ new Date();
5025
+ if (!(now instanceof Date) || Number.isNaN(now.getTime())) {
5026
+ throw new FFIDDbTokenError(FFID_DB_TOKEN_ERROR_CODES.INVALID_CLOCK, "now must be a valid Date");
5027
+ }
5028
+ return now;
5029
+ }
5030
+ function assertNoReservedClaims(claims) {
5031
+ if (!claims) return;
5032
+ for (const name of Object.keys(claims)) {
5033
+ if (RESERVED_CLAIM_SET.has(name)) {
5034
+ throw new FFIDDbTokenError(
5035
+ FFID_DB_TOKEN_ERROR_CODES.RESERVED_CLAIM,
5036
+ `Claim "${name}" is reserved by the DB token minter`
5037
+ );
5038
+ }
5039
+ }
5040
+ }
5041
+ async function importSigningKey(jwk, kid) {
5042
+ const ecParameters = { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y };
5043
+ let privateKey;
5044
+ let publicKey;
5045
+ try {
5046
+ const imported = await Promise.all([
5047
+ importJWK({ ...ecParameters, d: jwk.d, kid, alg: FFID_DB_TOKEN_ALGORITHM }, FFID_DB_TOKEN_ALGORITHM),
5048
+ importJWK({ ...ecParameters, kid, alg: FFID_DB_TOKEN_ALGORITHM }, FFID_DB_TOKEN_ALGORITHM)
5049
+ ]);
5050
+ if (imported[0] instanceof Uint8Array || imported[1] instanceof Uint8Array) {
5051
+ throw new Error("expected an asymmetric key");
5052
+ }
5053
+ ;
5054
+ [privateKey, publicKey] = imported;
5055
+ } catch (cause) {
5056
+ throw invalidKey(`key material could not be imported (${describeCause(cause)})`, cause);
5057
+ }
5058
+ try {
5059
+ const probe = await new SignJWT({}).setProtectedHeader({ alg: FFID_DB_TOKEN_ALGORITHM, kid }).sign(privateKey);
5060
+ await jwtVerify(probe, publicKey);
5061
+ } catch (cause) {
5062
+ throw invalidKey("private part (d) does not match the public part (x, y)", cause);
5063
+ }
5064
+ return privateKey;
5065
+ }
5066
+ function createDbTokenMinter(config) {
5067
+ const { jwk, kid } = parseSigningKey(config.signingKey, config.kid);
5068
+ const ttlSeconds = resolveTtlSeconds(config.ttlSeconds);
5069
+ const issuer = config.issuer;
5070
+ let keyPromise;
5071
+ const loadKey = () => {
5072
+ keyPromise ??= importSigningKey(jwk, kid).catch((error) => {
5073
+ keyPromise = void 0;
5074
+ throw error;
5075
+ });
5076
+ return keyPromise;
5077
+ };
5078
+ return {
5079
+ kid,
5080
+ ttlSeconds,
5081
+ async mint(input) {
5082
+ const sub = requireUuid(input.userId, "INVALID_USER_ID", "userId");
5083
+ const organizationId = input.organizationId === void 0 || input.organizationId === null ? void 0 : requireUuid(input.organizationId, "INVALID_ORGANIZATION_ID", "organizationId");
5084
+ assertNoReservedClaims(input.claims);
5085
+ const now = resolveNow(input.now);
5086
+ const iat = Math.floor(now.getTime() / MILLISECONDS_PER_SECOND);
5087
+ const exp = iat + ttlSeconds;
5088
+ const claims = {
5089
+ ...input.claims,
5090
+ sub,
5091
+ role: FFID_DB_TOKEN_ROLE,
5092
+ aud: FFID_DB_TOKEN_AUDIENCE,
5093
+ iat,
5094
+ exp,
5095
+ ...issuer === void 0 ? {} : { iss: issuer },
5096
+ ...organizationId === void 0 ? {} : { [FFID_DB_TOKEN_ORGANIZATION_CLAIM]: organizationId }
5097
+ };
5098
+ const key = await loadKey();
5099
+ const token = await new SignJWT(claims).setProtectedHeader({ alg: FFID_DB_TOKEN_ALGORITHM, kid, typ: "JWT" }).sign(key);
5100
+ return { token, expiresAt: new Date(exp * MILLISECONDS_PER_SECOND), claims };
5101
+ }
5102
+ };
5103
+ }
5104
+
5105
+ export { ALL_DENIED_EXCEPT_NECESSARY, CATALOG_HASH_PATTERN, CONSENT_COOKIE_NAME, COOKIE_VERSION, DEFAULT_DB_TOKEN_TTL_SECONDS, FFIDCatalogHashError, FFIDDbTokenError, FFID_ALLOWED_ORGANIZATION_LOGO_MIME_TYPES, FFID_CATALOG_ENVIRONMENTS, FFID_CATALOG_PUBLICATION_STATUSES, FFID_COMPANY_SIZE_CODES, FFID_DB_TOKEN_ALGORITHM, FFID_DB_TOKEN_AUDIENCE, FFID_DB_TOKEN_ERROR_CODES, FFID_DB_TOKEN_ORGANIZATION_CLAIM, FFID_DB_TOKEN_RESERVED_CLAIMS, FFID_DB_TOKEN_ROLE, FFID_ERROR_CODES, FFID_INDUSTRY_CODES, FFID_MAX_ORGANIZATION_LOGO_FILE_SIZE_BYTES, FFID_MAX_ORGANIZATION_LOGO_FILE_SIZE_MB, FFID_OAUTH_DENIAL_REASONS, FFID_ORGANIZATION_PROFILE_ERROR_CODES, FFID_SESSION_COOKIE_NAME, MAX_DB_TOKEN_TTL_SECONDS, canonicalizeCatalogValue, computeFFIDCheckoutCopyHash, computeLegalDisclosureHash, computePaymentConfigurationHash, computePraxisCopyHash, computeScopeHash, computeTaxConfigurationHash, createDbTokenMinter, createFFIDClient, createKVCacheAdapter, createMemoryCacheAdapter, createServerAuthClient, createTokenStore, createVerifyAccessToken, decodeConsentCookie, encodeConsentCookie, generateServerState, getFFIDAuthorizationError, getFFIDConsentFromCookieHeader, getFFIDConsentFromCookies, hashCanonicalJson, isFFIDOAuthDenialReason, sessionCookies, sha256Hex, validatePublishedCatalog };
@@ -1,4 +1,4 @@
1
- import { r as FFIDClient, e as FFIDOAuthUserInfo } from '../../ffid-client-DW8_m1_M.cjs';
1
+ import { r as FFIDClient, e as FFIDOAuthUserInfo } from '../../ffid-client-DMwmK8mM.cjs';
2
2
  import '../../types-Cjb9J0rL.cjs';
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { r as FFIDClient, e as FFIDOAuthUserInfo } from '../../ffid-client-ByfZA9sJ.js';
1
+ import { r as FFIDClient, e as FFIDOAuthUserInfo } from '../../ffid-client-Dr2KVlIZ.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": "12.0.0",
3
+ "version": "12.2.0",
4
4
  "description": "FeelFlow ID Platform SDK for React/Next.js applications",
5
5
  "keywords": [
6
6
  "feelflow",