@linked.cm/capacitor 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # @linked.cm/capacitor
2
2
 
3
+ ## 0.3.1
4
+
5
+ ### Patch Changes
6
+
7
+ - [#11](https://github.com/linked-cm/capacitor/pull/11) [`641906a`](https://github.com/linked-cm/capacitor/commit/641906a016d5d488096fcc8a3f3bb2c744b22d8e) Thanks [@carlenmy](https://github.com/carlenmy)! - Label the WhatsApp verification code input and keep its six numeric slots usable on narrow screens.
8
+
9
+ ## 0.3.0
10
+
11
+ ### Minor Changes
12
+
13
+ - [#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.
14
+
15
+ 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.
16
+
17
+ **Before deploying, the app must be ready for auth 3.** See auth's changelog for 2.0.0 and 3.0.0:
18
+
19
+ - **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.
20
+ - 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.
21
+ - Apple sign-in needs `APPLE_CLIENT_ID` and/or `APPLE_CLIENT_ID_IOS` on the server, or every Apple sign-in is rejected.
22
+
23
+ Changes in this package for auth 3:
24
+
25
+ - **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'`.
26
+ - **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.
27
+ - 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`.
28
+ - WhatsApp sign-in passes `refreshTokenExpiresIn`/`refreshTokenExpiresAt` to `updateAuth`, so native storage keeps the refresh token for as long as the server does.
29
+ - 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.
30
+
3
31
  ## 0.2.0
4
32
 
5
33
  ### 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,kBAAk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\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;AA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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 /** 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"]}
@@ -10,11 +10,10 @@ export default class CapacitorBackendProvider extends BackendProvider {
10
10
  dispose(): void;
11
11
  validateOTPWhatsapp(phoneIdentifier: any, OPT_Input: any): Promise<import("@_linked/auth/types/auth").AuthenticationResult>;
12
12
  generateOTPWhatsapp(phoneNumber: any): Promise<{
13
- data: any;
13
+ sent: boolean;
14
14
  }>;
15
- getBearerToken(): Promise<any>;
16
15
  generateOTP(): number;
17
- sendMessage(url: any, bearerToken: any, apiKey: any, otp: any, phoneNumber: any): Promise<Response>;
16
+ sendMessage(url: any, apiKey: any, otp: any, phoneNumber: any): Promise<Response>;
18
17
  getUserLocationAction(user: UserData): Promise<{
19
18
  agent: {
20
19
  id: string;
@@ -149,71 +149,54 @@ export default class CapacitorBackendProvider extends BackendProvider {
149
149
  }
150
150
  }
151
151
  async generateOTPWhatsapp(phoneNumber) {
152
+ var _a, _b;
152
153
  const session = this.request.session;
153
154
  const baseUrl = 'https://waba-v2.360dialog.io';
154
- const bearerToken = this.getBearerToken();
155
155
  const API_KEY = process.env.WA_D360_API_KEY;
156
- const otp = this.generateOTP();
157
- const message = `Your OTP for Whatsapp Auth is ${otp}`;
158
- console.log('OTP', message);
159
- // Save the OTP
160
- session.otp = otp;
161
- const url = `${baseUrl}/messages`;
162
- try {
163
- const response = await this.sendMessage(url, bearerToken, API_KEY, otp, phoneNumber);
164
- const data = await response.json();
165
- return { data };
156
+ const recipient = normalizeTelephone(phoneNumber).replace(/^\+/, '');
157
+ if (!/^\d{8,15}$/.test(recipient)) {
158
+ throw new Error('A valid WhatsApp phone number is required');
166
159
  }
167
- catch (error) {
168
- console.error('Error sending message:', error.message);
169
- throw error; // Propagate the error for handling at a higher level
170
- }
171
- }
172
- async getBearerToken() {
173
- const username = process.env.WA_D360_USERNAME;
174
- const password = process.env.WA_D360_PASSWORD;
175
- if (!username || !password) {
176
- throw new Error('WA_D360_USERNAME and WA_D360_PASSWORD are required to request a WhatsApp token');
160
+ if (!API_KEY) {
161
+ throw new Error('WA_D360_API_KEY is required to send a WhatsApp code');
177
162
  }
178
- const url = 'https://hub.360dialog.io/api/v2/token';
163
+ const otp = this.generateOTP();
164
+ const url = `${baseUrl}/messages`;
179
165
  try {
180
- const response = await fetch(url, {
181
- method: 'POST',
182
- headers: {
183
- 'Content-Type': 'application/json',
184
- },
185
- body: JSON.stringify({
186
- username,
187
- password,
188
- }),
189
- });
166
+ const response = await this.sendMessage(url, API_KEY, otp, recipient);
167
+ if (!response.ok) {
168
+ console.error('WhatsApp code request rejected by provider:', response.status);
169
+ throw new Error('Could not send the code. Please try again.');
170
+ }
190
171
  const data = await response.json();
191
- return data.access_token;
172
+ if (!((_b = (_a = data === null || data === void 0 ? void 0 : data.messages) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.id)) {
173
+ throw new Error('WhatsApp provider did not confirm the code request');
174
+ }
175
+ // Only make a code usable after the provider accepts the message.
176
+ session.otp = otp;
177
+ return { sent: true };
192
178
  }
193
179
  catch (error) {
194
- console.error('Error getting access token:', error.message);
195
- throw error; // Propagate the error for handling at a higher level
180
+ console.error('WhatsApp code send failed:', error.message);
181
+ throw new Error('Could not send the code. Please try again.');
196
182
  }
197
183
  }
198
184
  generateOTP() {
199
185
  return Math.floor(100000 + Math.random() * 900000);
200
186
  }
201
- async sendMessage(url, bearerToken, apiKey, otp, phoneNumber) {
202
- const templateNamespace = process.env.WA_D360_TEMPLATE_NAMESPACE;
187
+ async sendMessage(url, apiKey, otp, phoneNumber) {
203
188
  const templateName = process.env.WA_D360_TEMPLATE_NAME;
204
- if (!templateNamespace || !templateName) {
205
- throw new Error('WA_D360_TEMPLATE_NAMESPACE and WA_D360_TEMPLATE_NAME are required to send a WhatsApp code');
189
+ if (!templateName) {
190
+ throw new Error('WA_D360_TEMPLATE_NAME is required to send a WhatsApp code');
206
191
  }
207
192
  const payload = {
208
193
  messaging_product: 'whatsapp',
209
194
  to: phoneNumber,
210
195
  type: 'template',
211
196
  template: {
212
- namespace: templateNamespace,
213
197
  name: templateName,
214
198
  language: {
215
- code: 'en',
216
- policy: 'deterministic',
199
+ code: process.env.WA_D360_TEMPLATE_LANGUAGE || 'en',
217
200
  },
218
201
  components: [
219
202
  {
@@ -243,7 +226,6 @@ export default class CapacitorBackendProvider extends BackendProvider {
243
226
  method: 'POST',
244
227
  headers: {
245
228
  'Content-Type': 'application/json',
246
- Authorization: `bearer ${bearerToken}`,
247
229
  'D360-API-KEY': apiKey,
248
230
  },
249
231
  body: JSON.stringify(payload),
@@ -1 +1 @@
1
- {"version":3,"file":"backend.js","sourceRoot":"","sources":["../../src/backend.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,MAAM,6CAA6C,CAAC;AAC9E,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AAC/E,OAAO,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;AAChD,OAAO,EACL,uBAAuB,EACvB,sBAAsB,GACvB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAC;AAC/D,OAAO,EAAE,cAAc,EAAE,MAAM,qCAAqC,CAAC;AACrE,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAE7D,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAEvD,MAAM,CAAC,OAAO,OAAO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IAAI,CAAC,CAAC;QAE9D,8EAA8E;QAC9E,IAAI,CAAC,cAAc,EAAE,CAAC;YACpB,MAAM,QAAQ,GAAG,MAAM,kBAAkB,CAAC,MAAM,CAAC;gBAC/C,QAAQ,EAAE,QAAQ,CAAC,QAAQ,EAAE;gBAC7B,SAAS,EAAE,SAAS,CAAC,QAAQ,EAAE;aAChC,CAAC,CAAC;YAEH,MAAM,iBAAiB,GAAG,MAAM,oBAAoB,CAAC,MAAM,CAAC;gBAC1D,QAAQ,EAAE;oBACR,EAAE,EAAE,QAAQ,CAAC,EAAE;iBAChB;gBACD,KAAK,EAAE;oBACL,EAAE,EAAE,IAAI,CAAC,EAAE;iBACZ;aACF,CAAC,CAAC;YACH,OAAO,iBAAiB,CAAC;QAC3B,CAAC;aAAM,CAAC;YACN,yCAAyC;YACzC,MAAM,sBAAsB,GAAG,MAAO,oBAA4B,CAAC,MAAM,CACvE,cAAc,EACd;gBACE,QAAQ,EAAE;oBACR,QAAQ,EAAE,QAAQ,CAAC,QAAQ,EAAE;oBAC7B,SAAS,EAAE,SAAS,CAAC,QAAQ,EAAE;iBAChC;aACF,CACF,CAAC;YACF,OAAO,sBAAsB,CAAC;QAChC,CAAC;IACH,CAAC;CACF","sourcesContent":["import { Person as SchemaPerson } from '@_linked/schema/shapes/Person';\nimport { BackendProvider } from '@_linked/server-utils/utils/BackendProvider';\nimport { LocationUpdateAction } from './shapes/LocationUpdateAction.js';\nimport { AdministrativeArea } from '@_linked/schema/shapes/AdministrativeArea';\nimport { Auth } from '@_linked/auth/utils/auth';\nimport {\n offAccountWillBeRemoved,\n onAccountWillBeRemoved,\n} from '@_linked/auth/utils/events';\nimport { UserAccount } from '@_linked/sioc/shapes/UserAccount';\nimport { AuthCredential } from '@_linked/auth/shapes/AuthCredential';\nimport { telephoneToWebID } from '@_linked/auth/utils/webID';\nimport type { UserAccountData, UserData } from '@_linked/auth/types/auth';\nimport { normalizeTelephone } from './utils/helper.js';\n\nexport default class CapacitorBackendProvider extends BackendProvider {\n public accountShape: typeof UserAccount = UserAccount;\n public userShape: typeof SchemaPerson = SchemaPerson;\n private readonly onAccountRemoved = async (account: UserAccountData) => {\n const person = account.accountOf;\n\n if (person) {\n // The location action is optional. Delete by its relation so accounts\n // without location history do not pass `null` into an ID-based delete.\n await LocationUpdateAction.deleteWhere((action) =>\n action.agent.equals(person)\n );\n }\n };\n\n async setupBeforeControllers() {\n //if defined, take the values from the environment variables to define the shapes for the account and user\n await this.assignEnvPathToField('AUTH_ACCOUNT_TYPE', 'accountShape');\n await this.assignEnvPathToField('AUTH_USER_TYPE', 'userShape');\n\n onAccountWillBeRemoved(this.onAccountRemoved);\n }\n\n dispose() {\n offAccountWillBeRemoved(this.onAccountRemoved);\n }\n\n async validateOTPWhatsapp(phoneIdentifier, OPT_Input) {\n try {\n if (!phoneIdentifier) {\n console.log('No phone number provided');\n return { error: 'No phone number provided' };\n }\n\n const normalizedPhone = normalizeTelephone(phoneIdentifier);\n const legacyPhone = String(phoneIdentifier || '').trim();\n if (!normalizedPhone) {\n console.log('No valid phone number provided');\n return { error: 'No phone number provided' };\n }\n\n if (!OPT_Input) {\n console.log('No OTP code provided');\n return { error: 'No OTP code provided' };\n }\n\n if (this.request.session.otp.toString() !== OPT_Input) {\n console.log('OTP code is incorrect');\n return { error: 'OTP code is incorrect' };\n }\n\n return await Auth.login(\n this,\n async () => {\n const telephoneWebId = telephoneToWebID(normalizedPhone);\n\n // first, try to find account by telephone-based webID (for new users)\n let account = await UserAccount.select((ua) => [\n ua.email,\n ua.accountOf.select((p) => [\n p.givenName,\n p.familyName,\n p.telephone,\n ]),\n ])\n .where((ua) => {\n return ua.accountOf.equals({\n id: telephoneWebId,\n });\n })\n .one();\n\n if (account && account.accountOf) {\n console.log(\n `Found account by telephone-based webID for phone number ${phoneIdentifier}`\n );\n return {\n account,\n person: account.accountOf,\n };\n }\n\n // if not found, try to find by telephone property (for old users with normal ID)\n console.log(\n `Account not found by webID, searching by telephone property for ${normalizedPhone}`\n );\n account = await UserAccount.select((ua) => [\n ua.email,\n ua.accountOf.select((p) => [\n p.givenName,\n p.familyName,\n p.telephone,\n ]),\n ])\n .where((ua) => {\n // Try normalized phone first, but also support legacy stored strings.\n return ua.accountOf.telephone\n .equals(normalizedPhone)\n .or(ua.accountOf.telephone.equals(legacyPhone));\n })\n .one();\n\n if (account && account.accountOf) {\n console.log(\n `Found account by telephone property for phone number ${phoneIdentifier}`\n );\n return {\n account,\n person: account.accountOf,\n };\n }\n\n console.warn(\n `Could not find any account for phone number ${normalizedPhone} (tried webID: ${telephoneWebId} and telephone property)`\n );\n return null;\n },\n async () => {\n const telephoneWebId = telephoneToWebID(normalizedPhone);\n\n // create a new user by telephone webID\n const user = await (this.userShape as any).create({\n __id: telephoneWebId,\n givenName: '',\n familyName: '',\n telephone: normalizedPhone,\n });\n\n if (!user) {\n console.error(\n 'Error creating user by telephone webID: ' + telephoneWebId\n );\n return null;\n }\n\n // create a new credential for the user\n const newCredential = await AuthCredential.create({\n credentialOf: {\n id: user.id,\n },\n telephone: normalizedPhone,\n });\n\n if (!newCredential) {\n console.error(\n 'Error creating credential by telephone webID: ' + telephoneWebId\n );\n return null;\n }\n\n const account = await (this.accountShape as any).create({\n email: '',\n accountOf: user,\n });\n\n if (!account) {\n console.warn(\n 'Creating new account by telephone webID: ' +\n telephoneWebId +\n ' failed'\n );\n return null;\n }\n\n return {\n account: account,\n person: user,\n };\n },\n 'Whatsapp. Phonenumber: ' + phoneIdentifier\n );\n } catch (err) {\n console.error('validateOTPWhatsapp failed:', err);\n return {\n error: 'Sign-in failed. Please try again.',\n };\n }\n }\n\n async generateOTPWhatsapp(phoneNumber) {\n const session = this.request.session;\n const baseUrl = 'https://waba-v2.360dialog.io';\n const bearerToken = this.getBearerToken();\n const API_KEY = process.env.WA_D360_API_KEY;\n\n const otp = this.generateOTP();\n const message = `Your OTP for Whatsapp Auth is ${otp}`;\n console.log('OTP', message);\n\n // Save the OTP\n session.otp = otp;\n\n const url = `${baseUrl}/messages`;\n\n try {\n const response = await this.sendMessage(\n url,\n bearerToken,\n API_KEY,\n otp,\n phoneNumber\n );\n const data = await response.json();\n return { data };\n } catch (error) {\n console.error('Error sending message:', error.message);\n throw error; // Propagate the error for handling at a higher level\n }\n }\n\n async getBearerToken() {\n const username = process.env.WA_D360_USERNAME;\n const password = process.env.WA_D360_PASSWORD;\n if (!username || !password) {\n throw new Error(\n 'WA_D360_USERNAME and WA_D360_PASSWORD are required to request a WhatsApp token'\n );\n }\n const url = 'https://hub.360dialog.io/api/v2/token';\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n username,\n password,\n }),\n });\n const data = await response.json();\n return data.access_token;\n } catch (error) {\n console.error('Error getting access token:', error.message);\n throw error; // Propagate the error for handling at a higher level\n }\n }\n\n generateOTP() {\n return Math.floor(100000 + Math.random() * 900000);\n }\n\n async sendMessage(url, bearerToken, apiKey, otp, phoneNumber) {\n const templateNamespace = process.env.WA_D360_TEMPLATE_NAMESPACE;\n const templateName = process.env.WA_D360_TEMPLATE_NAME;\n if (!templateNamespace || !templateName) {\n throw new Error(\n 'WA_D360_TEMPLATE_NAMESPACE and WA_D360_TEMPLATE_NAME are required to send a WhatsApp code'\n );\n }\n const payload = {\n messaging_product: 'whatsapp',\n to: phoneNumber,\n type: 'template',\n template: {\n namespace: templateNamespace,\n name: templateName,\n language: {\n code: 'en',\n policy: 'deterministic',\n },\n components: [\n {\n type: 'body',\n parameters: [\n {\n type: 'text',\n text: otp,\n },\n ],\n },\n {\n type: 'button',\n sub_type: 'url',\n index: 0,\n parameters: [\n {\n type: 'text',\n text: otp.toString(),\n },\n ],\n },\n ],\n },\n };\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `bearer ${bearerToken}`,\n 'D360-API-KEY': apiKey,\n },\n body: JSON.stringify(payload),\n });\n\n return response;\n }\n\n async getUserLocationAction(user: UserData) {\n const locationAction = await LocationUpdateAction.select((la) => {\n return [la.agent];\n })\n .where((la) => {\n return la.agent.equals({\n id: user.id,\n });\n })\n .one();\n\n return locationAction;\n }\n\n async updateUserLocation(latitude: number, longitude: number) {\n const auth = this.request.linkedAuth;\n if (!auth || !auth.userAccount) {\n console.warn('No user authenticated.');\n return Auth.enforceSignedIn();\n }\n const user = auth.user;\n\n // find existing instance for the login person\n const locationAction = await this.getUserLocationAction(user);\n\n // if not found, create one and set person property and location, then .save()\n if (!locationAction) {\n const newPlace = await AdministrativeArea.create({\n latitude: latitude.toString(),\n longitude: longitude.toString(),\n });\n\n const newLocationAction = await LocationUpdateAction.create({\n location: {\n id: newPlace.id,\n },\n agent: {\n id: user.id,\n },\n });\n return newLocationAction;\n } else {\n // if existing one found, update location\n const existingLocationAction = await (LocationUpdateAction as any).update(\n locationAction,\n {\n location: {\n latitude: latitude.toString(),\n longitude: longitude.toString(),\n },\n }\n );\n return existingLocationAction;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"backend.js","sourceRoot":"","sources":["../../src/backend.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,MAAM,6CAA6C,CAAC;AAC9E,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AAC/E,OAAO,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;AAChD,OAAO,EACL,uBAAuB,EACvB,sBAAsB,GACvB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAC;AAC/D,OAAO,EAAE,cAAc,EAAE,MAAM,qCAAqC,CAAC;AACrE,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAE7D,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAEvD,MAAM,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EAAE,IAAI,CAAC,EAAE;iBACZ;aACF,CAAC,CAAC;YACH,OAAO,iBAAiB,CAAC;QAC3B,CAAC;aAAM,CAAC;YACN,yCAAyC;YACzC,MAAM,sBAAsB,GAAG,MAAO,oBAA4B,CAAC,MAAM,CACvE,cAAc,EACd;gBACE,QAAQ,EAAE;oBACR,QAAQ,EAAE,QAAQ,CAAC,QAAQ,EAAE;oBAC7B,SAAS,EAAE,SAAS,CAAC,QAAQ,EAAE;iBAChC;aACF,CACF,CAAC;YACF,OAAO,sBAAsB,CAAC;QAChC,CAAC;IACH,CAAC;CACF","sourcesContent":["import { Person as SchemaPerson } from '@_linked/schema/shapes/Person';\nimport { BackendProvider } from '@_linked/server-utils/utils/BackendProvider';\nimport { LocationUpdateAction } from './shapes/LocationUpdateAction.js';\nimport { AdministrativeArea } from '@_linked/schema/shapes/AdministrativeArea';\nimport { Auth } from '@_linked/auth/utils/auth';\nimport {\n offAccountWillBeRemoved,\n onAccountWillBeRemoved,\n} from '@_linked/auth/utils/events';\nimport { UserAccount } from '@_linked/sioc/shapes/UserAccount';\nimport { AuthCredential } from '@_linked/auth/shapes/AuthCredential';\nimport { telephoneToWebID } from '@_linked/auth/utils/webID';\nimport type { UserAccountData, UserData } from '@_linked/auth/types/auth';\nimport { normalizeTelephone } from './utils/helper.js';\n\nexport default class CapacitorBackendProvider extends BackendProvider {\n public accountShape: typeof UserAccount = UserAccount;\n public userShape: typeof SchemaPerson = SchemaPerson;\n private readonly onAccountRemoved = async (account: UserAccountData) => {\n const person = account.accountOf;\n\n if (person) {\n // The location action is optional. Delete by its relation so accounts\n // without location history do not pass `null` into an ID-based delete.\n await LocationUpdateAction.deleteWhere((action) =>\n action.agent.equals(person)\n );\n }\n };\n\n async setupBeforeControllers() {\n //if defined, take the values from the environment variables to define the shapes for the account and user\n await this.assignEnvPathToField('AUTH_ACCOUNT_TYPE', 'accountShape');\n await this.assignEnvPathToField('AUTH_USER_TYPE', 'userShape');\n\n onAccountWillBeRemoved(this.onAccountRemoved);\n }\n\n dispose() {\n offAccountWillBeRemoved(this.onAccountRemoved);\n }\n\n async validateOTPWhatsapp(phoneIdentifier, OPT_Input) {\n try {\n if (!phoneIdentifier) {\n console.log('No phone number provided');\n return { error: 'No phone number provided' };\n }\n\n const normalizedPhone = normalizeTelephone(phoneIdentifier);\n const legacyPhone = String(phoneIdentifier || '').trim();\n if (!normalizedPhone) {\n console.log('No valid phone number provided');\n return { error: 'No phone number provided' };\n }\n\n if (!OPT_Input) {\n console.log('No OTP code provided');\n return { error: 'No OTP code provided' };\n }\n\n if (this.request.session.otp.toString() !== OPT_Input) {\n console.log('OTP code is incorrect');\n return { error: 'OTP code is incorrect' };\n }\n\n return await Auth.login(\n this,\n async () => {\n const telephoneWebId = telephoneToWebID(normalizedPhone);\n\n // first, try to find account by telephone-based webID (for new users)\n let account = await UserAccount.select((ua) => [\n ua.email,\n ua.accountOf.select((p) => [\n p.givenName,\n p.familyName,\n p.telephone,\n ]),\n ])\n .where((ua) => {\n return ua.accountOf.equals({\n id: telephoneWebId,\n });\n })\n .one();\n\n if (account && account.accountOf) {\n console.log(\n `Found account by telephone-based webID for phone number ${phoneIdentifier}`\n );\n return {\n account,\n person: account.accountOf,\n };\n }\n\n // if not found, try to find by telephone property (for old users with normal ID)\n console.log(\n `Account not found by webID, searching by telephone property for ${normalizedPhone}`\n );\n account = await UserAccount.select((ua) => [\n ua.email,\n ua.accountOf.select((p) => [\n p.givenName,\n p.familyName,\n p.telephone,\n ]),\n ])\n .where((ua) => {\n // Try normalized phone first, but also support legacy stored strings.\n return ua.accountOf.telephone\n .equals(normalizedPhone)\n .or(ua.accountOf.telephone.equals(legacyPhone));\n })\n .one();\n\n if (account && account.accountOf) {\n console.log(\n `Found account by telephone property for phone number ${phoneIdentifier}`\n );\n return {\n account,\n person: account.accountOf,\n };\n }\n\n console.warn(\n `Could not find any account for phone number ${normalizedPhone} (tried webID: ${telephoneWebId} and telephone property)`\n );\n return null;\n },\n async () => {\n const telephoneWebId = telephoneToWebID(normalizedPhone);\n\n // create a new user by telephone webID\n const user = await (this.userShape as any).create({\n __id: telephoneWebId,\n givenName: '',\n familyName: '',\n telephone: normalizedPhone,\n });\n\n if (!user) {\n console.error(\n 'Error creating user by telephone webID: ' + telephoneWebId\n );\n return null;\n }\n\n // create a new credential for the user\n const newCredential = await AuthCredential.create({\n credentialOf: {\n id: user.id,\n },\n telephone: normalizedPhone,\n });\n\n if (!newCredential) {\n console.error(\n 'Error creating credential by telephone webID: ' + telephoneWebId\n );\n return null;\n }\n\n const account = await (this.accountShape as any).create({\n email: '',\n accountOf: user,\n });\n\n if (!account) {\n console.warn(\n 'Creating new account by telephone webID: ' +\n telephoneWebId +\n ' failed'\n );\n return null;\n }\n\n return {\n account: account,\n person: user,\n };\n },\n 'Whatsapp. Phonenumber: ' + phoneIdentifier\n );\n } catch (err) {\n console.error('validateOTPWhatsapp failed:', err);\n return {\n error: 'Sign-in failed. Please try again.',\n };\n }\n }\n\n async generateOTPWhatsapp(phoneNumber) {\n const session = this.request.session;\n const baseUrl = 'https://waba-v2.360dialog.io';\n const API_KEY = process.env.WA_D360_API_KEY;\n const recipient = normalizeTelephone(phoneNumber).replace(/^\\+/, '');\n if (!/^\\d{8,15}$/.test(recipient)) {\n throw new Error('A valid WhatsApp phone number is required');\n }\n if (!API_KEY) {\n throw new Error('WA_D360_API_KEY is required to send a WhatsApp code');\n }\n\n const otp = this.generateOTP();\n const url = `${baseUrl}/messages`;\n\n try {\n const response = await this.sendMessage(url, API_KEY, otp, recipient);\n if (!response.ok) {\n console.error('WhatsApp code request rejected by provider:', response.status);\n throw new Error('Could not send the code. Please try again.');\n }\n const data = await response.json();\n if (!data?.messages?.[0]?.id) {\n throw new Error('WhatsApp provider did not confirm the code request');\n }\n // Only make a code usable after the provider accepts the message.\n session.otp = otp;\n return { sent: true };\n } catch (error) {\n console.error('WhatsApp code send failed:', error.message);\n throw new Error('Could not send the code. Please try again.');\n }\n }\n\n generateOTP() {\n return Math.floor(100000 + Math.random() * 900000);\n }\n\n async sendMessage(url, apiKey, otp, phoneNumber) {\n const templateName = process.env.WA_D360_TEMPLATE_NAME;\n if (!templateName) {\n throw new Error('WA_D360_TEMPLATE_NAME is required to send a WhatsApp code');\n }\n const payload = {\n messaging_product: 'whatsapp',\n to: phoneNumber,\n type: 'template',\n template: {\n name: templateName,\n language: {\n code: process.env.WA_D360_TEMPLATE_LANGUAGE || 'en',\n },\n components: [\n {\n type: 'body',\n parameters: [\n {\n type: 'text',\n text: otp,\n },\n ],\n },\n {\n type: 'button',\n sub_type: 'url',\n index: 0,\n parameters: [\n {\n type: 'text',\n text: otp.toString(),\n },\n ],\n },\n ],\n },\n };\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'D360-API-KEY': apiKey,\n },\n body: JSON.stringify(payload),\n });\n\n return response;\n }\n\n async getUserLocationAction(user: UserData) {\n const locationAction = await LocationUpdateAction.select((la) => {\n return [la.agent];\n })\n .where((la) => {\n return la.agent.equals({\n id: user.id,\n });\n })\n .one();\n\n return locationAction;\n }\n\n async updateUserLocation(latitude: number, longitude: number) {\n const auth = this.request.linkedAuth;\n if (!auth || !auth.userAccount) {\n console.warn('No user authenticated.');\n return Auth.enforceSignedIn();\n }\n const user = auth.user;\n\n // find existing instance for the login person\n const locationAction = await this.getUserLocationAction(user);\n\n // if not found, create one and set person property and location, then .save()\n if (!locationAction) {\n const newPlace = await AdministrativeArea.create({\n latitude: latitude.toString(),\n longitude: longitude.toString(),\n });\n\n const newLocationAction = await LocationUpdateAction.create({\n location: {\n id: newPlace.id,\n },\n agent: {\n id: user.id,\n },\n });\n return newLocationAction;\n } else {\n // if existing one found, update location\n const existingLocationAction = await (LocationUpdateAction as any).update(\n locationAction,\n {\n location: {\n latitude: latitude.toString(),\n longitude: longitude.toString(),\n },\n }\n );\n return existingLocationAction;\n }\n }\n}\n"]}
@@ -27,19 +27,26 @@ export const SigninWithWhatsappButton = ({ label = 'Sign in with Whatsapp', clas
27
27
  const [phoneNumberField, setPhoneNumberField] = React.useState(false);
28
28
  const [isLoading, setLoading] = React.useState(false);
29
29
  const [showPhoneError, setShowPhoneError] = React.useState(false);
30
+ const [sendError, setSendError] = React.useState(false);
30
31
  const isValid = isPhoneValid(phoneNumber);
31
32
  const auth = useAuth();
32
33
  const { t } = useTranslate();
33
34
  const prefix = 'signIn';
35
+ const otpLabel = t(prefix + '.whatsappVerificationCode', 'WhatsApp verification code');
34
36
  const validateOTP = (phone, otp) => {
35
37
  if (!phone || !otp)
36
38
  return;
37
39
  Server.call(packageName, 'validateOTPWhatsapp', phone, otp).then((response) => {
38
40
  if (response && response.auth) {
41
+ // A browser gets the tokens as httpOnly cookies the server already set; only a
42
+ // native client (body transport) receives refreshToken. The expiry fields size the
43
+ // refresh token in native storage to the server's record.
39
44
  auth.updateAuth({
40
45
  auth: response.auth,
41
46
  accessToken: response.accessToken,
42
47
  refreshToken: response.refreshToken,
48
+ refreshTokenExpiresIn: response.refreshTokenExpiresIn,
49
+ refreshTokenExpiresAt: response.refreshTokenExpiresAt,
43
50
  });
44
51
  onSuccess(true);
45
52
  }
@@ -57,13 +64,18 @@ export const SigninWithWhatsappButton = ({ label = 'Sign in with Whatsapp', clas
57
64
  return;
58
65
  }
59
66
  setShowPhoneError(false);
67
+ setSendError(false);
60
68
  setLoading(true);
61
69
  Server.call(packageName, 'generateOTPWhatsapp', phone)
62
- .then(() => {
70
+ .then((response) => {
71
+ if (!(response === null || response === void 0 ? void 0 : response.sent)) {
72
+ setSendError(true);
73
+ return;
74
+ }
63
75
  setOTPField(true);
64
76
  })
65
77
  .catch(() => {
66
- alert('Could not send the code. Please try again.');
78
+ setSendError(true);
67
79
  })
68
80
  .finally(() => {
69
81
  setLoading(false);
@@ -78,9 +90,10 @@ export const SigninWithWhatsappButton = ({ label = 'Sign in with Whatsapp', clas
78
90
  } }),
79
91
  React.createElement("button", { type: "button", className: style.signButton, "aria-label": "Send code", onClick: () => sendWhatsappMessage(phoneNumber) },
80
92
  React.createElement("img", { src: asset('/images/signButton.png'), alt: "" }))),
81
- showPhoneError && !isValid ? (React.createElement("div", { className: style.phoneError }, "Phone is not valid")) : null)) : (React.createElement(React.Fragment, null,
93
+ showPhoneError && !isValid ? (React.createElement("div", { className: style.phoneError }, "Phone is not valid")) : null,
94
+ sendError && (React.createElement("div", { className: style.phoneError, role: "alert" }, "Could not send the WhatsApp code. Please try again.")))) : (React.createElement("div", { className: style.otpStep },
82
95
  React.createElement("h3", null, "Enter your OTP code"),
83
- React.createElement(InputOTP, { maxLength: 6, pattern: REGEXP_ONLY_DIGITS, inputMode: "numeric", autoComplete: "one-time-code", onComplete: (otp) => validateOTP(phoneNumber, otp) },
96
+ React.createElement(InputOTP, { maxLength: 6, pattern: REGEXP_ONLY_DIGITS, inputMode: "numeric", autoComplete: "one-time-code", "aria-label": otpLabel, containerClassName: style.otpInput, onComplete: (otp) => validateOTP(phoneNumber, otp) },
84
97
  React.createElement(InputOTPGroup, null, Array.from({ length: 6 }, (_, index) => (React.createElement(InputOTPSlot, { key: index, index: index })))))))));
85
98
  };
86
99
  //# sourceMappingURL=SignInWithWhatsapp.js.map
@@ -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,2BA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AAC,QAAQ,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 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,a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S,EACnB,YAAY,EAAC,eAAe,gBAChB,QAAQ,EACpB,kBAAkB,EAAE,KAAK,CAAC,QAAQ,EAClC,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,CACP,CACP,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 [sendError, setSendError] = React.useState(false);\n const isValid = isPhoneValid(phoneNumber);\n\n const auth = useAuth();\n const { t } = useTranslate();\n const prefix = 'signIn';\n const otpLabel = t(\n prefix + '.whatsappVerificationCode',\n 'WhatsApp verification code'\n );\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 setSendError(false);\n setLoading(true);\n Server.call(packageName, 'generateOTPWhatsapp', phone)\n .then((response) => {\n if (!response?.sent) {\n setSendError(true);\n return;\n }\n setOTPField(true);\n })\n .catch(() => {\n setSendError(true);\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 {sendError && (\n <div className={style.phoneError} role=\"alert\">\n Could not send the WhatsApp code. Please try again.\n </div>\n )}\n </div>\n ) : (\n <div className={style.otpStep}>\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 aria-label={otpLabel}\n containerClassName={style.otpInput}\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 </div>\n )}\n </>\n );\n};\n"]}
@@ -85,6 +85,31 @@
85
85
  margin-top: 6px;
86
86
  }
87
87
 
88
+ .otpStep {
89
+ display: flex;
90
+ flex-direction: column;
91
+ align-items: center;
92
+ gap: 12px;
93
+ width: 100%;
94
+ min-width: 0;
95
+ }
96
+
97
+ .otpStep h3 {
98
+ width: 100%;
99
+ margin: 0;
100
+ font-size: clamp(24px, 3vw, 32px);
101
+ line-height: 1.2;
102
+ text-align: center;
103
+ }
104
+
105
+ .otpInput {
106
+ justify-content: center;
107
+ width: 100%;
108
+ max-width: 100%;
109
+ --otp-slot-size: clamp(34px, 7vw, 48px);
110
+ --otp-slot-gap: clamp(3px, 1vw, 8px);
111
+ }
112
+
88
113
  .loading {
89
114
  width: 32px;
90
115
  height: 32px;
@@ -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,MA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;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 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,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,eAAe,GAChB,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,CAAC,KAAK,CAAC,CAAC;IAE9C,MAAM,IAAI,GAAG,OAAO,EAAE,CAAC;IACvB,MAAM,aAAa,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IACpC,MAAM,mBAAmB,GAAG,qBAAqB,EAAE,CAAC;IAEpD,MAAM,eAAe,GAAG,KAAK,IAAI,EAAE;QACjC,IAAI,aAAa,CAAC,OAAO;YAAE,OAAO;QAClC,aAAa,CAAC,OAAO,GAAG,IAAI,CAAC;QAC7B,UAAU,CAAC,IAAI,CAAC,CAAC;QACjB,IAAI,MAAwC,CAAC;QAC7C,IAAI,CAAC;YACH,eAAe,aAAf,eAAe,uBAAf,eAAe,CAAG,IAAI,CAAC,CAAC;YACxB,oEAAoE;YACpE,MAAM,GAAG,MAAM,eAAe,CAAC,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;QAC5E,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,UAAU,GAAG,wBAAwB,CAAC,KAAK,CAAC,CAAC;YACnD,IAAI,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,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,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,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,MAAM,QAAQ,GAAG,KAAK,IAAI,EAAE;QAC1B,IAAI,aAAa,CAAC,OAAO;YAAE,OAAO;QAClC,aAAa,CAAC,OAAO,GAAG,IAAI,CAAC;QAC7B,UAAU,CAAC,IAAI,CAAC,CAAC;QACjB,IAAI,MAAwC,CAAC;QAC7C,IAAI,CAAC;YACH,eAAe,aAAf,eAAe,uBAAf,eAAe,CAAG,IAA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AAG;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,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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\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.1",
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,67 @@ 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
+ });
154
+
155
+ test('WhatsApp verification uses an accessible numeric OTP field', async () => {
156
+ const source = await readFile(
157
+ new URL('../lib/esm/components/SignInWithWhatsapp.js', import.meta.url),
158
+ 'utf8'
159
+ );
160
+ assert.match(source, /pattern:\s*REGEXP_ONLY_DIGITS/);
161
+ assert.match(source, /inputMode:\s*"numeric"/);
162
+ assert.match(source, /autoComplete:\s*"one-time-code"/);
163
+ assert.match(source, /"aria-label":\s*otpLabel/);
164
+ });
@@ -0,0 +1,67 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import CapacitorBackendProvider from '../lib/esm/backend.js';
4
+
5
+ const makeProvider = () => {
6
+ const provider = Object.create(CapacitorBackendProvider.prototype);
7
+ Object.defineProperty(provider, 'request', { value: { session: {} } });
8
+ provider.generateOTP = () => 123456;
9
+ return provider;
10
+ };
11
+
12
+ const setEnv = (t, key, value) => {
13
+ const previous = process.env[key];
14
+ process.env[key] = value;
15
+ t.after(() => {
16
+ if (previous === undefined) delete process.env[key];
17
+ else process.env[key] = previous;
18
+ });
19
+ };
20
+
21
+ test('WhatsApp send uses the API key and configured authentication template', async (t) => {
22
+ t.mock.method(globalThis, 'fetch', async (_url, options) => {
23
+ const payload = JSON.parse(options.body);
24
+ assert.equal(options.headers['D360-API-KEY'], 'test-key');
25
+ assert.equal(options.headers.Authorization, undefined);
26
+ assert.equal(payload.template.name, 'authentication_test');
27
+ assert.equal(payload.to, '15551234567');
28
+ assert.equal(payload.template.language.code, 'en');
29
+ assert.equal(payload.template.components[0].parameters[0].text, 123456);
30
+ assert.equal(payload.template.components[1].parameters[0].text, '123456');
31
+ return { ok: true, json: async () => ({ messages: [{ id: 'test-message' }] }) };
32
+ });
33
+ t.mock.method(console, 'log', () => {
34
+ throw new Error('OTP must never be logged');
35
+ });
36
+ setEnv(t, 'WA_D360_API_KEY', 'test-key');
37
+ setEnv(t, 'WA_D360_TEMPLATE_NAME', 'authentication_test');
38
+ const provider = makeProvider();
39
+ assert.deepEqual(await provider.generateOTPWhatsapp('+1 555 123 4567'), { sent: true });
40
+ assert.equal(provider.request.session.otp, 123456);
41
+ });
42
+
43
+ test('a rejected WhatsApp request never enables an OTP', async (t) => {
44
+ setEnv(t, 'WA_D360_API_KEY', 'test-key');
45
+ setEnv(t, 'WA_D360_TEMPLATE_NAME', 'authentication_test');
46
+ t.mock.method(globalThis, 'fetch', async () => ({ ok: false, status: 401 }));
47
+ t.mock.method(console, 'error', () => {});
48
+ const provider = makeProvider();
49
+ await assert.rejects(
50
+ provider.generateOTPWhatsapp('15551234567'),
51
+ /Could not send the code/
52
+ );
53
+ assert.equal(provider.request.session.otp, undefined);
54
+ });
55
+
56
+ test('a provider response without a message id never enables an OTP', async (t) => {
57
+ setEnv(t, 'WA_D360_API_KEY', 'test-key');
58
+ setEnv(t, 'WA_D360_TEMPLATE_NAME', 'authentication_test');
59
+ t.mock.method(globalThis, 'fetch', async () => ({ ok: true, json: async () => ({}) }));
60
+ t.mock.method(console, 'error', () => {});
61
+ const provider = makeProvider();
62
+ await assert.rejects(
63
+ provider.generateOTPWhatsapp('15551234567'),
64
+ /Could not send the code/
65
+ );
66
+ assert.equal(provider.request.session.otp, undefined);
67
+ });