@linked.cm/capacitor 0.2.0 → 0.3.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # @linked.cm/capacitor
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#9](https://github.com/linked-cm/capacitor/pull/9) [`19f4d89`](https://github.com/linked-cm/capacitor/commit/19f4d890aa9775c64471b1aed10cff6543a01530) Thanks [@flyon](https://github.com/flyon)! - Depend on `@_linked/auth@^3.1.0` (was `^1.2.3`), so an app on `@_linked/react` 2 no longer installs `@_linked/react` 1 through auth 1.x. `@_linked/server-utils` moves from `~1.0` to `^1.12.0`: auth 3 needs `^1.9.0`, and the old range installed a second copy whose `BackendProvider` differed from auth's.
8
+
9
+ Minor rather than patch: an app that installs this release runs auth 3, which changes what it stores and how it signs in. This is a breaking change for consumers, and minor is the breaking-change bump for a 0.x package.
10
+
11
+ **Before deploying, the app must be ready for auth 3.** See auth's changelog for 2.0.0 and 3.0.0:
12
+
13
+ - **Stored auth data needs a one-time migration.** Auth 2.0 moved every auth class and property from `http://lincd.org/ont/auth/` to `https://linked.cm/ont/auth/`. Until `migrateAuthNamespace(store)` from `@_linked/auth/utils/migrateNamespace` has run on each dataset that holds auth shapes, credentials written by auth 1.x are invisible, including the `AuthCredential` records this package creates for WhatsApp sign-ups. This package does not migrate anything itself.
14
+ - Browsers now get the auth tokens as httpOnly cookies set by the server, and access tokens last 15 minutes. Native apps keep receiving the refresh token in the body once `CapacitorProvider` registers its token storage, as before.
15
+ - Apple sign-in needs `APPLE_CLIENT_ID` and/or `APPLE_CLIENT_ID_IOS` on the server, or every Apple sign-in is rejected.
16
+
17
+ Changes in this package for auth 3:
18
+
19
+ - **Apple sign-in uses a server-issued nonce.** `SigninWithAppleButton` now calls `createOAuthNonce` first and requests the identity token with that nonce. It used to generate the nonce on the device. Auth 3 rejects any nonce it did not issue ("Invalid or expired Apple sign-in nonce"), so every Apple sign-in would have failed. The new `signinWithApple(auth, scopes)` runs the same flow. `loginWithApple(scopes, nonce?)` takes the nonce as a second argument and leaves it out of the payload when none is given. `createAppleNonce` is deprecated. An app with an RPC exposure list must expose `createOAuthNonce: 'public'`.
20
+ - **Facebook sign-in no longer works.** Auth 3 does not verify Facebook tokens, so it rejects `signinOAuth('facebook', …)` and `SigninWithFacebookButton` calls `onCallback` with `{ error: 'Unsupported OAuth provider' }`. The button stays exported. Hide it until auth supports Facebook.
21
+ - OAuth `onCallback` can receive `{ error, action: 'sign_in_to_link' }` when the email belongs to an account that already has a password. The user signs in the usual way and then calls `useAuth().linkOAuthIdentity`.
22
+ - WhatsApp sign-in passes `refreshTokenExpiresIn`/`refreshTokenExpiresAt` to `updateAuth`, so native storage keeps the refresh token for as long as the server does.
23
+ - Account-removal listeners are now awaited, and a failure stops the removal. If deleting the account's `LocationUpdateAction` fails, the account is no longer removed.
24
+
3
25
  ## 0.2.0
4
26
 
5
27
  ### Minor Changes
