@linked.cm/capacitor 0.3.3 → 0.3.5

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,22 @@
1
1
  # @linked.cm/capacitor
2
2
 
3
+ ## 0.3.5
4
+
5
+ ### Patch Changes
6
+
7
+ - [#20](https://github.com/linked-cm/capacitor/pull/20) [`4f2a72a`](https://github.com/linked-cm/capacitor/commit/4f2a72a1641200837b3efbd03a3febfb024bc4d3) Thanks [@abdipramana](https://github.com/abdipramana)! - Check deterministic WhatsApp WebID and telephone-property matches together so
8
+ an existing duplicate identity is rejected instead of authenticated.
9
+
10
+ - [#20](https://github.com/linked-cm/capacitor/pull/20) [`4f2a72a`](https://github.com/linked-cm/capacitor/commit/4f2a72a1641200837b3efbd03a3febfb024bc4d3) Thanks [@abdipramana](https://github.com/abdipramana)! - WhatsApp code requests now obtain a 360dialog access token and send it as `Authorization: bearer` together with `D360-API-KEY`. The template payload includes `WA_D360_TEMPLATE_NAMESPACE` and a deterministic language policy.
11
+
12
+ `generateOTPWhatsapp` still returns `{ sent: true }` only after the provider answers HTTP 2xx. A 2xx response without `messages[0].id` is treated as delivered, and the code is stored on the session only then. A rejected send clears any previous code. `WA_D360_USERNAME` and `WA_D360_PASSWORD` are required.
13
+
14
+ ## 0.3.4
15
+
16
+ ### Patch Changes
17
+
18
+ - [#18](https://github.com/linked-cm/capacitor/pull/18) [`b3a3633`](https://github.com/linked-cm/capacitor/commit/b3a36335996ac527ff97ae18a8b2b35b06a3e15e) Thanks [@abdipramana](https://github.com/abdipramana)! - Invalidate previous WhatsApp OTPs when a resend fails or is not confirmed by the provider.
19
+
3
20
  ## 0.3.3
4
21
 
5
22
  ### Patch Changes
@@ -0,0 +1,61 @@
1
+ ---
2
+ summary: WhatsApp code sends request a 360dialog bearer token, then store the code and return `{ sent: true }` only after HTTP 2xx.
3
+ ---
4
+
5
+ # WhatsApp code send
6
+
7
+ ## Outcome
8
+
9
+ `generateOTPWhatsapp` asks the 360dialog hub for an access token, then posts the authentication template with both `Authorization: bearer <token>` and `D360-API-KEY`. The sign-in screen opens the code step only when the call returns `{ sent: true }`.
10
+
11
+ There was no plan document for this change. This report is the record.
12
+
13
+ Pull request: https://github.com/linked-cm/capacitor/pull/20
14
+
15
+ ## Request flow
16
+
17
+ 1. Refuse the call when the request has no session.
18
+ 2. Normalize the phone number to digits and require `WA_D360_API_KEY`.
19
+ 3. Delete any code already stored on the session, so a failed resend cannot be used.
20
+ 4. `POST https://hub.360dialog.io/api/v2/token` with `WA_D360_USERNAME` and `WA_D360_PASSWORD`. A missing token is a failed send.
21
+ 5. `POST https://waba-v2.360dialog.io/messages` with the template namespace, template name, deterministic language policy, and the code in the body and URL button.
22
+ 6. On HTTP 2xx, store the code and return `{ sent: true }`. The response body is not required to contain `messages[0].id`.
23
+ 7. On any other failure, leave the session without a code and throw `Could not send the code. Please try again.`
24
+
25
+ `validateOTPWhatsapp` is unchanged. It still compares the submitted code with `session.otp`.
26
+
27
+ ## Decisions
28
+
29
+ - The bearer token is added because the hub token endpoint is what the current 360dialog account uses. The API key header stays.
30
+ - HTTP 2xx is the acceptance signal. Requiring `messages[0].id` hid a delivered code from the sign-in screen when the provider omitted that id.
31
+ - The code is written to the session only after that 2xx. Writing it before the request let a rejected send leave a usable code behind.
32
+ - The screen keeps checking `response.sent`. A call that resolves without that flag, which non-2xx RPC responses can do, stays on the phone step and shows the inline error.
33
+ - `WA_D360_TEMPLATE_LANGUAGE` still overrides the language code. The default remains `en`. The policy is always `deterministic` because authentication templates are rejected without it.
34
+
35
+ ## Public behavior
36
+
37
+ Callers of `generateOTPWhatsapp` receive `{ sent: true }` or a thrown error. They no longer receive the provider body. Required environment variables:
38
+
39
+ - `WA_D360_API_KEY`
40
+ - `WA_D360_USERNAME`
41
+ - `WA_D360_PASSWORD`
42
+ - `WA_D360_TEMPLATE_NAMESPACE`
43
+ - `WA_D360_TEMPLATE_NAME`
44
+ - `WA_D360_TEMPLATE_LANGUAGE` (optional)
45
+
46
+ ## Files
47
+
48
+ - `src/backend.ts` — token request, template send, and session write.
49
+ - `src/components/SignInWithWhatsapp.tsx` — opens the code step only for `{ sent: true }`.
50
+ - `tests/whatsapp-otp.test.mjs` — token header, rejected resend, and 2xx without a message id.
51
+ - `readme.md` — documents the `{ sent: true }` result next to the environment variables.
52
+
53
+ ## Tests
54
+
55
+ `npm test` builds `lib/esm` and runs `tests/*.test.mjs`. The WhatsApp send tests cover the bearer header, namespace, normalized recipient, successful store, rejected resend clearing the previous code, and a 2xx body without a message id.
56
+
57
+ ## Limitations
58
+
59
+ The session is still `express-session` on the app server. This package does not create that session. If `req.session` is missing, the send fails before 360dialog is called.
60
+
61
+ The token is requested on every send and is not cached.
@@ -22,8 +22,9 @@ export default class CapacitorBackendProvider extends BackendProvider {
22
22
  generateOTPWhatsapp(phoneNumber: any): Promise<{
23
23
  sent: boolean;
24
24
  }>;
25
+ getBearerToken(): Promise<any>;
25
26
  generateOTP(): number;
26
- sendMessage(url: any, apiKey: any, otp: any, phoneNumber: any): Promise<Response>;
27
+ sendMessage(url: any, bearerToken: any, apiKey: any, otp: any, phoneNumber: any): Promise<Response>;
27
28
  getUserLocationAction(user: UserData): Promise<{
28
29
  agent: {
29
30
  id: string;
@@ -82,20 +82,10 @@ export default class CapacitorBackendProvider extends BackendProvider {
82
82
  id: telephoneWebId,
83
83
  });
84
84
  });
85
- const webIdResolution = resolveTelephoneAccount(webIdAccounts);
86
- if (webIdResolution.kind === 'ambiguous') {
87
- throw new AmbiguousTelephoneIdentityError(webIdResolution);
88
- }
89
- let account = webIdResolution.kind === 'one' ? webIdResolution.account : null;
90
- if (account && account.accountOf) {
91
- console.log(`Found account by telephone-based webID for phone number ${phoneIdentifier}`);
92
- return {
93
- account,
94
- person: account.accountOf,
95
- };
96
- }
97
- // if not found, try to find by telephone property (for old users with normal ID)
98
- console.log(`Account not found by webID, searching by telephone property for ${normalizedPhone}`);
85
+ // Also query the telephone property even when the deterministic WebID
86
+ // exists. Legacy email accounts may own the same number; returning the
87
+ // WebID match early would hide that conflict and authenticate the
88
+ // duplicate account.
99
89
  const telephoneAccounts = await this.accountShape.select((ua) => [
100
90
  ua.email,
101
91
  ua.accountOf.select((p) => [
@@ -110,16 +100,16 @@ export default class CapacitorBackendProvider extends BackendProvider {
110
100
  .equals(normalizedPhone)
111
101
  .or(ua.accountOf.telephone.equals(legacyPhone));
112
102
  });
113
- const telephoneResolution = resolveTelephoneAccount(telephoneAccounts);
114
- if (telephoneResolution.kind === 'ambiguous') {
115
- throw new AmbiguousTelephoneIdentityError(telephoneResolution);
103
+ const resolution = resolveTelephoneAccount([
104
+ ...webIdAccounts,
105
+ ...telephoneAccounts,
106
+ ]);
107
+ if (resolution.kind === 'ambiguous') {
108
+ throw new AmbiguousTelephoneIdentityError(resolution);
116
109
  }
117
- account =
118
- telephoneResolution.kind === 'one'
119
- ? telephoneResolution.account
120
- : null;
110
+ const account = resolution.kind === 'one' ? resolution.account : null;
121
111
  if (account && account.accountOf) {
122
- console.log(`Found account by telephone property for phone number ${phoneIdentifier}`);
112
+ console.log(`Found one account across WhatsApp WebID and telephone lookups for phone number ${phoneIdentifier}`);
123
113
  return {
124
114
  account,
125
115
  person: account.accountOf,
@@ -185,54 +175,79 @@ export default class CapacitorBackendProvider extends BackendProvider {
185
175
  }
186
176
  }
187
177
  async generateOTPWhatsapp(phoneNumber) {
188
- var _a, _b;
189
178
  const session = this.request.session;
190
- const baseUrl = 'https://waba-v2.360dialog.io';
191
- const API_KEY = process.env.WA_D360_API_KEY;
179
+ if (!session) {
180
+ throw new Error('Could not send the code. Please try again.');
181
+ }
192
182
  const recipient = normalizeTelephone(phoneNumber).replace(/^\+/, '');
193
183
  if (!/^\d{8,15}$/.test(recipient)) {
194
184
  throw new Error('A valid WhatsApp phone number is required');
195
185
  }
196
- if (!API_KEY) {
186
+ const apiKey = process.env.WA_D360_API_KEY;
187
+ if (!apiKey) {
197
188
  throw new Error('WA_D360_API_KEY is required to send a WhatsApp code');
198
189
  }
199
190
  const otp = this.generateOTP();
200
- const url = `${baseUrl}/messages`;
191
+ // A resend invalidates an earlier code even when the provider rejects it.
192
+ delete session.otp;
201
193
  try {
202
- const response = await this.sendMessage(url, API_KEY, otp, recipient);
194
+ const bearerToken = await this.getBearerToken();
195
+ const response = await this.sendMessage('https://waba-v2.360dialog.io/messages', bearerToken, apiKey, otp, recipient);
203
196
  if (!response.ok) {
204
197
  console.error('WhatsApp code request rejected by provider:', response.status);
205
198
  throw new Error('Could not send the code. Please try again.');
206
199
  }
207
- const data = await response.json();
208
- 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)) {
209
- throw new Error('WhatsApp provider did not confirm the code request');
210
- }
211
- // Only make a code usable after the provider accepts the message.
212
- session.otp = otp;
213
- return { sent: true };
214
200
  }
215
201
  catch (error) {
216
- console.error('WhatsApp code send failed:', error.message);
202
+ const message = error instanceof Error ? error.message : '';
203
+ if (message !== 'Could not send the code. Please try again.') {
204
+ console.error('WhatsApp code send failed:', message);
205
+ }
206
+ throw new Error('Could not send the code. Please try again.');
207
+ }
208
+ // HTTP 2xx is acceptance. The provider can omit messages[0].id after the
209
+ // message is already delivered, so the code becomes usable here.
210
+ session.otp = otp;
211
+ return { sent: true };
212
+ }
213
+ async getBearerToken() {
214
+ const username = process.env.WA_D360_USERNAME;
215
+ const password = process.env.WA_D360_PASSWORD;
216
+ if (!username || !password) {
217
+ throw new Error('WA_D360_USERNAME and WA_D360_PASSWORD are required to request a WhatsApp token');
218
+ }
219
+ const response = await fetch('https://hub.360dialog.io/api/v2/token', {
220
+ method: 'POST',
221
+ headers: { 'Content-Type': 'application/json' },
222
+ body: JSON.stringify({ username, password }),
223
+ });
224
+ const data = await response.json().catch(() => ({}));
225
+ if (!response.ok || !(data === null || data === void 0 ? void 0 : data.access_token)) {
226
+ console.error('WhatsApp token request rejected:', response.status);
217
227
  throw new Error('Could not send the code. Please try again.');
218
228
  }
229
+ return data.access_token;
219
230
  }
220
231
  generateOTP() {
221
232
  return Math.floor(100000 + Math.random() * 900000);
222
233
  }
223
- async sendMessage(url, apiKey, otp, phoneNumber) {
234
+ async sendMessage(url, bearerToken, apiKey, otp, phoneNumber) {
235
+ const templateNamespace = process.env.WA_D360_TEMPLATE_NAMESPACE;
224
236
  const templateName = process.env.WA_D360_TEMPLATE_NAME;
225
- if (!templateName) {
226
- throw new Error('WA_D360_TEMPLATE_NAME is required to send a WhatsApp code');
237
+ if (!templateNamespace || !templateName) {
238
+ throw new Error('WA_D360_TEMPLATE_NAMESPACE and WA_D360_TEMPLATE_NAME are required to send a WhatsApp code');
227
239
  }
228
240
  const payload = {
229
241
  messaging_product: 'whatsapp',
230
242
  to: phoneNumber,
231
243
  type: 'template',
232
244
  template: {
245
+ namespace: templateNamespace,
233
246
  name: templateName,
234
247
  language: {
235
248
  code: process.env.WA_D360_TEMPLATE_LANGUAGE || 'en',
249
+ // Authentication templates are rejected without a deterministic policy.
250
+ policy: 'deterministic',
236
251
  },
237
252
  components: [
238
253
  {
@@ -262,6 +277,7 @@ export default class CapacitorBackendProvider extends BackendProvider {
262
277
  method: 'POST',
263
278
  headers: {
264
279
  'Content-Type': 'application/json',
280
+ Authorization: `bearer ${bearerToken}`,
265
281
  'D360-API-KEY': apiKey,
266
282
  },
267
283
  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,QAAQ,EAAE,MAAM,sCAAsC,CAAC;AAChE,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,EAAE,kBAAk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,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;AAxUO;IADL,QAAQ,CAAC,QAAQ,CAAC;;;;mEAuLlB;AAGK;IADL,QAAQ,CAAC,QAAQ,CAAC;;;;mEAiClB","sourcesContent":["import { Person as SchemaPerson } from '@_linked/schema/shapes/Person';\nimport { BackendProvider } from '@_linked/server-utils/utils/BackendProvider';\nimport { callable } from '@_linked/server-utils/utils/callable';\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';\nimport {\n AMBIGUOUS_TELEPHONE_IDENTITY,\n AmbiguousTelephoneIdentityError,\n resolveTelephoneAccount,\n} from './utils/telephoneAccount.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 @callable('public')\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 // Query through the configured account shape. Applications can use a\n // UserAccount subclass with a different target class, so querying the\n // base SIOC shape would miss their existing accounts and create a\n // duplicate telephone-only identity.\n const webIdAccounts = await this.accountShape.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\n const webIdResolution = resolveTelephoneAccount(webIdAccounts);\n if (webIdResolution.kind === 'ambiguous') {\n throw new AmbiguousTelephoneIdentityError(webIdResolution);\n }\n let account =\n webIdResolution.kind === 'one' ? webIdResolution.account : null;\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 const telephoneAccounts = await this.accountShape.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\n const telephoneResolution = resolveTelephoneAccount(telephoneAccounts);\n if (telephoneResolution.kind === 'ambiguous') {\n throw new AmbiguousTelephoneIdentityError(telephoneResolution);\n }\n account =\n telephoneResolution.kind === 'one'\n ? telephoneResolution.account\n : null;\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 if (err instanceof AmbiguousTelephoneIdentityError) {\n console.warn(\n 'WhatsApp sign-in refused because the telephone matches multiple identities',\n {\n accountCount: err.resolution.accountIds.length,\n personCount: err.resolution.personIds.length,\n }\n );\n return {\n error:\n 'Multiple accounts use this phone number. Please use another sign-in method or contact support.',\n code: AMBIGUOUS_TELEPHONE_IDENTITY,\n };\n }\n console.error('validateOTPWhatsapp failed:', err);\n return {\n error: 'Sign-in failed. Please try again.',\n };\n }\n }\n\n @callable('public')\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"]}
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,C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Q,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;AAlWO;IADL,QAAQ,CAAC,QAAQ,CAAC;;;;mEAsKlB;AAGK;IADL,QAAQ,CAAC,QAAQ,CAAC;;;;mEAgDlB","sourcesContent":["import { Person as SchemaPerson } from '@_linked/schema/shapes/Person';\nimport { BackendProvider } from '@_linked/server-utils/utils/BackendProvider';\nimport { callable } from '@_linked/server-utils/utils/callable';\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';\nimport {\n AMBIGUOUS_TELEPHONE_IDENTITY,\n AmbiguousTelephoneIdentityError,\n resolveTelephoneAccount,\n} from './utils/telephoneAccount.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 @callable('public')\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 // Query through the configured account shape. Applications can use a\n // UserAccount subclass with a different target class, so querying the\n // base SIOC shape would miss their existing accounts and create a\n // duplicate telephone-only identity.\n const webIdAccounts = await this.accountShape.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\n // Also query the telephone property even when the deterministic WebID\n // exists. Legacy email accounts may own the same number; returning the\n // WebID match early would hide that conflict and authenticate the\n // duplicate account.\n const telephoneAccounts = await this.accountShape.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\n const resolution = resolveTelephoneAccount([\n ...webIdAccounts,\n ...telephoneAccounts,\n ]);\n if (resolution.kind === 'ambiguous') {\n throw new AmbiguousTelephoneIdentityError(resolution);\n }\n const account = resolution.kind === 'one' ? resolution.account : null;\n\n if (account && account.accountOf) {\n console.log(\n `Found one account across WhatsApp WebID and telephone lookups 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 if (err instanceof AmbiguousTelephoneIdentityError) {\n console.warn(\n 'WhatsApp sign-in refused because the telephone matches multiple identities',\n {\n accountCount: err.resolution.accountIds.length,\n personCount: err.resolution.personIds.length,\n }\n );\n return {\n error:\n 'Multiple accounts use this phone number. Please use another sign-in method or contact support.',\n code: AMBIGUOUS_TELEPHONE_IDENTITY,\n };\n }\n console.error('validateOTPWhatsapp failed:', err);\n return {\n error: 'Sign-in failed. Please try again.',\n };\n }\n }\n\n @callable('public')\n async generateOTPWhatsapp(phoneNumber) {\n const session = this.request.session;\n if (!session) {\n throw new Error('Could not send the code. Please try again.');\n }\n\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 const apiKey = process.env.WA_D360_API_KEY;\n if (!apiKey) {\n throw new Error('WA_D360_API_KEY is required to send a WhatsApp code');\n }\n\n const otp = this.generateOTP();\n // A resend invalidates an earlier code even when the provider rejects it.\n delete session.otp;\n\n try {\n const bearerToken = await this.getBearerToken();\n const response = await this.sendMessage(\n 'https://waba-v2.360dialog.io/messages',\n bearerToken,\n apiKey,\n otp,\n recipient\n );\n if (!response.ok) {\n console.error(\n 'WhatsApp code request rejected by provider:',\n response.status\n );\n throw new Error('Could not send the code. Please try again.');\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : '';\n if (message !== 'Could not send the code. Please try again.') {\n console.error('WhatsApp code send failed:', message);\n }\n throw new Error('Could not send the code. Please try again.');\n }\n\n // HTTP 2xx is acceptance. The provider can omit messages[0].id after the\n // message is already delivered, so the code becomes usable here.\n session.otp = otp;\n return { sent: true };\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 response = await fetch('https://hub.360dialog.io/api/v2/token', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ username, password }),\n });\n const data = await response.json().catch(() => ({}));\n if (!response.ok || !data?.access_token) {\n console.error('WhatsApp token request rejected:', response.status);\n throw new Error('Could not send the code. Please try again.');\n }\n return data.access_token;\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: process.env.WA_D360_TEMPLATE_LANGUAGE || 'en',\n // Authentication templates are rejected without a deterministic policy.\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"]}
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.3.3",
13
+ "version": "0.3.5",
14
14
  "linkedPackage": true,
15
15
  "type": "module",
16
16
  "main": "lib/esm/index.js",
package/readme.md CHANGED
@@ -43,7 +43,7 @@ Sign-in is verified by `@_linked/auth` 3:
43
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
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
45
 
46
- WhatsApp sign-in asks the backend to send a code, then validates it. The server reads:
46
+ WhatsApp sign-in asks the backend to send a code, then validates it. `generateOTPWhatsapp` returns `{ sent: true }` after the provider answers HTTP 2xx, and only then stores the code on the browser session. The server reads:
47
47
 
48
48
  - `WA_D360_API_KEY`
49
49
  - `WA_D360_USERNAME`
@@ -65,3 +65,15 @@ test('one account linked to distinct Persons is ambiguous', () => {
65
65
  assert.deepEqual(resolution.personIds, ['urn:person:1', 'urn:person:2']);
66
66
  });
67
67
 
68
+ test('combined WebID and telephone matches expose a legacy duplicate', () => {
69
+ const resolution = resolveTelephoneAccount([
70
+ account('urn:account:whatsapp', 'urn:person:whatsapp'),
71
+ account('urn:account:email', 'urn:person:email'),
72
+ ]);
73
+
74
+ assert.deepEqual(resolution, {
75
+ kind: 'ambiguous',
76
+ accountIds: ['urn:account:email', 'urn:account:whatsapp'],
77
+ personIds: ['urn:person:email', 'urn:person:whatsapp'],
78
+ });
79
+ });
@@ -2,9 +2,9 @@ import assert from 'node:assert/strict';
2
2
  import test from 'node:test';
3
3
  import CapacitorBackendProvider from '../lib/esm/backend.js';
4
4
 
5
- const makeProvider = () => {
5
+ const makeProvider = (session = {}) => {
6
6
  const provider = Object.create(CapacitorBackendProvider.prototype);
7
- Object.defineProperty(provider, 'request', { value: { session: {} } });
7
+ Object.defineProperty(provider, 'request', { value: { session } });
8
8
  provider.generateOTP = () => 123456;
9
9
  return provider;
10
10
  };
@@ -18,14 +18,28 @@ const setEnv = (t, key, value) => {
18
18
  });
19
19
  };
20
20
 
21
+ const configureSend = (t) => {
22
+ setEnv(t, 'WA_D360_API_KEY', 'test-key');
23
+ setEnv(t, 'WA_D360_USERNAME', 'wa-user');
24
+ setEnv(t, 'WA_D360_PASSWORD', 'wa-password');
25
+ setEnv(t, 'WA_D360_TEMPLATE_NAMESPACE', 'test-namespace');
26
+ setEnv(t, 'WA_D360_TEMPLATE_NAME', 'authentication_test');
27
+ };
28
+
21
29
  test('WhatsApp send uses the API key and configured authentication template', async (t) => {
22
- t.mock.method(globalThis, 'fetch', async (_url, options) => {
30
+ t.mock.method(globalThis, 'fetch', async (url, options) => {
31
+ if (String(url).endsWith('/token')) {
32
+ assert.equal(JSON.parse(options.body).username, 'wa-user');
33
+ return { ok: true, json: async () => ({ access_token: 'token-1' }) };
34
+ }
23
35
  const payload = JSON.parse(options.body);
24
36
  assert.equal(options.headers['D360-API-KEY'], 'test-key');
25
- assert.equal(options.headers.Authorization, undefined);
37
+ assert.equal(options.headers.Authorization, 'bearer token-1');
38
+ assert.equal(payload.template.namespace, 'test-namespace');
26
39
  assert.equal(payload.template.name, 'authentication_test');
27
40
  assert.equal(payload.to, '15551234567');
28
41
  assert.equal(payload.template.language.code, 'en');
42
+ assert.equal(payload.template.language.policy, 'deterministic');
29
43
  assert.equal(payload.template.components[0].parameters[0].text, 123456);
30
44
  assert.equal(payload.template.components[1].parameters[0].text, '123456');
31
45
  return { ok: true, json: async () => ({ messages: [{ id: 'test-message' }] }) };
@@ -33,19 +47,22 @@ test('WhatsApp send uses the API key and configured authentication template', as
33
47
  t.mock.method(console, 'log', () => {
34
48
  throw new Error('OTP must never be logged');
35
49
  });
36
- setEnv(t, 'WA_D360_API_KEY', 'test-key');
37
- setEnv(t, 'WA_D360_TEMPLATE_NAME', 'authentication_test');
50
+ configureSend(t);
38
51
  const provider = makeProvider();
39
52
  assert.deepEqual(await provider.generateOTPWhatsapp('+1 555 123 4567'), { sent: true });
40
53
  assert.equal(provider.request.session.otp, 123456);
41
54
  });
42
55
 
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 }));
56
+ test('a rejected WhatsApp resend invalidates the earlier OTP', async (t) => {
57
+ configureSend(t);
58
+ t.mock.method(globalThis, 'fetch', async (url) => {
59
+ if (String(url).endsWith('/token')) {
60
+ return { ok: true, json: async () => ({ access_token: 'token-1' }) };
61
+ }
62
+ return { ok: false, status: 401, json: async () => ({}) };
63
+ });
47
64
  t.mock.method(console, 'error', () => {});
48
- const provider = makeProvider();
65
+ const provider = makeProvider({ otp: 654321 });
49
66
  await assert.rejects(
50
67
  provider.generateOTPWhatsapp('15551234567'),
51
68
  /Could not send the code/
@@ -53,15 +70,16 @@ test('a rejected WhatsApp request never enables an OTP', async (t) => {
53
70
  assert.equal(provider.request.session.otp, undefined);
54
71
  });
55
72
 
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 () => ({}) }));
73
+ test('an accepted WhatsApp send without a message id still returns the code entry step', async (t) => {
74
+ configureSend(t);
75
+ t.mock.method(globalThis, 'fetch', async (url) => {
76
+ if (String(url).endsWith('/token')) {
77
+ return { ok: true, json: async () => ({ access_token: 'token-1' }) };
78
+ }
79
+ return { ok: true, json: async () => ({}) };
80
+ });
60
81
  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);
82
+ const provider = makeProvider({ otp: 654321 });
83
+ assert.deepEqual(await provider.generateOTPWhatsapp('15551234567'), { sent: true });
84
+ assert.equal(provider.request.session.otp, 123456);
67
85
  });
@@ -21,3 +21,14 @@ test('WhatsApp OTP generation does not log the plaintext code', () => {
21
21
  /console\.log\(['"]OTP/
22
22
  );
23
23
  });
24
+
25
+ test('WhatsApp validation resolves WebID and telephone matches together', () => {
26
+ const source =
27
+ CapacitorBackendProvider.prototype.validateOTPWhatsapp.toString();
28
+
29
+ assert.match(
30
+ source,
31
+ /resolveTelephoneAccount\(\[\s*\.\.\.webIdAccounts,\s*\.\.\.telephoneAccounts,?\s*\]\)/
32
+ );
33
+ assert.doesNotMatch(source, /webIdResolution\.kind === ['"]one['"]/);
34
+ });