@@ -14,7 +14,8 @@ export type GoogleOAuthPayload = OAuthProfilePayload & {
14
14
  export type AppleOAuthPayload = OAuthProfilePayload & {
15
15
  identityToken: string;
16
16
  authorizationCode?: string;
17
- nonce: string;
17
+ /** The server-issued nonce the token was requested with, sent back for the server to redeem. */
18
+ nonce?: string;
18
19
  };
19
20
  export type FacebookOAuthPayload = {
20
21
  accessToken: string;
@@ -30,11 +31,40 @@ export declare function classifySocialLoginError(error: unknown): SocialLoginErr
30
31
  export declare function initializeSocialLogin(): Promise<void>;
31
32
  export declare function resumePendingSocialLoginRedirect(): Promise<boolean>;
32
33
  export declare function isAppleLoginSupported(): boolean;
34
+ /**
35
+ * A random base64url nonce, generated on the device.
36
+ *
37
+ * @deprecated `@_linked/auth` 3 only accepts nonces it issued itself (`createOAuthNonce`), and
38
+ * rejects an Apple sign-in that carries any other nonce. `loginWithApple` no longer uses this.
39
+ */
33
40
  export declare function createAppleNonce(): string;
34
41
  export declare function buildGoogleLoginOptions(platform: string, scopes: string[]): Record<string, never> | {
35
42
  scopes: string[];
36
43
  };
37
44
  export declare function loginWithGoogle(scopes?: string[]): Promise<GoogleOAuthPayload>;
38
- export declare function loginWithApple(scopes?: string[]): Promise<AppleOAuthPayload>;
45
+ /**
46
+ * Run the Apple sign-in prompt.
47
+ *
48
+ * @param nonce a nonce from `useAuth().createOAuthNonce()`. Apple puts it in the identity token
49
+ * and it is returned in the payload, so the server can check it issued the nonce and redeem it
50
+ * once. Without one the token carries no nonce, which `@_linked/auth` only accepts while
51
+ * `AUTH_APPLE_NONCE` is `optional`. Do not pass a nonce the server did not issue: the server
52
+ * rejects it.
53
+ */
54
+ export declare function loginWithApple(scopes?: string[], nonce?: string): Promise<AppleOAuthPayload>;
55
+ /** The part of `useAuth()` an Apple sign-in needs. */
56
+ export type AppleSigninAuth = {
57
+ createOAuthNonce: () => Promise<{
58
+ nonce: string;
59
+ }>;
60
+ signinOAuth: (provider: 'apple', payload: AppleOAuthPayload) => Promise<any>;
61
+ };
62
+ /**
63
+ * Sign in with Apple the way `@_linked/auth` 3 verifies it: ask the server for a single-use
64
+ * nonce, request the identity token with it, and send both back to `signinOAuth`.
65
+ *
66
+ * @param login the prompt to run; replaceable for tests
67
+ */
68
+ export declare function signinWithApple(auth: AppleSigninAuth, scopes?: string[], login?: typeof loginWithApple): Promise<any>;
39
69
  export declare function loginWithFacebook(permissions?: string[]): Promise<FacebookOAuthPayload>;
40
70
  export {};
@@ -150,6 +150,12 @@ export async function resumePendingSocialLoginRedirect() {
150
150
  export function isAppleLoginSupported() {
151
151
  return ['ios', 'web'].includes(Capacitor.getPlatform());
152
152
  }
153
+ /**
154
+ * A random base64url nonce, generated on the device.
155
+ *
156
+ * @deprecated `@_linked/auth` 3 only accepts nonces it issued itself (`createOAuthNonce`), and
157
+ * rejects an Apple sign-in that carries any other nonce. `loginWithApple` no longer uses this.
158
+ */
153
159
  export function createAppleNonce() {
154
160
  const bytes = new Uint8Array(32);
155
161
  globalThis.crypto.getRandomValues(bytes);
@@ -182,7 +188,16 @@ export async function loginWithGoogle(scopes = ['email', 'profile']) {
182
188
  throw classifySocialLoginError(error);
183
189
  }
184
190
  }
185
- export async function loginWithApple(scopes = ['email', 'name']) {
191
+ /**
192
+ * Run the Apple sign-in prompt.
193
+ *
194
+ * @param nonce a nonce from `useAuth().createOAuthNonce()`. Apple puts it in the identity token
195
+ * and it is returned in the payload, so the server can check it issued the nonce and redeem it
196
+ * once. Without one the token carries no nonce, which `@_linked/auth` only accepts while
197
+ * `AUTH_APPLE_NONCE` is `optional`. Do not pass a nonce the server did not issue: the server
198
+ * rejects it.
199
+ */
200
+ export async function loginWithApple(scopes = ['email', 'name'], nonce) {
186
201
  if (!isAppleLoginSupported()) {
187
202
  throw new SocialLoginError('configuration', 'Apple sign-in is not available on this device.');
188
203
  }
@@ -195,11 +210,10 @@ export async function loginWithApple(scopes = ['email', 'name']) {
195
210
  }
196
211
  }
197
212
  await initializeSocialLogin();
198
- const nonce = createAppleNonce();
199
213
  try {
200
214
  const { result } = await (await loadPluginModule()).SocialLogin.login({
201
215
  provider: 'apple',
202
- options: { scopes, nonce },
216
+ options: nonce ? { scopes, nonce } : { scopes },
203
217
  });
204
218
  if (!result.idToken) {
205
219
  throw new Error('Apple login did not return an ID token');
@@ -210,13 +224,24 @@ export async function loginWithApple(scopes = ['email', 'name']) {
210
224
  familyName: result.profile.familyName,
211
225
  identityToken: result.idToken,
212
226
  authorizationCode: result.authorizationCode,
213
- nonce,
227
+ ...(nonce ? { nonce } : {}),
214
228
  };
215
229
  }
216
230
  catch (error) {
217
231
  throw classifySocialLoginError(error);
218
232
  }
219
233
  }
234
+ /**
235
+ * Sign in with Apple the way `@_linked/auth` 3 verifies it: ask the server for a single-use
236
+ * nonce, request the identity token with it, and send both back to `signinOAuth`.
237
+ *
238
+ * @param login the prompt to run; replaceable for tests
239
+ */
240
+ export async function signinWithApple(auth, scopes = ['email', 'name'], login = loginWithApple) {
241
+ const { nonce } = await auth.createOAuthNonce();
242
+ const payload = await login(scopes, nonce);
243
+ return auth.signinOAuth('apple', payload);
244
+ }
220
245
  export async function loginWithFacebook(permissions = ['email', 'public_profile']) {
221
246
  var _a;
222
247
  if (!env.facebookClientId) {
@@ -1 +1 @@
1
- {"version":3,"file":"SocialLoginClient.js","sourceRoot":"","sources":["../../../src/auth/SocialLoginClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AA8B5C,SAAS,OAAO,CAAC,IAA8B;IAC7C,IAAI,CAAC;QACH,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAED,MAAM,GAAG,GAAG;IACV,cAAc,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC;IAC3D,iBAAiB,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC;IAClE,QAAQ,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC;IAC9C,aAAa,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC;IACjE,gBAAgB,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC;IACvE,gBAAgB,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC;IAC/D,mBAAmB,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,qBAAqB,CAAC;CACtE,CAAC;AAEF,IAAI,mBAA2D,CAAC;AAChE,IAAI,qBAAgD,CAAC;AAQrD,MAAM,qBAAqB,GAAyC;IAClE,SAAS,EAAE,wBAAwB;I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OAAO;YAC7B,iBAAiB,EAAE,MAAM,CAAC,iBAAiB;YAC3C,KAAK;SACN,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,wBAAwB,CAAC,KAAK,CAAC,CAAC;IACxC,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,WAAW,GAAG,CAAC,OAAO,EAAE,gBAAgB,CAAC;;IAEzC,IAAI,CAAC,GAAG,CAAC,gBAAgB,EAAE,CAAC;QAC1B,MAAM,kBAAkB,CAAC,sCAAsC,CAAC,CAAC;IACnE,CAAC;IACD,MAAM,qBAAqB,EAAE,CAAC;IAC9B,IAAI,CAAC;QACH,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,CACvB,MAAM,gBAAgB,EAAE,CACzB,CAAC,WAAW,CAAC,KAAK,CAAC;YAClB,QAAQ,EAAE,UAAU;YACpB,OAAO,EAAE,EAAE,WAAW,EAAE,YAAY,EAAE,KAAK,EAAE;SAC9C,CAAC,CAAC;QACH,IAAI,CAAC,CAAA,MAAA,MAAM,CAAC,WAAW,0CAAE,KAAK,CAAA,EAAE,CAAC;YAC/B,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;QACnE,CAAC;QACD,OAAO,EAAE,WAAW,EAAE,MAAM,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;IACnD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,wBAAwB,CAAC,KAAK,CAAC,CAAC;IACxC,CAAC;AACH,CAAC","sourcesContent":["import { Capacitor } from '@capacitor/core';\nimport type {\n InitializeOptions,\n SocialLoginPlugin,\n} from '@capgo/capacitor-social-login';\ntype OAuthProfilePayload = {\n email?: string;\n name?: string;\n familyName?: string;\n givenName?: string;\n fullName?: string;\n imageUrl?: string;\n};\n\nexport type GoogleOAuthPayload = OAuthProfilePayload & {\n authentication: { idToken: string };\n};\n\nexport type AppleOAuthPayload = OAuthProfilePayload & {\n identityToken: string;\n authorizationCode?: string;\n nonce: string;\n};\n\nexport type FacebookOAuthPayload = {\n accessToken: string;\n};\n\ntype SocialLoginModule = { SocialLogin: SocialLoginPlugin };\n\nfunction readEnv(read: () => string | undefined): string | undefined {\n try {\n return read();\n } catch {\n return undefined;\n }\n}\n\nconst env = {\n googleClientId: readEnv(() => process.env.GOOGLE_CLIENT_ID),\n googleIosClientId: readEnv(() => process.env.GOOGLE_CLIENT_ID_IOS),\n siteRoot: readEnv(() => process.env.SITE_ROOT),\n appleClientId: readEnv(() => process.env.APPLE_SIGN_IN_CLIENT_ID),\n appleRedirectUri: readEnv(() => process.env.APPLE_SIGN_IN_REDIRECT_URI),\n facebookClientId: readEnv(() => process.env.FACEBOOK_CLIENT_ID),\n facebookClientToken: readEnv(() => process.env.FACEBOOK_CLIENT_TOKEN),\n};\n\nlet pluginModulePromise: Promise<SocialLoginModule> | undefined;\nlet initializationPromise: Promise<void> | undefined;\n\nexport type SocialLoginErrorKind =\n | 'cancelled'\n | 'configuration'\n | 'network'\n | 'provider';\n\nconst SOCIAL_LOGIN_MESSAGES: Record<SocialLoginErrorKind, string> = {\n cancelled: 'Sign-in was cancelled.',\n configuration:\n 'Sign-in is not available right now. Please try another sign-in method.',\n network:\n \"We couldn't connect to the sign-in service. Check your internet connection and try again.\",\n provider:\n \"We couldn't complete sign-in. Please try again or use another sign-in method.\",\n};\n\nexport class SocialLoginError extends Error {\n constructor(\n public readonly kind: SocialLoginErrorKind,\n message: string,\n public readonly cause?: unknown\n ) {\n super(message);\n this.name = 'SocialLoginError';\n }\n}\n\nfunction configurationError(detail: string): SocialLoginError {\n return new SocialLoginError(\n 'configuration',\n SOCIAL_LOGIN_MESSAGES.configuration,\n new Error(detail)\n );\n}\n\nexport function resolveGoogleRedirectUri(\n siteRoot: string | undefined,\n platform: string\n): string | undefined {\n if (platform !== 'web') return undefined;\n const root = siteRoot?.trim();\n if (!root) {\n throw configurationError('SITE_ROOT is required for Google web login');\n }\n try {\n return new URL('/signin', root).toString();\n } catch (error) {\n throw new SocialLoginError(\n 'configuration',\n SOCIAL_LOGIN_MESSAGES.configuration,\n { detail: 'SITE_ROOT is not a valid URL', error }\n );\n }\n}\n\nexport function classifySocialLoginError(error: unknown): SocialLoginError {\n if (error instanceof SocialLoginError) return error;\n const details =\n error && typeof error === 'object'\n ? [\n error instanceof Error ? error.message : undefined,\n (error as { message?: unknown }).message,\n (error as { error?: unknown }).error,\n (error as { code?: unknown }).code,\n (error as { errorCode?: unknown }).errorCode,\n ]\n .filter((value) => value !== undefined)\n .join(' ')\n : String(error);\n // Each provider SDK phrases a user cancellation differently, including numeric codes.\n if (\n /cancel(?:led|ed|lation)?|popup[_\\s-]+(?:was[_\\s-]+)?closed(?:[_\\s-]+by[_\\s-]+user)?|access[_\\s-]?denied|user.*denied|dismiss(?:ed|al)?|sign[_\\s-]?in[_\\s-]?cancelled|user[_\\s-]?cancelled[_\\s-]?authorize|12501|getcredentialcancellationexception|authorizationerror[^\\d]*1001/i.test(\n details\n )\n ) {\n return new SocialLoginError(\n 'cancelled',\n SOCIAL_LOGIN_MESSAGES.cancelled,\n error\n );\n }\n if (/network|fetch|offline/i.test(details)) {\n return new SocialLoginError(\n 'network',\n SOCIAL_LOGIN_MESSAGES.network,\n error\n );\n }\n return new SocialLoginError(\n 'provider',\n SOCIAL_LOGIN_MESSAGES.provider,\n error\n );\n}\n\nasync function loadPluginModule(): Promise<SocialLoginModule> {\n if (!pluginModulePromise) {\n pluginModulePromise = import('@capgo/capacitor-social-login').catch(\n (error) => {\n pluginModulePromise = undefined;\n throw error;\n }\n );\n }\n return pluginModulePromise;\n}\n\nexport function initializeSocialLogin(): Promise<void> {\n if (!initializationPromise) {\n initializationPromise = loadPluginModule()\n .then(({ SocialLogin }) => {\n const platform = Capacitor.getPlatform();\n const options: InitializeOptions = {};\n\n if (env.googleClientId) {\n options.google = {\n webClientId: env.googleClientId,\n iOSClientId: env.googleIosClientId,\n iOSServerClientId: env.googleClientId,\n redirectUrl: resolveGoogleRedirectUri(env.siteRoot, platform),\n mode: 'online',\n };\n }\n if (platform === 'ios') {\n options.apple = {};\n } else if (\n platform === 'web' &&\n env.appleClientId &&\n env.appleRedirectUri\n ) {\n options.apple = {\n clientId: env.appleClientId,\n redirectUrl: env.appleRedirectUri,\n };\n }\n if (env.facebookClientId) {\n options.facebook = {\n appId: env.facebookClientId,\n clientToken: env.facebookClientToken,\n };\n }\n return SocialLogin.initialize(options);\n })\n .catch((error) => {\n initializationPromise = undefined;\n throw classifySocialLoginError(error);\n });\n }\n return initializationPromise;\n}\n\nexport async function resumePendingSocialLoginRedirect(): Promise<boolean> {\n if (typeof globalThis.window === 'undefined') return false;\n let pendingOAuthState: string | null;\n try {\n pendingOAuthState =\n globalThis.localStorage?.getItem('social_login_oauth_pending') ?? null;\n } catch {\n return false;\n }\n\n const callbackUrl = `${globalThis.location?.search ?? ''}&${\n globalThis.location?.hash ?? ''\n }`;\n const hasResponse = /(?:^|[?#&])(code|access_token|id_token|error)=/i.test(\n callbackUrl\n );\n const hasContext = /(?:^|[?#&])(state|iss)=/i.test(callbackUrl);\n if (\n Capacitor.getPlatform() !== 'web' ||\n pendingOAuthState === null ||\n !globalThis.window.opener ||\n !hasResponse ||\n !hasContext\n ) {\n return false;\n }\n\n await initializeSocialLogin();\n return true;\n}\n\nexport function isAppleLoginSupported(): boolean {\n return ['ios', 'web'].includes(Capacitor.getPlatform());\n}\n\nexport function createAppleNonce(): string {\n const bytes = new Uint8Array(32);\n globalThis.crypto.getRandomValues(bytes);\n const binary = Array.from(bytes, (byte) => String.fromCharCode(byte)).join(\n ''\n );\n const encoded =\n typeof globalThis.btoa === 'function'\n ? globalThis.btoa(binary)\n : Buffer.from(bytes).toString('base64');\n return encoded.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nexport function buildGoogleLoginOptions(\n platform: string,\n scopes: string[]\n): Record<string, never> | { scopes: string[] } {\n // Android rejects a caller-supplied scopes list and uses the plugin default.\n return platform === 'android' ? {} : { scopes };\n}\n\nexport async function loginWithGoogle(\n scopes = ['email', 'profile']\n): Promise<GoogleOAuthPayload> {\n if (!env.googleClientId) {\n throw configurationError('GOOGLE_CLIENT_ID is not configured');\n }\n await initializeSocialLogin();\n try {\n const { result } = await (\n await loadPluginModule()\n ).SocialLogin.login({\n provider: 'google',\n options: buildGoogleLoginOptions(Capacitor.getPlatform(), scopes),\n });\n if (result.responseType !== 'online' || !result.idToken) {\n throw new Error('Google login did not return an ID token');\n }\n return { authentication: { idToken: result.idToken } };\n } catch (error) {\n throw classifySocialLoginError(error);\n }\n}\n\nexport async function loginWithApple(\n scopes = ['email', 'name']\n): Promise<AppleOAuthPayload> {\n if (!isAppleLoginSupported()) {\n throw new SocialLoginError(\n 'configuration',\n 'Apple sign-in is not available on this device.'\n );\n }\n if (Capacitor.getPlatform() === 'web') {\n if (!env.appleClientId) {\n throw configurationError('APPLE_SIGN_IN_CLIENT_ID is not configured');\n }\n if (!env.appleRedirectUri) {\n throw configurationError('APPLE_SIGN_IN_REDIRECT_URI is not configured');\n }\n }\n await initializeSocialLogin();\n const nonce = createAppleNonce();\n try {\n const { result } = await (\n await loadPluginModule()\n ).SocialLogin.login({\n provider: 'apple',\n options: { scopes, nonce },\n });\n if (!result.idToken) {\n throw new Error('Apple login did not return an ID token');\n }\n return {\n email: result.profile.email,\n givenName: result.profile.givenName,\n familyName: result.profile.familyName,\n identityToken: result.idToken,\n authorizationCode: result.authorizationCode,\n nonce,\n };\n } catch (error) {\n throw classifySocialLoginError(error);\n }\n}\n\nexport async function loginWithFacebook(\n permissions = ['email', 'public_profile']\n): Promise<FacebookOAuthPayload> {\n if (!env.facebookClientId) {\n throw configurationError('FACEBOOK_CLIENT_ID is not configured');\n }\n await initializeSocialLogin();\n try {\n const { result } = await (\n await loadPluginModule()\n ).SocialLogin.login({\n provider: 'facebook',\n options: { permissions, limitedLogin: false },\n });\n if (!result.accessToken?.token) {\n throw new Error('Facebook login did not return an access token');\n }\n return { accessToken: result.accessToken.token };\n } catch (error) {\n throw classifySocialLoginError(error);\n }\n}\n"]}
1
+ {"version":3,"file":"SocialLoginClient.js","sourceRoot":"","sources":["../../../src/auth/SocialLoginClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AA+B5C,SAAS,OAAO,CAAC,IAA8B;IAC7C,IAAI,CAAC;QACH,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAED,MAAM,GAAG,GAAG;IACV,cAAc,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC;IAC3D,iBAAiB,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC;IAClE,QAAQ,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC;IAC9C,aAAa,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC;IACjE,gBAAgB,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC;IACvE,gBAAgB,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC;IAC/D,mBAAmB,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,qBAAqB,CAAC;CACtE,CAAC;AAEF,IAAI,mBAA2D,CAAC;AAChE,IAAI,qBAAgD,CAAC;AAQrD,MAAM,qBAAqB,GAAyC;IAClE,SAAS,EAAE,wBAAwB;IACnC,aAAa,EACX,wEAAwE;IAC1E,OAAO,EACL,2FAA2F;IAC7F,QAAQ,EACN,+EAA+E;CAClF,CAAC;AAEF,MAAM,OAAO,gBAA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EAAE,CAAC;IACnD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,wBAAwB,CAAC,KAAK,CAAC,CAAC;IACxC,CAAC;AACH,CAAC","sourcesContent":["import { Capacitor } from '@capacitor/core';\nimport type {\n InitializeOptions,\n SocialLoginPlugin,\n} from '@capgo/capacitor-social-login';\ntype OAuthProfilePayload = {\n email?: string;\n name?: string;\n familyName?: string;\n givenName?: string;\n fullName?: string;\n imageUrl?: string;\n};\n\nexport type GoogleOAuthPayload = OAuthProfilePayload & {\n authentication: { idToken: string };\n};\n\nexport type AppleOAuthPayload = OAuthProfilePayload & {\n identityToken: string;\n authorizationCode?: string;\n /** The server-issued nonce the token was requested with, sent back for the server to redeem. */\n nonce?: string;\n};\n\nexport type FacebookOAuthPayload = {\n accessToken: string;\n};\n\ntype SocialLoginModule = { SocialLogin: SocialLoginPlugin };\n\nfunction readEnv(read: () => string | undefined): string | undefined {\n try {\n return read();\n } catch {\n return undefined;\n }\n}\n\nconst env = {\n googleClientId: readEnv(() => process.env.GOOGLE_CLIENT_ID),\n googleIosClientId: readEnv(() => process.env.GOOGLE_CLIENT_ID_IOS),\n siteRoot: readEnv(() => process.env.SITE_ROOT),\n appleClientId: readEnv(() => process.env.APPLE_SIGN_IN_CLIENT_ID),\n appleRedirectUri: readEnv(() => process.env.APPLE_SIGN_IN_REDIRECT_URI),\n facebookClientId: readEnv(() => process.env.FACEBOOK_CLIENT_ID),\n facebookClientToken: readEnv(() => process.env.FACEBOOK_CLIENT_TOKEN),\n};\n\nlet pluginModulePromise: Promise<SocialLoginModule> | undefined;\nlet initializationPromise: Promise<void> | undefined;\n\nexport type SocialLoginErrorKind =\n | 'cancelled'\n | 'configuration'\n | 'network'\n | 'provider';\n\nconst SOCIAL_LOGIN_MESSAGES: Record<SocialLoginErrorKind, string> = {\n cancelled: 'Sign-in was cancelled.',\n configuration:\n 'Sign-in is not available right now. Please try another sign-in method.',\n network:\n \"We couldn't connect to the sign-in service. Check your internet connection and try again.\",\n provider:\n \"We couldn't complete sign-in. Please try again or use another sign-in method.\",\n};\n\nexport class SocialLoginError extends Error {\n constructor(\n public readonly kind: SocialLoginErrorKind,\n message: string,\n public readonly cause?: unknown\n ) {\n super(message);\n this.name = 'SocialLoginError';\n }\n}\n\nfunction configurationError(detail: string): SocialLoginError {\n return new SocialLoginError(\n 'configuration',\n SOCIAL_LOGIN_MESSAGES.configuration,\n new Error(detail)\n );\n}\n\nexport function resolveGoogleRedirectUri(\n siteRoot: string | undefined,\n platform: string\n): string | undefined {\n if (platform !== 'web') return undefined;\n const root = siteRoot?.trim();\n if (!root) {\n throw configurationError('SITE_ROOT is required for Google web login');\n }\n try {\n return new URL('/signin', root).toString();\n } catch (error) {\n throw new SocialLoginError(\n 'configuration',\n SOCIAL_LOGIN_MESSAGES.configuration,\n { detail: 'SITE_ROOT is not a valid URL', error }\n );\n }\n}\n\nexport function classifySocialLoginError(error: unknown): SocialLoginError {\n if (error instanceof SocialLoginError) return error;\n const details =\n error && typeof error === 'object'\n ? [\n error instanceof Error ? error.message : undefined,\n (error as { message?: unknown }).message,\n (error as { error?: unknown }).error,\n (error as { code?: unknown }).code,\n (error as { errorCode?: unknown }).errorCode,\n ]\n .filter((value) => value !== undefined)\n .join(' ')\n : String(error);\n // Each provider SDK phrases a user cancellation differently, including numeric codes.\n if (\n /cancel(?:led|ed|lation)?|popup[_\\s-]+(?:was[_\\s-]+)?closed(?:[_\\s-]+by[_\\s-]+user)?|access[_\\s-]?denied|user.*denied|dismiss(?:ed|al)?|sign[_\\s-]?in[_\\s-]?cancelled|user[_\\s-]?cancelled[_\\s-]?authorize|12501|getcredentialcancellationexception|authorizationerror[^\\d]*1001/i.test(\n details\n )\n ) {\n return new SocialLoginError(\n 'cancelled',\n SOCIAL_LOGIN_MESSAGES.cancelled,\n error\n );\n }\n if (/network|fetch|offline/i.test(details)) {\n return new SocialLoginError(\n 'network',\n SOCIAL_LOGIN_MESSAGES.network,\n error\n );\n }\n return new SocialLoginError(\n 'provider',\n SOCIAL_LOGIN_MESSAGES.provider,\n error\n );\n}\n\nasync function loadPluginModule(): Promise<SocialLoginModule> {\n if (!pluginModulePromise) {\n pluginModulePromise = import('@capgo/capacitor-social-login').catch(\n (error) => {\n pluginModulePromise = undefined;\n throw error;\n }\n );\n }\n return pluginModulePromise;\n}\n\nexport function initializeSocialLogin(): Promise<void> {\n if (!initializationPromise) {\n initializationPromise = loadPluginModule()\n .then(({ SocialLogin }) => {\n const platform = Capacitor.getPlatform();\n const options: InitializeOptions = {};\n\n if (env.googleClientId) {\n options.google = {\n webClientId: env.googleClientId,\n iOSClientId: env.googleIosClientId,\n iOSServerClientId: env.googleClientId,\n redirectUrl: resolveGoogleRedirectUri(env.siteRoot, platform),\n mode: 'online',\n };\n }\n if (platform === 'ios') {\n options.apple = {};\n } else if (\n platform === 'web' &&\n env.appleClientId &&\n env.appleRedirectUri\n ) {\n options.apple = {\n clientId: env.appleClientId,\n redirectUrl: env.appleRedirectUri,\n };\n }\n if (env.facebookClientId) {\n options.facebook = {\n appId: env.facebookClientId,\n clientToken: env.facebookClientToken,\n };\n }\n return SocialLogin.initialize(options);\n })\n .catch((error) => {\n initializationPromise = undefined;\n throw classifySocialLoginError(error);\n });\n }\n return initializationPromise;\n}\n\nexport async function resumePendingSocialLoginRedirect(): Promise<boolean> {\n if (typeof globalThis.window === 'undefined') return false;\n let pendingOAuthState: string | null;\n try {\n pendingOAuthState =\n globalThis.localStorage?.getItem('social_login_oauth_pending') ?? null;\n } catch {\n return false;\n }\n\n const callbackUrl = `${globalThis.location?.search ?? ''}&${\n globalThis.location?.hash ?? ''\n }`;\n const hasResponse = /(?:^|[?#&])(code|access_token|id_token|error)=/i.test(\n callbackUrl\n );\n const hasContext = /(?:^|[?#&])(state|iss)=/i.test(callbackUrl);\n if (\n Capacitor.getPlatform() !== 'web' ||\n pendingOAuthState === null ||\n !globalThis.window.opener ||\n !hasResponse ||\n !hasContext\n ) {\n return false;\n }\n\n await initializeSocialLogin();\n return true;\n}\n\nexport function isAppleLoginSupported(): boolean {\n return ['ios', 'web'].includes(Capacitor.getPlatform());\n}\n\n/**\n * A random base64url nonce, generated on the device.\n *\n * @deprecated `@_linked/auth` 3 only accepts nonces it issued itself (`createOAuthNonce`), and\n * rejects an Apple sign-in that carries any other nonce. `loginWithApple` no longer uses this.\n */\nexport function createAppleNonce(): string {\n const bytes = new Uint8Array(32);\n globalThis.crypto.getRandomValues(bytes);\n const binary = Array.from(bytes, (byte) => String.fromCharCode(byte)).join(\n ''\n );\n const encoded =\n typeof globalThis.btoa === 'function'\n ? globalThis.btoa(binary)\n : Buffer.from(bytes).toString('base64');\n return encoded.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nexport function buildGoogleLoginOptions(\n platform: string,\n scopes: string[]\n): Record<string, never> | { scopes: string[] } {\n // Android rejects a caller-supplied scopes list and uses the plugin default.\n return platform === 'android' ? {} : { scopes };\n}\n\nexport async function loginWithGoogle(\n scopes = ['email', 'profile']\n): Promise<GoogleOAuthPayload> {\n if (!env.googleClientId) {\n throw configurationError('GOOGLE_CLIENT_ID is not configured');\n }\n await initializeSocialLogin();\n try {\n const { result } = await (\n await loadPluginModule()\n ).SocialLogin.login({\n provider: 'google',\n options: buildGoogleLoginOptions(Capacitor.getPlatform(), scopes),\n });\n if (result.responseType !== 'online' || !result.idToken) {\n throw new Error('Google login did not return an ID token');\n }\n return { authentication: { idToken: result.idToken } };\n } catch (error) {\n throw classifySocialLoginError(error);\n }\n}\n\n/**\n * Run the Apple sign-in prompt.\n *\n * @param nonce a nonce from `useAuth().createOAuthNonce()`. Apple puts it in the identity token\n * and it is returned in the payload, so the server can check it issued the nonce and redeem it\n * once. Without one the token carries no nonce, which `@_linked/auth` only accepts while\n * `AUTH_APPLE_NONCE` is `optional`. Do not pass a nonce the server did not issue: the server\n * rejects it.\n */\nexport async function loginWithApple(\n scopes = ['email', 'name'],\n nonce?: string\n): Promise<AppleOAuthPayload> {\n if (!isAppleLoginSupported()) {\n throw new SocialLoginError(\n 'configuration',\n 'Apple sign-in is not available on this device.'\n );\n }\n if (Capacitor.getPlatform() === 'web') {\n if (!env.appleClientId) {\n throw configurationError('APPLE_SIGN_IN_CLIENT_ID is not configured');\n }\n if (!env.appleRedirectUri) {\n throw configurationError('APPLE_SIGN_IN_REDIRECT_URI is not configured');\n }\n }\n await initializeSocialLogin();\n try {\n const { result } = await (\n await loadPluginModule()\n ).SocialLogin.login({\n provider: 'apple',\n options: nonce ? { scopes, nonce } : { scopes },\n });\n if (!result.idToken) {\n throw new Error('Apple login did not return an ID token');\n }\n return {\n email: result.profile.email,\n givenName: result.profile.givenName,\n familyName: result.profile.familyName,\n identityToken: result.idToken,\n authorizationCode: result.authorizationCode,\n ...(nonce ? { nonce } : {}),\n };\n } catch (error) {\n throw classifySocialLoginError(error);\n }\n}\n\n/** The part of `useAuth()` an Apple sign-in needs. */\nexport type AppleSigninAuth = {\n createOAuthNonce: () => Promise<{ nonce: string }>;\n signinOAuth: (provider: 'apple', payload: AppleOAuthPayload) => Promise<any>;\n};\n\n/**\n * Sign in with Apple the way `@_linked/auth` 3 verifies it: ask the server for a single-use\n * nonce, request the identity token with it, and send both back to `signinOAuth`.\n *\n * @param login the prompt to run; replaceable for tests\n */\nexport async function signinWithApple(\n auth: AppleSigninAuth,\n scopes = ['email', 'name'],\n login: typeof loginWithApple = loginWithApple\n) {\n const { nonce } = await auth.createOAuthNonce();\n const payload = await login(scopes, nonce);\n return auth.signinOAuth('apple', payload);\n}\n\nexport async function loginWithFacebook(\n permissions = ['email', 'public_profile']\n): Promise<FacebookOAuthPayload> {\n if (!env.facebookClientId) {\n throw configurationError('FACEBOOK_CLIENT_ID is not configured');\n }\n await initializeSocialLogin();\n try {\n const { result } = await (\n await loadPluginModule()\n ).SocialLogin.login({\n provider: 'facebook',\n options: { permissions, limitedLogin: false },\n });\n if (!result.accessToken?.token) {\n throw new Error('Facebook login did not return an access token');\n }\n return { accessToken: result.accessToken.token };\n } catch (error) {\n throw classifySocialLoginError(error);\n }\n}\n"]}
@@ -36,10 +36,15 @@ export const SigninWithWhatsappButton = ({ label = 'Sign in with Whatsapp', clas
36
36
  return;
37
37
  Server.call(packageName, 'validateOTPWhatsapp', phone, otp).then((response) => {
38
38
  if (response && response.auth) {
39
+ // A browser gets the tokens as httpOnly cookies the server already set; only a
40
+ // native client (body transport) receives refreshToken. The expiry fields size the
41
+ // refresh token in native storage to the server's record.
39
42
  auth.updateAuth({
40
43
  auth: response.auth,
41
44
  accessToken: response.accessToken,
42
45
  refreshToken: response.refreshToken,
46
+ refreshTokenExpiresIn: response.refreshTokenExpiresIn,
47
+ refreshTokenExpiresAt: response.refreshTokenExpiresAt,
43
48
  });
44
49
  onSuccess(true);
45
50
  }
@@ -1 +1 @@
1
- {"version":3,"file":"SignInWithWhatsapp.js","sourceRoot":"","sources":["../../../src/components/SignInWithWhatsapp.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,KAAK,MAAM,iCAAiC,CAAC;AACpD,OAAO,EAAE,MAAM,EAAE,MAAM,uCAAuC,CAAC;AAC/D,OAAO,EAAE,EAAE,EAAE,MAAM,iCAAiC,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,MAAM,EAAE,MAAM,oCAAoC,CAAC;AAC5D,OAAO,EACL,QAAQ,EACR,aAAa,EACb,YAAY,EACZ,kBAAkB,GACnB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AACvD,OAAO,qCAAqC,CAAC;AAC7C,OAAO,QAAQ,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC;AACtD,OAAO,EAAE,KAAK,EAAE,MAAM,uCAAuC,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAE7C,MAAM,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AAO,CAAC,CAAC,CAAC,CAC5B,6BAAK,SAAS,EAAE,KAAK,CAAC,UAAU,yBAA0B,CAC3D,CAAC,CAAC,CAAC,IAAI,CACJ,CACP,CAAC,CAAC,CAAC,CACF;QACE,sDAA4B;QAC5B,oBAAC,QAAQ,IACP,SAAS,EAAE,CAAC,EACZ,OAAO,EAAE,kBAAkB,EAC3B,SAAS,EAAC,SAAS,EACnB,YAAY,EAAC,eAAe,EAC5B,UAAU,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,WAAW,CAAC,WAAW,EAAE,GAAG,CAAC;YAElD,oBAAC,aAAa,QACX,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC,CACvC,oBAAC,YAAY,IAAC,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,GAAI,CAC3C,CAAC,CACY,CACP,CACV,CACJ,CACA,CACJ,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import React from 'react';\nimport style from './SignInWithWhatsapp.module.css';\nimport { Button } from '@_linked/primitives/components/Button';\nimport { cl } from '@_linked/react/utils/ClassNames';\nimport { packageName } from '../package.js';\nimport { Server } from '@_linked/server-utils/utils/Server';\nimport {\n InputOTP,\n InputOTPGroup,\n InputOTPSlot,\n REGEXP_ONLY_DIGITS,\n} from '@_linked/primitives/components/InputOTP';\nimport { PhoneInput } from 'react-international-phone';\nimport 'react-international-phone/style.css';\nimport libphone from 'google-libphonenumber';\nimport { useAuth } from '@_linked/auth/hooks/useAuth';\nimport { asset } from '@_linked/core/utils/LinkedFileStorage';\nimport { useTranslate } from '@tolgee/react';\n\nconst PhoneNumberUtil = libphone.PhoneNumberUtil;\n\ninterface SigninWithWhatsappButton\n extends Omit<React.ComponentProps<typeof Button>, 'onClick' | 'children'> {\n label?: string;\n onSuccess: (data: boolean) => void;\n}\n\nexport const SigninWithWhatsappButton = ({\n label = 'Sign in with Whatsapp',\n className,\n onSuccess,\n ...buttonProps\n}: SigninWithWhatsappButton) => {\n const phoneUtil = PhoneNumberUtil.getInstance();\n const isPhoneValid = (phoneNumber: string) => {\n try {\n return phoneUtil.isValidNumber(\n phoneUtil.parseAndKeepRawInput(phoneNumber)\n );\n } catch {\n return false;\n }\n };\n const [otpField, setOTPField] = React.useState(false);\n const [phoneNumber, setPhoneNumber] = React.useState('');\n const [phoneNumberField, setPhoneNumberField] = React.useState(false);\n const [isLoading, setLoading] = React.useState(false);\n const [showPhoneError, setShowPhoneError] = React.useState(false);\n const isValid = isPhoneValid(phoneNumber);\n\n const auth = useAuth();\n const { t } = useTranslate();\n const prefix = 'signIn';\n\n const validateOTP = (phone: string, otp: string) => {\n if (!phone || !otp) return;\n Server.call(packageName, 'validateOTPWhatsapp', phone, otp).then(\n (response) => {\n if (response && response.auth) {\n auth.updateAuth({\n auth: response.auth,\n accessToken: response.accessToken,\n refreshToken: response.refreshToken,\n });\n onSuccess(true);\n } else if (response?.error) {\n alert(response.error);\n } else {\n onSuccess(false);\n }\n }\n );\n };\n\n const sendWhatsappMessage = (phone: string) => {\n if (!isValid) {\n setShowPhoneError(true);\n return;\n }\n setShowPhoneError(false);\n setLoading(true);\n Server.call(packageName, 'generateOTPWhatsapp', phone)\n .then(() => {\n setOTPField(true);\n })\n .catch(() => {\n alert('Could not send the code. Please try again.');\n })\n .finally(() => {\n setLoading(false);\n });\n };\n\n return (\n <>\n {!otpField && !phoneNumberField ? (\n <Button\n type=\"button\"\n className={cl(style.root, className)}\n onClick={() => setPhoneNumberField(true)}\n variant=\"outline\"\n {...buttonProps}\n >\n <img\n src={asset('/images/wa_icon.png')}\n alt=\"\"\n className={style.WhatsappIcon}\n />\n {t(prefix + '.whatsapp', label)}\n </Button>\n ) : isLoading ? (\n <img\n src={asset('/images/loading.gif')}\n className={style.loading}\n alt=\"loading\"\n />\n ) : phoneNumberField && !otpField ? (\n <div className={style.phoneStep}>\n <div className={style.phoneRow}>\n <PhoneInput\n className={style.phoneInput}\n defaultCountry=\"us\"\n value={phoneNumber}\n onChange={(nextPhone) => setPhoneNumber(nextPhone)}\n inputProps={{\n placeholder: '+1 555 123 4567',\n }}\n />\n <button\n type=\"button\"\n className={style.signButton}\n aria-label=\"Send code\"\n onClick={() => sendWhatsappMessage(phoneNumber)}\n >\n <img src={asset('/images/signButton.png')} alt=\"\" />\n </button>\n </div>\n {showPhoneError && !isValid ? (\n <div className={style.phoneError}>Phone is not valid</div>\n ) : null}\n </div>\n ) : (\n <>\n <h3>Enter your OTP code</h3>\n <InputOTP\n maxLength={6}\n pattern={REGEXP_ONLY_DIGITS}\n inputMode=\"numeric\"\n autoComplete=\"one-time-code\"\n onComplete={(otp) => validateOTP(phoneNumber, otp)}\n >\n <InputOTPGroup>\n {Array.from({ length: 6 }, (_, index) => (\n <InputOTPSlot key={index} index={index} />\n ))}\n </InputOTPGroup>\n </InputOTP>\n </>\n )}\n </>\n );\n};\n"]}
1
+ {"version":3,"file":"SignInWithWhatsapp.js","sourceRoot":"","sources":["../../../src/components/SignInWithWhatsapp.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,KAAK,MAAM,iCAAiC,CAAC;AACpD,OAAO,EAAE,MAAM,EAAE,MAAM,uCAAuC,CAAC;AAC/D,OAAO,EAAE,EAAE,EAAE,MAAM,iCAAiC,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,MAAM,EAAE,MAAM,oCAAoC,CAAC;AAC5D,OAAO,EACL,QAAQ,EACR,aAAa,EACb,YAAY,EACZ,kBAAkB,GACnB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AACvD,OAAO,qCAAqC,CAAC;AAC7C,OAAO,QAAQ,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC;AACtD,OAAO,EAAE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,EACb,SAAS,EAAE,KAAK,CAAC,UAAU,gBAChB,WAAW,EACtB,OAAO,EAAE,GAAG,EAAE,CAAC,mBAAmB,CAAC,WAAW,CAAC;gBAE/C,6BAAK,GAAG,EAAE,KAAK,CAAC,wBAAwB,CAAC,EAAE,GAAG,EAAC,EAAE,GAAG,CAC7C,CACL;QACL,cAAc,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAC5B,6BAAK,SAAS,EAAE,KAAK,CAAC,UAAU,yBAA0B,CAC3D,CAAC,CAAC,CAAC,IAAI,CACJ,CACP,CAAC,CAAC,CAAC,CACF;QACE,sDAA4B;QAC5B,oBAAC,QAAQ,IACP,SAAS,EAAE,CAAC,EACZ,OAAO,EAAE,kBAAkB,EAC3B,SAAS,EAAC,SAAS,EACnB,YAAY,EAAC,eAAe,EAC5B,UAAU,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,WAAW,CAAC,WAAW,EAAE,GAAG,CAAC;YAElD,oBAAC,aAAa,QACX,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC,CACvC,oBAAC,YAAY,IAAC,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,GAAI,CAC3C,CAAC,CACY,CACP,CACV,CACJ,CACA,CACJ,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import React from 'react';\nimport style from './SignInWithWhatsapp.module.css';\nimport { Button } from '@_linked/primitives/components/Button';\nimport { cl } from '@_linked/react/utils/ClassNames';\nimport { packageName } from '../package.js';\nimport { Server } from '@_linked/server-utils/utils/Server';\nimport {\n InputOTP,\n InputOTPGroup,\n InputOTPSlot,\n REGEXP_ONLY_DIGITS,\n} from '@_linked/primitives/components/InputOTP';\nimport { PhoneInput } from 'react-international-phone';\nimport 'react-international-phone/style.css';\nimport libphone from 'google-libphonenumber';\nimport { useAuth } from '@_linked/auth/hooks/useAuth';\nimport { asset } from '@_linked/core/utils/LinkedFileStorage';\nimport { useTranslate } from '@tolgee/react';\n\nconst PhoneNumberUtil = libphone.PhoneNumberUtil;\n\ninterface SigninWithWhatsappButton\n extends Omit<React.ComponentProps<typeof Button>, 'onClick' | 'children'> {\n label?: string;\n onSuccess: (data: boolean) => void;\n}\n\nexport const SigninWithWhatsappButton = ({\n label = 'Sign in with Whatsapp',\n className,\n onSuccess,\n ...buttonProps\n}: SigninWithWhatsappButton) => {\n const phoneUtil = PhoneNumberUtil.getInstance();\n const isPhoneValid = (phoneNumber: string) => {\n try {\n return phoneUtil.isValidNumber(\n phoneUtil.parseAndKeepRawInput(phoneNumber)\n );\n } catch {\n return false;\n }\n };\n const [otpField, setOTPField] = React.useState(false);\n const [phoneNumber, setPhoneNumber] = React.useState('');\n const [phoneNumberField, setPhoneNumberField] = React.useState(false);\n const [isLoading, setLoading] = React.useState(false);\n const [showPhoneError, setShowPhoneError] = React.useState(false);\n const isValid = isPhoneValid(phoneNumber);\n\n const auth = useAuth();\n const { t } = useTranslate();\n const prefix = 'signIn';\n\n const validateOTP = (phone: string, otp: string) => {\n if (!phone || !otp) return;\n Server.call(packageName, 'validateOTPWhatsapp', phone, otp).then(\n (response) => {\n if (response && response.auth) {\n // A browser gets the tokens as httpOnly cookies the server already set; only a\n // native client (body transport) receives refreshToken. The expiry fields size the\n // refresh token in native storage to the server's record.\n auth.updateAuth({\n auth: response.auth,\n accessToken: response.accessToken,\n refreshToken: response.refreshToken,\n refreshTokenExpiresIn: response.refreshTokenExpiresIn,\n refreshTokenExpiresAt: response.refreshTokenExpiresAt,\n });\n onSuccess(true);\n } else if (response?.error) {\n alert(response.error);\n } else {\n onSuccess(false);\n }\n }\n );\n };\n\n const sendWhatsappMessage = (phone: string) => {\n if (!isValid) {\n setShowPhoneError(true);\n return;\n }\n setShowPhoneError(false);\n setLoading(true);\n Server.call(packageName, 'generateOTPWhatsapp', phone)\n .then(() => {\n setOTPField(true);\n })\n .catch(() => {\n alert('Could not send the code. Please try again.');\n })\n .finally(() => {\n setLoading(false);\n });\n };\n\n return (\n <>\n {!otpField && !phoneNumberField ? (\n <Button\n type=\"button\"\n className={cl(style.root, className)}\n onClick={() => setPhoneNumberField(true)}\n variant=\"outline\"\n {...buttonProps}\n >\n <img\n src={asset('/images/wa_icon.png')}\n alt=\"\"\n className={style.WhatsappIcon}\n />\n {t(prefix + '.whatsapp', label)}\n </Button>\n ) : isLoading ? (\n <img\n src={asset('/images/loading.gif')}\n className={style.loading}\n alt=\"loading\"\n />\n ) : phoneNumberField && !otpField ? (\n <div className={style.phoneStep}>\n <div className={style.phoneRow}>\n <PhoneInput\n className={style.phoneInput}\n defaultCountry=\"us\"\n value={phoneNumber}\n onChange={(nextPhone) => setPhoneNumber(nextPhone)}\n inputProps={{\n placeholder: '+1 555 123 4567',\n }}\n />\n <button\n type=\"button\"\n className={style.signButton}\n aria-label=\"Send code\"\n onClick={() => sendWhatsappMessage(phoneNumber)}\n >\n <img src={asset('/images/signButton.png')} alt=\"\" />\n </button>\n </div>\n {showPhoneError && !isValid ? (\n <div className={style.phoneError}>Phone is not valid</div>\n ) : null}\n </div>\n ) : (\n <>\n <h3>Enter your OTP code</h3>\n <InputOTP\n maxLength={6}\n pattern={REGEXP_ONLY_DIGITS}\n inputMode=\"numeric\"\n autoComplete=\"one-time-code\"\n onComplete={(otp) => validateOTP(phoneNumber, otp)}\n >\n <InputOTPGroup>\n {Array.from({ length: 6 }, (_, index) => (\n <InputOTPSlot key={index} index={index} />\n ))}\n </InputOTPGroup>\n </InputOTP>\n </>\n )}\n </>\n );\n};\n"]}
@@ -3,7 +3,7 @@ import style from './SigninWithAppleButton.module.css';
3
3
  import { Button } from '@_linked/primitives/components/Button';
4
4
  import { cl } from '@_linked/react/utils/ClassNames';
5
5
  import { useAuth } from '@_linked/auth/hooks/useAuth';
6
- import { classifySocialLoginError, isAppleLoginSupported, loginWithApple, } from '../auth/SocialLoginClient.js';
6
+ import { classifySocialLoginError, isAppleLoginSupported, signinWithApple, } from '../auth/SocialLoginClient.js';
7
7
  export const SigninWithAppleButton = ({ label = 'Sign in with Apple', scopes = 'email name', className, onCallback, onLoadingChange, restProps, disabled: disabledByCaller = false, ...buttonProps }) => {
8
8
  const [loading, setLoading] = useState(false);
9
9
  const auth = useAuth();
@@ -17,8 +17,8 @@ export const SigninWithAppleButton = ({ label = 'Sign in with Apple', scopes = '
17
17
  let result;
18
18
  try {
19
19
  onLoadingChange === null || onLoadingChange === void 0 ? void 0 : onLoadingChange(true);
20
- const payload = await loginWithApple(scopes.split(/\s+/).filter(Boolean));
21
- result = await auth.signinOAuth('apple', payload);
20
+ // the server issues the nonce and redeems it once (@_linked/auth 3)
21
+ result = await signinWithApple(auth, scopes.split(/\s+/).filter(Boolean));
22
22
  }
23
23
  catch (error) {
24
24
  const loginError = classifySocialLoginError(error);
@@ -1 +1 @@
1
- {"version":3,"file":"SigninWithAppleButton.js","sourceRoot":"","sources":["../../../src/components/SigninWithAppleButton.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAChD,OAAO,KAAK,MAAM,oCAAoC,CAAC;AACvD,OAAO,EAAE,MAAM,EAAE,MAAM,uCAAuC,CAAC;AAC/D,OAAO,EAAE,EAAE,EAAE,MAAM,iCAAiC,CAAC;AACrD,OAAO,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC;AAEtD,OAAO,EACL,wBAAwB,EACxB,qBAAqB,EACrB,cAAc,GACf,MAAM,8BAA8B,CAAC;AAWtC,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,EACpC,KAAK,GAAG,oBAAoB,EAC5B,MAAM,GAAG,YAAY,EACrB,SAAS,EACT,UAAU,EACV,eAAe,EACf,SAAS,EACT,QAAQ,EAAE,gBAAgB,GAAG,KAAK,EAClC,GAAG,WAAW,EACa,EAAE,EAAE;IAC/B,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,GAAG,QAAQ,CA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,QAAQ,EACb,SAAS,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,EACpC,OAAO,EAAC,SAAS,KACb,SAAS,KACT,WAAW,EACf,OAAO,EAAE,eAAe,EACxB,QAAQ,EAAE,OAAO,IAAI,gBAAgB,KAAI,SAAS,aAAT,SAAS,uBAAT,SAAS,CAAE,QAAQ,CAAA;QAE5D,6BAAK,SAAS,EAAE,KAAK,CAAC,IAAI,EAAE,OAAO,EAAC,cAAc;YAC9C,8BACE,CAAC,EAAC,+uBAA+uB,EACjvB,IAAI,EAAC,MAAM,EACX,QAAQ,EAAC,SAAS,GAClB,CACA;QACL,KAAK,CACC,CACV,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import React, { useRef, useState } from 'react';\nimport style from './SigninWithAppleButton.module.css';\nimport { Button } from '@_linked/primitives/components/Button';\nimport { cl } from '@_linked/react/utils/ClassNames';\nimport { useAuth } from '@_linked/auth/hooks/useAuth';\nimport type { AuthenticationResult } from '@_linked/auth/types/auth';\nimport {\n classifySocialLoginError,\n isAppleLoginSupported,\n loginWithApple,\n} from '../auth/SocialLoginClient.js';\n\ninterface SigninWithAppleButtonProps\n extends Omit<React.ComponentProps<typeof Button>, 'onClick' | 'children'> {\n label?: string;\n scopes?: string;\n className?: string;\n onCallback: (data: AuthenticationResult) => void;\n restProps?: any;\n onLoadingChange?: (loading: boolean) => void;\n}\nexport const SigninWithAppleButton = ({\n label = 'Sign in with Apple',\n scopes = 'email name',\n className,\n onCallback,\n onLoadingChange,\n restProps,\n disabled: disabledByCaller = false,\n ...buttonProps\n}: SigninWithAppleButtonProps) => {\n const [loading, setLoading] = useState(false);\n\n const auth = useAuth();\n const loginInFlight = useRef(false);\n const isSupportedPlatform = isAppleLoginSupported();\n\n const signInWithApple = async () => {\n if (loginInFlight.current) return;\n loginInFlight.current = true;\n setLoading(true);\n let result: AuthenticationResult | undefined;\n try {\n onLoadingChange?.(true);\n const payload = await loginWithApple(scopes.split(/\\s+/).filter(Boolean));\n result = await auth.signinOAuth('apple', payload);\n } catch (error) {\n const loginError = classifySocialLoginError(error);\n if (loginError.kind !== 'cancelled') {\n result = { error: loginError.message };\n }\n } finally {\n loginInFlight.current = false;\n setLoading(false);\n onLoadingChange?.(false);\n }\n if (result) onCallback(result);\n };\n\n if (!isSupportedPlatform) {\n return null;\n }\n\n return (\n <Button\n type=\"button\"\n className={cl(style.root, className)}\n variant=\"outline\"\n {...restProps}\n {...buttonProps}\n onClick={signInWithApple}\n disabled={loading || disabledByCaller || restProps?.disabled}\n >\n <svg className={style.icon} viewBox=\"-1.5 0 20 20\">\n <path\n d=\"M11.570887 3.19296C12.29996 2.34797 12.791401 1.17098 12.656912 0c-1.050633.04-2.321706.67099-3.075048 1.51498-.67649.74899-1.267029 1.94597-1.10827 3.09396 1.171976.08699 2.36822-.57 3.097293-1.41598m2.6281 7.43189C14.22831 13.65181 16.969663 14.65879 17 14.67179c-.022246.071-.437848 1.43498-1.443988 2.84496-.87064 1.21799-1.773639 2.43097-3.196392 2.45697-1.397473.025-1.847455-.79399-3.446157-.79399-1.59769 0-2.09722.76799-3.419865.81899-1.373205.049-2.419793-1.31798-3.2965-2.53196C.403236 14.98379-.966935 10.44985.873442 7.3899c.914121-1.51898 2.547203-2.48197 4.320842-2.50597 1.347924-.025 2.62102.86899 3.445145.86899s2.371256-1.07499 3.99726-.91699c.680534.027 2.591695.263 3.818276 1.98397-.099097.059-2.280247 1.27499-2.255979 3.80495\"\n fill=\"#000\"\n fillRule=\"evenodd\"\n />\n </svg>\n {label}\n </Button>\n );\n};\n"]}
1
+ {"version":3,"file":"SigninWithAppleButton.js","sourceRoot":"","sources":["../../../src/components/SigninWithAppleButton.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAChD,OAAO,KAAK,MAAM,oCAAoC,CAAC;AACvD,OAAO,EAAE,MAAM,EAAE,MAAM,uCAAuC,CAA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AAC,OAAO,EAAE,CAAC;YACzC,CAAC;QACH,CAAC;gBAAS,CAAC;YACT,aAAa,CAAC,OAAO,GAAG,KAAK,CAAC;YAC9B,UAAU,CAAC,KAAK,CAAC,CAAC;YAClB,eAAe,aAAf,eAAe,uBAAf,eAAe,CAAG,KAAK,CAAC,CAAC;QAC3B,CAAC;QACD,IAAI,MAAM;YAAE,UAAU,CAAC,MAAM,CAAC,CAAC;IACjC,CAAC,CAAC;IAEF,IAAI,CAAC,mBAAmB,EAAE,CAAC;QACzB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,CACL,oBAAC,MAAM,IACL,IAAI,EAAC,QAAQ,EACb,SAAS,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,EACpC,OAAO,EAAC,SAAS,KACb,SAAS,KACT,WAAW,EACf,OAAO,EAAE,eAAe,EACxB,QAAQ,EAAE,OAAO,IAAI,gBAAgB,KAAI,SAAS,aAAT,SAAS,uBAAT,SAAS,CAAE,QAAQ,CAAA;QAE5D,6BAAK,SAAS,EAAE,KAAK,CAAC,IAAI,EAAE,OAAO,EAAC,cAAc;YAC9C,8BACE,CAAC,EAAC,+uBAA+uB,EACjvB,IAAI,EAAC,MAAM,EACX,QAAQ,EAAC,SAAS,GAClB,CACA;QACL,KAAK,CACC,CACV,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import React, { useRef, useState } from 'react';\nimport style from './SigninWithAppleButton.module.css';\nimport { Button } from '@_linked/primitives/components/Button';\nimport { cl } from '@_linked/react/utils/ClassNames';\nimport { useAuth } from '@_linked/auth/hooks/useAuth';\nimport type { AuthenticationResult } from '@_linked/auth/types/auth';\nimport {\n classifySocialLoginError,\n isAppleLoginSupported,\n signinWithApple,\n} from '../auth/SocialLoginClient.js';\n\ninterface SigninWithAppleButtonProps\n extends Omit<React.ComponentProps<typeof Button>, 'onClick' | 'children'> {\n label?: string;\n scopes?: string;\n className?: string;\n onCallback: (data: AuthenticationResult) => void;\n restProps?: any;\n onLoadingChange?: (loading: boolean) => void;\n}\nexport const SigninWithAppleButton = ({\n label = 'Sign in with Apple',\n scopes = 'email name',\n className,\n onCallback,\n onLoadingChange,\n restProps,\n disabled: disabledByCaller = false,\n ...buttonProps\n}: SigninWithAppleButtonProps) => {\n const [loading, setLoading] = useState(false);\n\n const auth = useAuth();\n const loginInFlight = useRef(false);\n const isSupportedPlatform = isAppleLoginSupported();\n\n const signInWithApple = async () => {\n if (loginInFlight.current) return;\n loginInFlight.current = true;\n setLoading(true);\n let result: AuthenticationResult | undefined;\n try {\n onLoadingChange?.(true);\n // the server issues the nonce and redeems it once (@_linked/auth 3)\n result = await signinWithApple(auth, scopes.split(/\\s+/).filter(Boolean));\n } catch (error) {\n const loginError = classifySocialLoginError(error);\n if (loginError.kind !== 'cancelled') {\n result = { error: loginError.message };\n }\n } finally {\n loginInFlight.current = false;\n setLoading(false);\n onLoadingChange?.(false);\n }\n if (result) onCallback(result);\n };\n\n if (!isSupportedPlatform) {\n return null;\n }\n\n return (\n <Button\n type=\"button\"\n className={cl(style.root, className)}\n variant=\"outline\"\n {...restProps}\n {...buttonProps}\n onClick={signInWithApple}\n disabled={loading || disabledByCaller || restProps?.disabled}\n >\n <svg className={style.icon} viewBox=\"-1.5 0 20 20\">\n <path\n d=\"M11.570887 3.19296C12.29996 2.34797 12.791401 1.17098 12.656912 0c-1.050633.04-2.321706.67099-3.075048 1.51498-.67649.74899-1.267029 1.94597-1.10827 3.09396 1.171976.08699 2.36822-.57 3.097293-1.41598m2.6281 7.43189C14.22831 13.65181 16.969663 14.65879 17 14.67179c-.022246.071-.437848 1.43498-1.443988 2.84496-.87064 1.21799-1.773639 2.43097-3.196392 2.45697-1.397473.025-1.847455-.79399-3.446157-.79399-1.59769 0-2.09722.76799-3.419865.81899-1.373205.049-2.419793-1.31798-3.2965-2.53196C.403236 14.98379-.966935 10.44985.873442 7.3899c.914121-1.51898 2.547203-2.48197 4.320842-2.50597 1.347924-.025 2.62102.86899 3.445145.86899s2.371256-1.07499 3.99726-.91699c.680534.027 2.591695.263 3.818276 1.98397-.099097.059-2.280247 1.27499-2.255979 3.80495\"\n fill=\"#000\"\n fillRule=\"evenodd\"\n />\n </svg>\n {label}\n </Button>\n );\n};\n"]}
@@ -9,5 +9,12 @@ interface SigninWithFacebookButtonProps extends Omit<React.ComponentProps<typeof
9
9
  onLoadingChange?: (loading: boolean) => void;
10
10
  restProps?: any;
11
11
  }
12
+ /**
13
+ * Facebook sign-in button.
14
+ *
15
+ * `@_linked/auth` 3 does not verify Facebook tokens yet, so its `signinOAuth` refuses the
16
+ * `facebook` provider: after the prompt, `onCallback` receives
17
+ * `{ error: 'Unsupported OAuth provider' }`. Hide this button until auth accepts Facebook.
18
+ */
12
19
  export declare const SigninWithFacebookButton: ({ label, scopes, className, onCallback, onLoadingChange, restProps, disabled: disabledByCaller, ...buttonProps }: SigninWithFacebookButtonProps) => React.JSX.Element;
13
20
  export {};
@@ -4,6 +4,13 @@ import { Button } from '@_linked/primitives/components/Button';
4
4
  import { cl } from '@_linked/react/utils/ClassNames';
5
5
  import { useAuth } from '@_linked/auth/hooks/useAuth';
6
6
  import { classifySocialLoginError, loginWithFacebook, } from '../auth/SocialLoginClient.js';
7
+ /**
8
+ * Facebook sign-in button.
9
+ *
10
+ * `@_linked/auth` 3 does not verify Facebook tokens yet, so its `signinOAuth` refuses the
11
+ * `facebook` provider: after the prompt, `onCallback` receives
12
+ * `{ error: 'Unsupported OAuth provider' }`. Hide this button until auth accepts Facebook.
13
+ */
7
14
  export const SigninWithFacebookButton = ({ label = 'Sign in with Facebook', scopes = ['email'], className, onCallback, onLoadingChange, restProps, disabled: disabledByCaller = false, ...buttonProps }) => {
8
15
  const [loading, setLoading] = useState(false);
9
16
  const auth = useAuth();
@@ -1 +1 @@
1
- {"version":3,"file":"SigninWithFacebookButton.js","sourceRoot":"","sources":["../../../src/components/SigninWithFacebookButton.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAE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UAAU,CAAC,IAAI,KAAK,WAAW,EAAE,CAAC;gBACpC,MAAM,GAAG,EAAE,KAAK,EAAE,UAAU,CAAC,OAAO,EAAE,CAAC;YACzC,CAAC;QACH,CAAC;gBAAS,CAAC;YACT,aAAa,CAAC,OAAO,GAAG,KAAK,CAAC;YAC9B,UAAU,CAAC,KAAK,CAAC,CAAC;YAClB,eAAe,aAAf,eAAe,uBAAf,eAAe,CAAG,KAAK,CAAC,CAAC;QAC3B,CAAC;QACD,IAAI,MAAM;YAAE,UAAU,CAAC,MAAM,CAAC,CAAC;IACjC,CAAC,CAAC;IAEF,OAAO,CACL,oBAAC,MAAM,IACL,IAAI,EAAC,QAAQ,EACb,SAAS,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,EACpC,OAAO,EAAC,SAAS,KACb,SAAS,KACT,WAAW,EACf,OAAO,EAAE,QAAQ,EACjB,QAAQ,EAAE,OAAO,IAAI,gBAAgB,KAAI,SAAS,aAAT,SAAS,uBAAT,SAAS,CAAE,QAAQ,CAAA;QAE5D,6BAAK,SAAS,EAAE,KAAK,CAAC,IAAI,EAAE,KAAK,EAAC,IAAI,EAAC,MAAM,EAAC,IAAI,EAAC,IAAI,EAAC,MAAM;YAC1D,2BAAG,QAAQ,EAAC,SAAS;gBACnB,8BACE,CAAC,EAAC,qUAAqU,EACvU,IAAI,EAAC,SAAS,GACd;gBACF,8BACE,CAAC,EAAC,2OAA2O,EAC7O,IAAI,EAAC,MAAM,GACX,CACA;YACJ;gBACE,kCAAU,EAAE,EAAC,GAAG;oBACd,8BAAM,IAAI,EAAC,MAAM,EAAC,CAAC,EAAC,eAAe,GAAG,CAC7B,CACN,CACL;QACL,KAAK,CACC,CACV,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import React, { useRef, useState } from 'react';\nimport style from './SigninWithFacebookButton.module.css';\nimport { Button } from '@_linked/primitives/components/Button';\nimport { cl } from '@_linked/react/utils/ClassNames';\nimport { useAuth } from '@_linked/auth/hooks/useAuth';\nimport type { AuthenticationResult } from '@_linked/auth/types/auth';\nimport {\n classifySocialLoginError,\n loginWithFacebook,\n} from '../auth/SocialLoginClient.js';\n\ninterface SigninWithFacebookButtonProps\n extends Omit<React.ComponentProps<typeof Button>, 'onClick' | 'children'> {\n label?: string;\n scopes?: string[];\n className?: string;\n onCallback: (data: AuthenticationResult) => void;\n onLoadingChange?: (loading: boolean) => void;\n restProps?: any;\n}\n\nexport const SigninWithFacebookButton = ({\n label = 'Sign in with Facebook',\n scopes = ['email'],\n className,\n onCallback,\n onLoadingChange,\n restProps,\n disabled: disabledByCaller = false,\n ...buttonProps\n}: SigninWithFacebookButtonProps) => {\n const [loading, setLoading] = useState(false);\n\n const auth = useAuth();\n const loginInFlight = useRef(false);\n\n const onSignin = async () => {\n if (loginInFlight.current) return;\n loginInFlight.current = true;\n setLoading(true);\n let result: AuthenticationResult | undefined;\n try {\n onLoadingChange?.(true);\n const payload = await loginWithFacebook(scopes);\n result = await auth.signinOAuth('facebook', payload);\n } catch (error) {\n const loginError = classifySocialLoginError(error);\n if (loginError.kind !== 'cancelled') {\n result = { error: loginError.message };\n }\n } finally {\n loginInFlight.current = false;\n setLoading(false);\n onLoadingChange?.(false);\n }\n if (result) onCallback(result);\n };\n\n return (\n <Button\n type=\"button\"\n className={cl(style.root, className)}\n variant=\"outline\"\n {...restProps}\n {...buttonProps}\n onClick={onSignin}\n disabled={loading || disabledByCaller || restProps?.disabled}\n >\n <svg className={style.icon} width=\"24\" height=\"24\" fill=\"none\">\n <g clipPath=\"url(#a)\">\n <path\n d=\"M24 12c0-6.62742-5.3726-12-12-12C5.37258 0 0 5.37258 0 12c0 5.9895 4.3882 10.954 10.125 11.8542v-8.3854H7.07812V12H10.125V9.35625c0-3.0075 1.7916-4.66875 4.5326-4.66875 1.3125 0 2.6862.23438 2.6862.23438V7.875h-1.5132c-1.4906 0-1.9556.92508-1.9556 1.875V12h3.3281l-.532 3.4688H13.875v8.3854C19.6118 22.954 24 17.9895 24 12Z\"\n fill=\"#1877F2\"\n />\n <path\n d=\"M16.6711 15.4688 17.2031 12H13.875V9.75c0-.94898.465-1.875 1.9556-1.875h1.5132V4.92188s-1.3733-.23438-2.6862-.23438c-2.741 0-4.5326 1.66125-4.5326 4.66875V12H7.07812v3.4688H10.125v8.3854c1.2424.1944 2.5076.1944 3.75 0v-8.3854h2.7961Z\"\n fill=\"#fff\"\n />\n </g>\n <defs>\n <clipPath id=\"a\">\n <path fill=\"#fff\" d=\"M0 0h24v24H0z\" />\n </clipPath>\n </defs>\n </svg>\n {label}\n </Button>\n );\n};\n"]}
1
+ {"version":3,"file":"SigninWithFacebookButton.js","sourceRoot":"","sources":["../../../src/components/SigninWithFacebookButton.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAChD,OAAO,KAAK,MAAM,uCAAuC,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,uCAAuC,CAAC;AAC/D,OAAO,EAAE,EAAE,EAAE,MAAM,iCAAiC,CAAC;AACrD,OAAO,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC;AAEtD,OAAO,EACL,wBAAwB,EACxB,iBAAiB,GAClB,MAAM,8BAA8B,CAAC;AAYtC;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,EACvC,KAAK,GAAG,uBAAuB,EAC/B,MAAM,GAAG,CAAC,OAAO,CAAC,EAClB,SAAS,EACT,UAAU,EACV,eAAe,EACf,SAAS,EACT,QAAQ,EAAE,gBAAgB,GAAG,KAAK,EAClC,GAAG,WAAW,EACgB,EAAE,EAAE;IAClC,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IAE9C,MAAM,IAAI,GAAG,OAAO,EAAE,CAAC;IACvB,MAAM,aAAa,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IAEpC,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IAAI,EAAC,MAAM,EAAC,IAAI,EAAC,IAAI,EAAC,MAAM;YAC1D,2BAAG,QAAQ,EAAC,SAAS;gBACnB,8BACE,CAAC,EAAC,qUAAqU,EACvU,IAAI,EAAC,SAAS,GACd;gBACF,8BACE,CAAC,EAAC,2OAA2O,EAC7O,IAAI,EAAC,MAAM,GACX,CACA;YACJ;gBACE,kCAAU,EAAE,EAAC,GAAG;oBACd,8BAAM,IAAI,EAAC,MAAM,EAAC,CAAC,EAAC,eAAe,GAAG,CAC7B,CACN,CACL;QACL,KAAK,CACC,CACV,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import React, { useRef, useState } from 'react';\nimport style from './SigninWithFacebookButton.module.css';\nimport { Button } from '@_linked/primitives/components/Button';\nimport { cl } from '@_linked/react/utils/ClassNames';\nimport { useAuth } from '@_linked/auth/hooks/useAuth';\nimport type { AuthenticationResult } from '@_linked/auth/types/auth';\nimport {\n classifySocialLoginError,\n loginWithFacebook,\n} from '../auth/SocialLoginClient.js';\n\ninterface SigninWithFacebookButtonProps\n extends Omit<React.ComponentProps<typeof Button>, 'onClick' | 'children'> {\n label?: string;\n scopes?: string[];\n className?: string;\n onCallback: (data: AuthenticationResult) => void;\n onLoadingChange?: (loading: boolean) => void;\n restProps?: any;\n}\n\n/**\n * Facebook sign-in button.\n *\n * `@_linked/auth` 3 does not verify Facebook tokens yet, so its `signinOAuth` refuses the\n * `facebook` provider: after the prompt, `onCallback` receives\n * `{ error: 'Unsupported OAuth provider' }`. Hide this button until auth accepts Facebook.\n */\nexport const SigninWithFacebookButton = ({\n label = 'Sign in with Facebook',\n scopes = ['email'],\n className,\n onCallback,\n onLoadingChange,\n restProps,\n disabled: disabledByCaller = false,\n ...buttonProps\n}: SigninWithFacebookButtonProps) => {\n const [loading, setLoading] = useState(false);\n\n const auth = useAuth();\n const loginInFlight = useRef(false);\n\n const onSignin = async () => {\n if (loginInFlight.current) return;\n loginInFlight.current = true;\n setLoading(true);\n let result: AuthenticationResult | undefined;\n try {\n onLoadingChange?.(true);\n const payload = await loginWithFacebook(scopes);\n result = await auth.signinOAuth('facebook', payload);\n } catch (error) {\n const loginError = classifySocialLoginError(error);\n if (loginError.kind !== 'cancelled') {\n result = { error: loginError.message };\n }\n } finally {\n loginInFlight.current = false;\n setLoading(false);\n onLoadingChange?.(false);\n }\n if (result) onCallback(result);\n };\n\n return (\n <Button\n type=\"button\"\n className={cl(style.root, className)}\n variant=\"outline\"\n {...restProps}\n {...buttonProps}\n onClick={onSignin}\n disabled={loading || disabledByCaller || restProps?.disabled}\n >\n <svg className={style.icon} width=\"24\" height=\"24\" fill=\"none\">\n <g clipPath=\"url(#a)\">\n <path\n d=\"M24 12c0-6.62742-5.3726-12-12-12C5.37258 0 0 5.37258 0 12c0 5.9895 4.3882 10.954 10.125 11.8542v-8.3854H7.07812V12H10.125V9.35625c0-3.0075 1.7916-4.66875 4.5326-4.66875 1.3125 0 2.6862.23438 2.6862.23438V7.875h-1.5132c-1.4906 0-1.9556.92508-1.9556 1.875V12h3.3281l-.532 3.4688H13.875v8.3854C19.6118 22.954 24 17.9895 24 12Z\"\n fill=\"#1877F2\"\n />\n <path\n d=\"M16.6711 15.4688 17.2031 12H13.875V9.75c0-.94898.465-1.875 1.9556-1.875h1.5132V4.92188s-1.3733-.23438-2.6862-.23438c-2.741 0-4.5326 1.66125-4.5326 4.66875V12H7.07812v3.4688H10.125v8.3854c1.2424.1944 2.5076.1944 3.75 0v-8.3854h2.7961Z\"\n fill=\"#fff\"\n />\n </g>\n <defs>\n <clipPath id=\"a\">\n <path fill=\"#fff\" d=\"M0 0h24v24H0z\" />\n </clipPath>\n </defs>\n </svg>\n {label}\n </Button>\n );\n};\n"]}
package/package.json CHANGED
@@ -10,7 +10,7 @@
10
10
  "type": "git",
11
11
  "url": "git+ssh://git@github.com/linked-cm/capacitor.git"
12
12
  },
13
- "version": "0.2.0",
13
+ "version": "0.3.0",
14
14
  "linkedPackage": true,
15
15
  "type": "module",
16
16
  "main": "lib/esm/index.js",
@@ -53,12 +53,12 @@
53
53
  }
54
54
  },
55
55
  "dependencies": {
56
- "@_linked/auth": "^1.2.3",
56
+ "@_linked/auth": "^3.1.0",
57
57
  "@_linked/core": "^2.27.0",
58
58
  "@_linked/primitives": "^1.8.0",
59
59
  "@_linked/react": "^2.0.0",
60
60
  "@_linked/schema": "^1.5.0",
61
- "@_linked/server-utils": "~1.0",
61
+ "@_linked/server-utils": "^1.12.0",
62
62
  "@_linked/sioc": "^1.4.0",
63
63
  "google-libphonenumber": "3.2.33",
64
64
  "react-international-phone": "4.0.4",
package/readme.md CHANGED
@@ -35,6 +35,14 @@ import { SigninWithGoogleButton } from '@linked.cm/capacitor/components/SigninWi
35
35
 
36
36
  Google web login needs `GOOGLE_CLIENT_ID` and `SITE_ROOT` (the callback is `{SITE_ROOT}/signin`). Apple on the web needs `APPLE_SIGN_IN_CLIENT_ID` and `APPLE_SIGN_IN_REDIRECT_URI`. Facebook needs `FACEBOOK_CLIENT_ID`.
37
37
 
38
+ Sign-in is verified by `@_linked/auth` 3:
39
+
40
+ - **Apple**: the button asks the server for a single-use nonce (`createOAuthNonce`) and requests the identity token with it; `signinWithApple(auth, scopes)` does the same outside the button. The server needs `APPLE_CLIENT_ID` (web, the Services ID) and/or `APPLE_CLIENT_ID_IOS` (the app's bundle ID), or it rejects every Apple sign-in. Calling `loginWithApple` yourself with a nonce the server did not issue gets the sign-in rejected.
41
+ - **Google**: the server needs `GOOGLE_CLIENT_ID` (and `GOOGLE_CLIENT_ID_IOS` for iOS).
42
+ - **Facebook**: auth 3 does not verify Facebook tokens yet and answers `{ error: 'Unsupported OAuth provider' }`. Hide the Facebook button until it does.
43
+ - When the provider's email belongs to an existing account that signed in another way, `onCallback` gets `{ error, action: 'sign_in_to_link' }`. Sign the user in the way they did before, then call `useAuth().linkOAuthIdentity`.
44
+ - An app with an RPC exposure list must expose auth's `createOAuthNonce: 'public'` for Apple sign-in, and `linkOAuthIdentity: 'user'` to link a provider.
45
+
38
46
  WhatsApp sign-in asks the backend to send a code, then validates it. The server reads:
39
47
 
40
48
  - `WA_D360_API_KEY`
@@ -6,6 +6,7 @@ import {
6
6
  createAppleNonce,
7
7
  classifySocialLoginError,
8
8
  resolveGoogleRedirectUri,
9
+ signinWithApple,
9
10
  } from '../lib/esm/auth/SocialLoginClient.js';
10
11
 
11
12
  test('resolves the Google web callback from SITE_ROOT', () => {
@@ -97,3 +98,56 @@ for (const provider of ['Apple', 'Google', 'Facebook']) {
97
98
  );
98
99
  });
99
100
  }
101
+
102
+ test('signs in with Apple using the nonce the server issued', async () => {
103
+ const calls = [];
104
+ const auth = {
105
+ createOAuthNonce: async () => {
106
+ calls.push('createOAuthNonce');
107
+ return { nonce: 'server.nonce.hmac', expiresAt: '2030-01-01T00:00:00Z' };
108
+ },
109
+ signinOAuth: async (provider, payload) => {
110
+ calls.push(['signinOAuth', provider, payload]);
111
+ return { auth: {}, accessToken: 'a' };
112
+ },
113
+ };
114
+ const login = async (scopes, nonce) => {
115
+ calls.push(['login', scopes, nonce]);
116
+ return { identityToken: 'token', nonce };
117
+ };
118
+
119
+ const result = await signinWithApple(auth, ['email'], login);
120
+
121
+ assert.deepEqual(result, { auth: {}, accessToken: 'a' });
122
+ assert.deepEqual(calls, [
123
+ 'createOAuthNonce',
124
+ ['login', ['email'], 'server.nonce.hmac'],
125
+ ['signinOAuth', 'apple', { identityToken: 'token', nonce: 'server.nonce.hmac' }],
126
+ ]);
127
+ });
128
+
129
+ test('Apple sign-in never sends a nonce generated on the device', async () => {
130
+ const source = await readFile(
131
+ new URL('../lib/esm/auth/SocialLoginClient.js', import.meta.url),
132
+ 'utf8'
133
+ );
134
+ const loginWithApple = source.slice(
135
+ source.indexOf('export async function loginWithApple'),
136
+ source.indexOf('export async function signinWithApple')
137
+ );
138
+ assert.doesNotMatch(loginWithApple, /createAppleNonce\(/);
139
+ const button = await readFile(
140
+ new URL('../lib/esm/components/SigninWithAppleButton.js', import.meta.url),
141
+ 'utf8'
142
+ );
143
+ assert.match(button, /signinWithApple\(auth,/);
144
+ });
145
+
146
+ test('WhatsApp sign-in passes the refresh token expiry to updateAuth', async () => {
147
+ const source = await readFile(
148
+ new URL('../lib/esm/components/SignInWithWhatsapp.js', import.meta.url),
149
+ 'utf8'
150
+ );
151
+ assert.match(source, /refreshTokenExpiresIn:\s*response\.refreshTokenExpiresIn/);
152
+ assert.match(source, /refreshTokenExpiresAt:\s*response\.refreshTokenExpiresAt/);
153
+ });