@curless/hotel-storefront 0.58.2 → 0.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/dist/account/fake-mall.d.ts +19 -0
  2. package/dist/account/fake-mall.d.ts.map +1 -1
  3. package/dist/account/fake-mall.js +81 -10
  4. package/dist/account/fake-mall.js.map +1 -1
  5. package/dist/account/index.d.ts +75 -3
  6. package/dist/account/index.d.ts.map +1 -1
  7. package/dist/account/index.js +765 -31
  8. package/dist/account/index.js.map +1 -1
  9. package/dist/account/mall.d.ts +3 -1
  10. package/dist/account/mall.d.ts.map +1 -1
  11. package/dist/account/mall.js +17 -2
  12. package/dist/account/mall.js.map +1 -1
  13. package/dist/account/ota-member.d.ts +72 -0
  14. package/dist/account/ota-member.d.ts.map +1 -0
  15. package/dist/account/ota-member.js +127 -0
  16. package/dist/account/ota-member.js.map +1 -0
  17. package/dist/account/pages.d.ts +99 -4
  18. package/dist/account/pages.d.ts.map +1 -1
  19. package/dist/account/pages.js +221 -16
  20. package/dist/account/pages.js.map +1 -1
  21. package/dist/account/requests.d.ts +13 -1
  22. package/dist/account/requests.d.ts.map +1 -1
  23. package/dist/account/requests.js +2 -1
  24. package/dist/account/requests.js.map +1 -1
  25. package/dist/account/store.d.ts +8 -0
  26. package/dist/account/store.d.ts.map +1 -1
  27. package/dist/account/store.js.map +1 -1
  28. package/dist/aggregate/places.d.ts +10 -0
  29. package/dist/aggregate/places.d.ts.map +1 -1
  30. package/dist/aggregate/places.js +21 -0
  31. package/dist/aggregate/places.js.map +1 -1
  32. package/dist/card.generated.d.ts +1 -1
  33. package/dist/card.generated.js +2 -2
  34. package/dist/card.generated.js.map +1 -1
  35. package/dist/choices.d.ts +88 -0
  36. package/dist/choices.d.ts.map +1 -0
  37. package/dist/choices.js +126 -0
  38. package/dist/choices.js.map +1 -0
  39. package/dist/otaless/backend.d.ts +28 -0
  40. package/dist/otaless/backend.d.ts.map +1 -1
  41. package/dist/otaless/backend.js +349 -93
  42. package/dist/otaless/backend.js.map +1 -1
  43. package/dist/otaless/client.d.ts +46 -4
  44. package/dist/otaless/client.d.ts.map +1 -1
  45. package/dist/otaless/client.js +138 -35
  46. package/dist/otaless/client.js.map +1 -1
  47. package/dist/otaless/limits.d.ts +58 -0
  48. package/dist/otaless/limits.d.ts.map +1 -0
  49. package/dist/otaless/limits.js +132 -0
  50. package/dist/otaless/limits.js.map +1 -0
  51. package/dist/otaless/make.d.ts.map +1 -1
  52. package/dist/otaless/make.js +14 -1
  53. package/dist/otaless/make.js.map +1 -1
  54. package/dist/otaless/places.d.ts +40 -4
  55. package/dist/otaless/places.d.ts.map +1 -1
  56. package/dist/otaless/places.js +152 -2
  57. package/dist/otaless/places.js.map +1 -1
  58. package/dist/present.d.ts +12 -1
  59. package/dist/present.d.ts.map +1 -1
  60. package/dist/present.js +27 -1
  61. package/dist/present.js.map +1 -1
  62. package/dist/server.d.ts +2 -2
  63. package/dist/server.d.ts.map +1 -1
  64. package/dist/server.js +53 -35
  65. package/dist/server.js.map +1 -1
  66. package/dist/sessions.d.ts +23 -4
  67. package/dist/sessions.d.ts.map +1 -1
  68. package/dist/sessions.js +57 -7
  69. package/dist/sessions.js.map +1 -1
  70. package/dist/supplier.d.ts +6 -0
  71. package/dist/supplier.d.ts.map +1 -1
  72. package/dist/supplier.js.map +1 -1
  73. package/dist/surface.js +1 -1
  74. package/dist/surface.js.map +1 -1
  75. package/dist/tools.d.ts +11 -1
  76. package/dist/tools.d.ts.map +1 -1
  77. package/dist/tools.js +424 -169
  78. package/dist/tools.js.map +1 -1
  79. package/dist/trip-ids.d.ts +35 -4
  80. package/dist/trip-ids.d.ts.map +1 -1
  81. package/dist/trip-ids.js +87 -19
  82. package/dist/trip-ids.js.map +1 -1
  83. package/dist/types.d.ts +35 -6
  84. package/dist/types.d.ts.map +1 -1
  85. package/package.json +1 -1
@@ -2,7 +2,8 @@ import { createHmac, randomBytes } from 'node:crypto';
2
2
  import { bodyLimit } from 'hono/body-limit';
3
3
  import { WindowCounter } from '../limits.js';
4
4
  import { LIMITS, MallError, makeMall, } from './mall.js';
5
- import { PAGE_HEADERS, accountPage, loginPage, say, signedInPage, statePage, } from './pages.js';
5
+ import { OtaMemberError, makeOtaMembers, maskNumber } from './ota-member.js';
6
+ import { PAGE_HEADERS, accountPage, linkGroupPage, linkReauthPage, linkedPage, loginPage, say, signedInPage, statePage, } from './pages.js';
6
7
  import { CODE, createSignIns, hashOf, same, } from './requests.js';
7
8
  import { AccountStore, WEB_IDLE_MS, WebSessions, shownOf } from './store.js';
8
9
  /**
@@ -21,11 +22,16 @@ export const accountToolNames = (prefix) => ({
21
22
  view: `view_${prefix}account`,
22
23
  signOut: `sign_out_${prefix}account`,
23
24
  card: `card_${prefix}account`,
25
+ // A hotel group's membership, linked to the account (0.58.0) - offered only
26
+ // where `account.memberships` lists one.
27
+ link: `link_${prefix}membership`,
24
28
  });
25
29
  /** Beside every answer of a deployment with an account, for the card's header. */
26
30
  export const ACCOUNT_META_KEY = 'curless/account';
27
31
  /** Beside a sign-in's answer where a card is drawn: the link and its short code, the card's alone. */
28
32
  export const SIGN_IN_META_KEY = 'curless/account-sign-in';
33
+ /** …and beside a membership link's answer (0.58.0): the same, with the group. */
34
+ export const LINK_META_KEY = 'curless/account-link';
29
35
  /** The mall is asked at most this often whether a sign-in is still theirs. */
30
36
  export const CHECK_EVERY_MS = 5 * 60_000;
31
37
  export const COOKIE = '__Host-hotel_account';
@@ -100,8 +106,24 @@ export const acceptLang = (h) => {
100
106
  }
101
107
  return 'en';
102
108
  };
103
- /** A mall failure that says the sign-in is not theirs any more - not a blip on the way. */
104
- const refused = (e) => e instanceof MallError && (e.envelope || e.code === 401 || e.code === 403);
109
+ /**
110
+ * A mall failure that says the sign-in is not theirs any more - not a blip on the way.
111
+ *
112
+ * ⚠️ A NO, NOT EVERY ENVELOPE (0.59.0, review C3). Any envelope that was not 200
113
+ * counted - and their envelope says 500 for a fault of their own too (Nexva's
114
+ * audit M-18): one 500 on a renewal a minute before the token lapsed signed the
115
+ * guest out, and ended their token at the mall. Now only a 4xx - HTTP's or the
116
+ * envelope's - is a no: the request was not theirs to grant. A 5xx, a timeout,
117
+ * an answer that is not JSON, a code that is not a number, and 408 / 429 (wait
118
+ * and ask again) leave them signed in, asked again next time. The refresh
119
+ * token's own lapse is the store's (store.ts), not this.
120
+ */
121
+ export const refused = (e) => e instanceof MallError &&
122
+ typeof e.code === 'number' &&
123
+ e.code >= 400 &&
124
+ e.code < 500 &&
125
+ e.code !== 408 &&
126
+ e.code !== 429;
105
127
  /**
106
128
  * ⚠️ A POST COMES FROM OUR OWN PAGE (and with the form's token): its Origin is
107
129
  * this site - the public origin, or the Host it was sent to (https; http only
@@ -132,6 +154,82 @@ export const readForm = async (c) => {
132
154
  return null;
133
155
  }
134
156
  };
157
+ /**
158
+ * ⚠️ A USER NAME'S WRONG GUESSES (review C8, robin 11-09): only a no from the
159
+ * mall counts - a sign-in that works clears the name, and a mall that did not
160
+ * answer is nobody's mistake. `enter` reserves a try BEFORE the mall is asked
161
+ * (it counts the tries still in flight with the failures, so a burst of posts
162
+ * on many links cannot all pass at "7 of 8"); `leave` settles it. No await sits
163
+ * between the check and the reservation. Idle names are forgotten first when
164
+ * the table is full, as WindowCounter does.
165
+ */
166
+ export class NameFailures {
167
+ windowMs;
168
+ now;
169
+ maxKeys;
170
+ fails = new Map();
171
+ busy = new Map();
172
+ constructor(windowMs, now, maxKeys = 10_000) {
173
+ this.windowMs = windowMs;
174
+ this.now = now;
175
+ this.maxKeys = maxKeys;
176
+ }
177
+ recent(key) {
178
+ const cutoff = this.now() - this.windowMs;
179
+ return (this.fails.get(key) ?? []).filter((t) => t > cutoff);
180
+ }
181
+ /** Whether this name is shut (failures in the window, with tries in flight, at the limit). */
182
+ shut(key, max) {
183
+ return this.recent(key).length + (this.busy.get(key) ?? 0) >= max;
184
+ }
185
+ /** Reserve one try; false (nothing reserved) when the name is shut. */
186
+ enter(key, max) {
187
+ if (this.shut(key, max))
188
+ return false;
189
+ this.busy.set(key, (this.busy.get(key) ?? 0) + 1);
190
+ return true;
191
+ }
192
+ /** The try is over: `failed` is counted, `ok` clears the name, `unknown` (no answer) counts nothing. */
193
+ leave(key, outcome) {
194
+ const left = (this.busy.get(key) ?? 1) - 1;
195
+ if (left > 0)
196
+ this.busy.set(key, left);
197
+ else
198
+ this.busy.delete(key);
199
+ if (outcome === 'ok') {
200
+ this.fails.delete(key);
201
+ return;
202
+ }
203
+ if (outcome === 'unknown')
204
+ return;
205
+ const recent = this.recent(key);
206
+ recent.push(this.now());
207
+ this.fails.delete(key);
208
+ this.fails.set(key, recent);
209
+ if (this.fails.size <= this.maxKeys)
210
+ return;
211
+ const cutoff = this.now() - this.windowMs;
212
+ for (const [k, times] of this.fails) {
213
+ if (this.fails.size <= this.maxKeys)
214
+ return;
215
+ if (!this.busy.has(k) && !times.some((t) => t > cutoff))
216
+ this.fails.delete(k);
217
+ }
218
+ while (this.fails.size > this.maxKeys) {
219
+ const idlest = this.fails.keys().next().value;
220
+ if (idlest === undefined || idlest === key)
221
+ break;
222
+ this.fails.delete(idlest);
223
+ }
224
+ }
225
+ }
226
+ /** How long renewals may go unanswered, the access token lapsed, before the sign-in goes (C3). */
227
+ export const RENEW_GIVE_UP_MS = 15 * 60_000;
228
+ /** The membership service did not answer - not a no. */
229
+ const otaNotThere = (e) => e instanceof OtaMemberError &&
230
+ (e.code === 'timeout' ||
231
+ e.code === 'unreachable' ||
232
+ (typeof e.code === 'number' && e.code >= 500 && !e.envelope));
135
233
  /** The mall did not answer - not a no. */
136
234
  const notThere = (e) => e instanceof MallError &&
137
235
  (e.code === 'timeout' ||
@@ -168,9 +266,9 @@ export const makeAccount = (opts) => {
168
266
  linksAll: new WindowCounter(60_000, now),
169
267
  pages: new WindowCounter(60_000, now),
170
268
  posts: new WindowCounter(10 * 60_000, now),
171
- names: new WindowCounter(10 * 60_000, now),
172
269
  all: new WindowCounter(60_000, now),
173
270
  };
271
+ const nameFailures = new NameFailures(10 * 60_000, now);
174
272
  const refusals = {
175
273
  links: 0,
176
274
  linksIp: 0,
@@ -200,6 +298,82 @@ export const makeAccount = (opts) => {
200
298
  const brand = opts.brand;
201
299
  /** "an Otaless", "a Shangri-La". */
202
300
  const aBrand = `${/^[aeiou]/i.test(brand) ? 'an' : 'a'} ${brand}`;
301
+ // ── Hotel groups' memberships, linked to the account (0.58.0) ────────────
302
+ // ⚠️ OFF UNLESS LISTED: with no `account.memberships`, nothing below is
303
+ // offered, drawn or said - the tools, the card and the pages are as 0.57.1.
304
+ const memberships = (opts.account.memberships ?? []).filter((m) => typeof m?.code === 'string' && /^[a-z0-9_-]{1,32}$/i.test(m.code));
305
+ const linking = memberships.length > 0;
306
+ const groupOf = (code) => typeof code === 'string'
307
+ ? memberships.find((m) => m.code.toLowerCase() === code.trim().toLowerCase())
308
+ : undefined;
309
+ const groupName = (m) => m.name || m.code;
310
+ const ota = makeOtaMembers({
311
+ baseUrl,
312
+ tenant,
313
+ ...(opts.fetch ? { fetch: opts.fetch } : {}),
314
+ now,
315
+ });
316
+ // A request table of their own: a link used does not void the account's sign-in links.
317
+ const linkRequests = createSignIns({ now });
318
+ const linkCsrf = (r) => createHmac('sha256', secretKey).update(`link:${r.codeHash}`).digest('base64url').slice(0, 32);
319
+ /** A linked membership, alive - one whose group session is over is dropped, as an unlink. */
320
+ const liveLink = (s, code) => {
321
+ const l = s.links?.get(code);
322
+ if (!l)
323
+ return undefined;
324
+ if (l.expires > now())
325
+ return l;
326
+ s.links?.delete(code);
327
+ return undefined;
328
+ };
329
+ /** Unlinked: forgotten here, and the group's session ended at the backend (not waited for). */
330
+ const unlink = (s, code) => {
331
+ const l = s.links?.get(code);
332
+ if (!l)
333
+ return false;
334
+ s.links?.delete(code);
335
+ ota
336
+ .signOut({ group: code, ...(l.session ? { session: l.session } : {}), auth: s.tokens.access })
337
+ .catch((e) => log(`[account] a membership's sign-out did not answer (${codeOf(e)})`));
338
+ return true;
339
+ };
340
+ /** "ASR Member (AS82••36)" → "ASR Member": a label with its hidden number taken out. */
341
+ const tierOf = (label) => label
342
+ .replace(/\s*[([(][^)\])]*••[^)\])]*[)\])]/g, '')
343
+ .split(/\s+/)
344
+ .filter((w) => !w.includes('••'))
345
+ .join(' ')
346
+ .trim();
347
+ const membershipRows = (s, forCard) => memberships.map((m) => {
348
+ const l = s ? liveLink(s, m.code) : undefined;
349
+ return {
350
+ group: m.code,
351
+ name: groupName(m),
352
+ ...(m.names?.zh ? { names: { zh: m.names.zh } } : {}),
353
+ linked: !!l,
354
+ // The label has the number in it, hidden but for its ends (`maskLabel`):
355
+ // the model is given the tier alone (总线程 11-09: not even hidden).
356
+ ...(l?.label && (forCard || tierOf(l.label))
357
+ ? { label: forCard ? l.label : tierOf(l.label) }
358
+ : {}),
359
+ // The number, hidden but for its ends, for the card and the page only.
360
+ ...(forCard && l?.numberMasked ? { numberMasked: l.numberMasked } : {}),
361
+ signIn: m.signIn !== false,
362
+ join: m.join === true,
363
+ };
364
+ });
365
+ const membershipsSaid = (s) => {
366
+ if (!linking)
367
+ return '';
368
+ const rows = membershipRows(s, false);
369
+ const linked = rows.filter((r) => r.linked);
370
+ return `Hotel memberships linked to this account: ${linked.length
371
+ ? linked.map((r) => `${r.name}${r.label ? ` · ${r.label}` : ''}`).join('; ')
372
+ : 'none'}. Can be linked: ${rows
373
+ .filter((r) => !r.linked)
374
+ .map((r) => `${r.name} (\`${r.group}\`)`)
375
+ .join(', ') || 'none more'} - ${names.link} gives the guest a one-time page for it.`;
376
+ };
203
377
  // ── Signing in and out ───────────────────────────────────────────────────
204
378
  /** Signed in now, for this conversation: whatever was there before is ended. */
205
379
  const signInWith = (key, member, tokens) => {
@@ -207,11 +381,14 @@ export const makeAccount = (opts) => {
207
381
  if (was)
208
382
  end(was);
209
383
  requests.cancelFor(key);
384
+ linkRequests.cancelFor(key);
210
385
  return store.set(key, member, tokens);
211
386
  };
212
387
  /** A sign-in that is over: its pages closed, its tokens ended at the mall (not waited for). */
213
388
  const end = (s) => {
214
389
  web.dropFor(s.sid);
390
+ for (const code of [...(s.links?.keys() ?? [])])
391
+ unlink(s, code);
215
392
  mall
216
393
  .logout(s.tokens)
217
394
  .catch((e) => log(`[account] the mall's sign-out did not answer (${codeOf(e)})`));
@@ -219,11 +396,16 @@ export const makeAccount = (opts) => {
219
396
  const signOut = (key) => {
220
397
  const was = store.clear(key);
221
398
  requests.cancelFor(key);
399
+ linkRequests.cancelFor(key);
222
400
  if (was)
223
401
  end(was);
224
402
  return was;
225
403
  };
226
- const codeOf = (e) => e instanceof MallError ? String(e.code).slice(0, 16) : e instanceof Error ? e.name : 'error';
404
+ const codeOf = (e) => e instanceof MallError || e instanceof OtaMemberError
405
+ ? String(e.code).slice(0, 16)
406
+ : e instanceof Error
407
+ ? e.name
408
+ : 'error';
227
409
  /**
228
410
  * Still theirs? Asked of the mall at most every five minutes: a token
229
411
  * revoked there - signed out on another device - answers as nobody, and the
@@ -251,9 +433,22 @@ export const makeAccount = (opts) => {
251
433
  const renew = async () => {
252
434
  try {
253
435
  s.tokens = await mall.refresh(s.tokens);
436
+ s.renewFailingSince = undefined;
254
437
  }
255
438
  catch (e) {
256
- throw refused(e) ? GONE : e;
439
+ if (refused(e))
440
+ throw GONE;
441
+ // ⚠️ A BLIP IS SHORT (0.59.0, review C3). The mall's envelope says 500
442
+ // for "no valid buyer" too (apidev, 10-20) - so a 500 here may be a dead
443
+ // refresh token, and kept as a blip it would show the guest signed in
444
+ // for good. Once the access token has lapsed and no renewal has been
445
+ // answered for a quarter of an hour, the sign-in is no use to anyone:
446
+ // it goes, as a refused one does.
447
+ const since = s.renewFailingSince ?? now();
448
+ s.renewFailingSince = since;
449
+ if (s.tokens.accessExpires <= now() && now() - since >= RENEW_GIVE_UP_MS)
450
+ throw GONE;
451
+ throw e;
257
452
  }
258
453
  };
259
454
  const whoIs = () => mall.info(s.tokens).catch((e) => {
@@ -293,7 +488,9 @@ export const makeAccount = (opts) => {
293
488
  }
294
489
  };
295
490
  // ── The tools ────────────────────────────────────────────────────────────
296
- const NO_PRICE = `Being signed in changes no price or room shown here: ${brand} has no member rate here yet.`;
491
+ const NO_PRICE = linking
492
+ ? `Being signed in to ${brand} itself changes no price or room shown here; a hotel group's membership linked to the account (${names.link}) asks that group for its prices as the member.`
493
+ : `Being signed in changes no price or room shown here: ${brand} has no member rate here yet.`;
297
494
  const NEVER_IN_CHAT = 'never in this chat: do not ask for, or accept, a password, an email or a phone number here, and never write back one the guest typed - not even to say which to change';
298
495
  const minutes = Math.round(requests.ttlMs / 60_000);
299
496
  const accountUrl = `${publicUrl}/account`;
@@ -305,9 +502,128 @@ export const makeAccount = (opts) => {
305
502
  const shownFor = (s) => s.shown.displayName ? { displayName: s.shown.displayName } : {};
306
503
  const whoSaid = (s) => s.shown.displayName ? `the ${brand} account of ${s.shown.displayName}` : `${aBrand} account`;
307
504
  const signedInAnswer = (s, lead) => ({
308
- text: `${lead} Signed in to ${whoSaid(s)}. ${NO_PRICE} The guest sees the whole account - its user name, and its email and phone partly hidden - on ${brand}'s account page, ${accountUrl}, in the browser they signed in with, for ${WEB_IDLE_MS / 60_000} minutes after. ${names.signOut} signs them out.`.trim(),
309
- structured: { view: 'account', brand, signedIn: true, account: shownFor(s), accountUrl },
505
+ text: `${lead} Signed in to ${whoSaid(s)}. ${linking ? '' : `${NO_PRICE} `}The guest sees the whole account - its user name, and its email and phone partly hidden - on ${brand}'s account page, ${accountUrl}, in the browser they signed in with, for ${WEB_IDLE_MS / 60_000} minutes after. ${names.signOut} signs them out.${linking ? ` ${membershipsSaid(s)}` : ''}`.trim(),
506
+ structured: {
507
+ view: 'account',
508
+ brand,
509
+ signedIn: true,
510
+ account: shownFor(s),
511
+ accountUrl,
512
+ // What is linked, by group and label - never a membership number.
513
+ ...(linking ? { memberships: membershipRows(s, false) } : {}),
514
+ },
310
515
  });
516
+ /**
517
+ * A one-time page to link a hotel group's membership to the account (0.58.0) -
518
+ * or, `mode: unlink`, the link undone. Only for a conversation signed in to
519
+ * the account: the link is for THAT sign-in (`SignedIn.sid`), and its page
520
+ * opens only in the browser that proves it is that account's (pages, below).
521
+ */
522
+ const linkAnswer = async (args, call) => {
523
+ const { key, noCards } = call;
524
+ const m = groupOf(args.group);
525
+ const listed = memberships.map((x) => `\`${x.code}\` (${groupName(x)})`).join(', ');
526
+ if (!m)
527
+ return {
528
+ text: `No such hotel group to link here. The ones that can be linked: ${listed}.`,
529
+ structured: { view: 'error', brand, code: 'no_such_group' },
530
+ isError: true,
531
+ };
532
+ const s = await checked(key);
533
+ if (!s)
534
+ return {
535
+ text: `Linking a ${groupName(m)} membership needs the guest signed in to ${aBrand} account first: ${names.signIn} gives them a one-time page for that. ${NEVER_IN_CHAT[0]?.toUpperCase()}${NEVER_IN_CHAT.slice(1)}.`,
536
+ structured: { view: 'account', brand, signedIn: false, code: 'not_signed_in' },
537
+ };
538
+ const mode = args.mode === 'unlink' ? 'unlink' : args.mode === 'join' ? 'up' : 'in';
539
+ if (mode === 'unlink') {
540
+ const was = unlink(s, m.code);
541
+ if (was)
542
+ log(`[account] ${tag(key)} unlinked a membership`);
543
+ return {
544
+ ...signedInAnswer(s, ''),
545
+ text: was
546
+ ? `The ${groupName(m)} membership is unlinked from this ${brand} account: its prices here are the standard ones again.`
547
+ : `No ${groupName(m)} membership was linked, so nothing changed.`,
548
+ };
549
+ }
550
+ if (liveLink(s, m.code))
551
+ return {
552
+ ...signedInAnswer(s, ''),
553
+ text: `A ${groupName(m)} membership is already linked to this ${brand} account. To use another, unlink it first.`,
554
+ };
555
+ if ((mode === 'up' && m.join !== true) || (mode === 'in' && m.signIn === false))
556
+ return {
557
+ text: `A ${groupName(m)} membership cannot be ${mode === 'up' ? 'made' : 'linked'} here.`,
558
+ structured: { view: 'error', brand, code: 'not_offered' },
559
+ isError: true,
560
+ };
561
+ if (counters.links.count(`link:${key}`) >= ACCOUNT_LIMITS.linksPerConversation) {
562
+ refusals.links++;
563
+ return {
564
+ text: 'Too many links were asked for in this conversation just now. Wait a few minutes, then ask again.',
565
+ structured: { view: 'error', brand, code: 'too_many_links' },
566
+ isError: true,
567
+ };
568
+ }
569
+ const ip = call.ip ?? 'unknown';
570
+ if (counters.linksIp.count(ip) >= ACCOUNT_LIMITS.linksPerIp ||
571
+ counters.linksAll.count('all') >= ACCOUNT_LIMITS.linksPerMinute) {
572
+ refusals.linksIp++;
573
+ return {
574
+ text: 'Too many sign-ins are being started just now. Try again in a minute.',
575
+ structured: { view: 'error', brand, code: 'busy' },
576
+ isError: true,
577
+ };
578
+ }
579
+ counters.links.add(`link:${key}`);
580
+ counters.linksIp.add(ip);
581
+ counters.linksAll.add('all');
582
+ const lang = langOf(args.lang);
583
+ const made = linkRequests.create({
584
+ key,
585
+ ...(lang ? { lang } : {}),
586
+ words: !!noCards,
587
+ link: { group: m.code, mode, sid: s.sid },
588
+ });
589
+ if (!made)
590
+ return {
591
+ text: 'Too many sign-ins are open just now. Try again in a minute.',
592
+ structured: { view: 'error', brand, code: 'busy' },
593
+ isError: true,
594
+ };
595
+ const url = `${publicUrl}/login?code=${made.code}${mode === 'up' ? '&view=register' : ''}`;
596
+ const expiresAt = new Date(made.expiresAt).toISOString();
597
+ log(`[account] a membership link for ${tag(key)}${noCards ? ' in words' : ''}`);
598
+ const what = mode === 'up'
599
+ ? `join ${groupName(m)} and link the new membership`
600
+ : `link their ${groupName(m)} membership`;
601
+ const typed = `the ${groupName(m)} email (or user name) and password are typed on that page, never in this chat: do not ask for, or accept, them here, and never write back one the guest typed`;
602
+ if (noCards)
603
+ return {
604
+ text: `A one-time page is ready for the guest to ${what} to their ${brand} account: ${url} - ${typed}. The page opens in the browser they signed in to ${brand} with, or asks them to sign in to ${brand} again first. It shows the code ${made.short}: tell the guest it must match the code you give them here, and to close the page if it does not. The link works once, for ${minutes} minutes. When they say they are done, ${names.view} shows what is linked.`,
605
+ structured: {
606
+ view: 'account-link',
607
+ brand,
608
+ group: m.code,
609
+ url,
610
+ shortCode: made.short,
611
+ expiresAt,
612
+ expiresInSeconds: Math.round(linkRequests.ttlMs / 1000),
613
+ },
614
+ };
615
+ return {
616
+ text: `A one-time page is ready for the guest to ${what} to their ${brand} account, opened from the card: ${typed}. The card shows a code the page shows too; the link works once, for ${minutes} minutes.`,
617
+ structured: {
618
+ view: 'account-link',
619
+ brand,
620
+ group: m.code,
621
+ expiresAt,
622
+ expiresInSeconds: Math.round(linkRequests.ttlMs / 1000),
623
+ },
624
+ meta: { [LINK_META_KEY]: { url, shortCode: made.short, expiresAt, group: m.code } },
625
+ };
626
+ };
311
627
  const handle = async (name, args, call) => {
312
628
  const { key, noCards } = call;
313
629
  // The card's own: the same three, by `action`.
@@ -316,8 +632,18 @@ export const makeAccount = (opts) => {
316
632
  ? names.signIn
317
633
  : args.action === 'sign_out'
318
634
  ? names.signOut
319
- : names.view;
320
- return handle(act, args, { ...call, noCards: false, fromCard: true });
635
+ : linking &&
636
+ (args.action === 'link' || args.action === 'join' || args.action === 'unlink')
637
+ ? names.link
638
+ : names.view;
639
+ return handle(act, act === names.link
640
+ ? { ...args, mode: args.action === 'link' ? 'sign_in' : args.action }
641
+ : args, { ...call, noCards: false, fromCard: true });
642
+ }
643
+ if (name === names.link) {
644
+ if (!linking)
645
+ throw new Error(`not an account tool: ${name}`);
646
+ return linkAnswer(args, call);
321
647
  }
322
648
  if (name === names.view) {
323
649
  const s = await checked(key);
@@ -494,6 +820,44 @@ export const makeAccount = (opts) => {
494
820
  },
495
821
  inputSchema: { type: 'object', properties: {} },
496
822
  },
823
+ ...(linking
824
+ ? [
825
+ {
826
+ name: names.link,
827
+ // ⚠️ NOTHING ABOUT THE GUEST IS ASKED FOR HERE - the group's email and
828
+ // password are typed on our page, never in the chat.
829
+ description: `Links one hotel group's loyalty membership to the guest's ${brand} account - or joins that group and links the new membership, or unlinks it - on ${brand}'s own web page: answers with a one-time link and a short code the page shows too. Needs the guest signed in to ${brand}. Takes no personal details. Groups: ${memberships.map((m) => `\`${m.code}\` (${groupName(m)})`).join(', ')}.`,
830
+ annotations: {
831
+ title: 'Link a hotel membership',
832
+ readOnlyHint: false,
833
+ destructiveHint: false,
834
+ idempotentHint: false,
835
+ openWorldHint: true,
836
+ },
837
+ inputSchema: {
838
+ type: 'object',
839
+ properties: {
840
+ group: {
841
+ type: 'string',
842
+ enum: memberships.map((m) => m.code),
843
+ description: 'The hotel group, by its code',
844
+ },
845
+ mode: {
846
+ type: 'string',
847
+ enum: ['sign_in', 'join', 'unlink'],
848
+ description: 'sign_in: link a membership the guest has (the default); join: make one and link it; unlink: undo a link',
849
+ },
850
+ lang: {
851
+ type: 'string',
852
+ enum: ['zh', 'en'],
853
+ description: 'The language the page opens in: zh for a guest writing Chinese, en otherwise.',
854
+ },
855
+ },
856
+ required: ['group'],
857
+ },
858
+ },
859
+ ]
860
+ : []),
497
861
  {
498
862
  name: names.card,
499
863
  // The card's own (app-only, server.ts): never offered to the assistant.
@@ -508,14 +872,26 @@ export const makeAccount = (opts) => {
508
872
  inputSchema: {
509
873
  type: 'object',
510
874
  properties: {
511
- action: { type: 'string', enum: ['sign_in', 'view', 'sign_out'] },
875
+ action: {
876
+ type: 'string',
877
+ enum: linking
878
+ ? ['sign_in', 'view', 'sign_out', 'link', 'join', 'unlink']
879
+ : ['sign_in', 'view', 'sign_out'],
880
+ },
512
881
  lang: { type: 'string', enum: ['zh', 'en'] },
882
+ ...(linking ? { group: { type: 'string', enum: memberships.map((m) => m.code) } } : {}),
513
883
  },
514
884
  required: ['action'],
515
885
  },
516
886
  },
517
887
  ];
518
- const ACCOUNT_VIEWS = ['account-sign-in', 'account', 'account-signed-out', 'error'];
888
+ const ACCOUNT_VIEWS = [
889
+ 'account-sign-in',
890
+ 'account',
891
+ 'account-signed-out',
892
+ 'error',
893
+ ...(linking ? ['account-link'] : []),
894
+ ];
519
895
  const outputSchemas = () => ({
520
896
  [names.card]: {
521
897
  type: 'object',
@@ -530,9 +906,32 @@ export const makeAccount = (opts) => {
530
906
  account: { type: 'object' },
531
907
  accountUrl: STR,
532
908
  code: STR,
909
+ ...(linking ? { memberships: { type: 'array' }, group: STR } : {}),
533
910
  },
534
911
  required: ['view'],
535
912
  },
913
+ ...(linking
914
+ ? {
915
+ [names.link]: {
916
+ type: 'object',
917
+ properties: {
918
+ view: { enum: ['account-link', 'account', 'error'] },
919
+ brand: STR,
920
+ group: STR,
921
+ signedIn: { type: 'boolean' },
922
+ url: STR,
923
+ shortCode: STR,
924
+ expiresAt: STR,
925
+ expiresInSeconds: { type: 'number' },
926
+ account: { type: 'object' },
927
+ accountUrl: STR,
928
+ memberships: { type: 'array' },
929
+ code: STR,
930
+ },
931
+ required: ['view'],
932
+ },
933
+ }
934
+ : {}),
536
935
  [names.signIn]: {
537
936
  type: 'object',
538
937
  properties: {
@@ -559,6 +958,7 @@ export const makeAccount = (opts) => {
559
958
  cardIsRight: { type: 'boolean' },
560
959
  account: { type: 'object' },
561
960
  accountUrl: STR,
961
+ ...(linking ? { memberships: { type: 'array' } } : {}),
562
962
  },
563
963
  required: ['view'],
564
964
  },
@@ -573,9 +973,13 @@ export const makeAccount = (opts) => {
573
973
  required: ['view'],
574
974
  },
575
975
  });
576
- const instructions = (noCards) => noCards
577
- ? `${brand} ACCOUNT: a guest who wants to sign in to their ${brand} account, or create one, is given a one-time page by ${names.signIn}: pass on its link and its code exactly, and say they sign in or create the account on that page. Never ask for, or accept, a password, an email or a phone number in the chat; if the guest types one, never write it back - not even to say which one to change: call it \"the password you typed\" - and tell them to use the page and, as it went into a chat, to choose another. When they say they are done, ${names.view} shows who is signed in - use it only when they ask, never on your own; ${names.signOut} signs them out. Being signed in changes no price here: say nothing of member rates.`
578
- : `${brand} ACCOUNT: the card's Sign in opens ${brand}'s own page, where the guest signs in or creates an account; ${names.signIn} does the same when they ask in words. The card tells you when the guest signs in or out on it - take its word, and do not look again to check. Look at the account (${names.view}) only when the guest asks about it - never on your own, and never beside a list of hotels. Never ask for, or accept, a password, an email or a phone number in the chat; if the guest types one, never write it back - not even to say which one to change: call it \"the password you typed\" - and tell them to use the page and, as it went into a chat, to choose another. ${names.signOut} signs them out. Being signed in changes no price here: say nothing of member rates.`;
976
+ const LINK_SAID = linking
977
+ ? ` HOTEL MEMBERSHIPS: a guest signed in to ${brand} can link a hotel group's loyalty membership to the account - ${memberships.map(groupName).join(', ')} - and that group's prices here are then asked for as the member. ${names.link} gives a one-time page for it (or joins the group, or unlinks); the group's email and password are typed on that page, never in the chat - never ask for or accept them here, and never write one back. Say a price is a member rate only where the answer says so.`
978
+ : '';
979
+ const instructions = (noCards) => (noCards
980
+ ? `${brand} ACCOUNT: a guest who wants to sign in to their ${brand} account, or create one, is given a one-time page by ${names.signIn}: pass on its link and its code exactly, and say they sign in or create the account on that page. Never ask for, or accept, a password, an email or a phone number in the chat; if the guest types one, never write it back - not even to say which one to change: call it \"the password you typed\" - and tell them to use the page and, as it went into a chat, to choose another. When they say they are done, ${names.view} shows who is signed in - use it only when they ask, never on your own; ${names.signOut} signs them out.${linking ? '' : ' Being signed in changes no price here: say nothing of member rates.'}`
981
+ : `${brand} ACCOUNT: the card's Sign in opens ${brand}'s own page, where the guest signs in or creates an account; ${names.signIn} does the same when they ask in words. The card tells you when the guest signs in or out on it - take its word, and do not look again to check. Look at the account (${names.view}) only when the guest asks about it - never on your own, and never beside a list of hotels. Never ask for, or accept, a password, an email or a phone number in the chat; if the guest types one, never write it back - not even to say which one to change: call it \"the password you typed\" - and tell them to use the page and, as it went into a chat, to choose another. ${names.signOut} signs them out.${linking ? '' : ' Being signed in changes no price here: say nothing of member rates.'}`) +
982
+ LINK_SAID;
579
983
  // ── The pages ────────────────────────────────────────────────────────────
580
984
  const send = (c, status, html) => c.html(html, status, PAGE_HEADERS);
581
985
  const langFor = (c, r, form) => langOf(c.req.query('lang')) ??
@@ -645,9 +1049,253 @@ export const makeAccount = (opts) => {
645
1049
  return send(c, 200, statePage(brandPage, lang, 'finished', href));
646
1050
  return send(c, statusOf(state), statePage(brandPage, lang, state, href));
647
1051
  };
1052
+ // ── A hotel group's membership, linked (0.58.0) ──────────────────────────
1053
+ // ⚠️ ONLY IN THE BROWSER OF THE ACCOUNT THE LINK BELONGS TO (总线程 11-06): one
1054
+ // holding that sign-in's cookie, or one that signs in to that account again
1055
+ // here. A link opened anywhere else - forwarded, or made by someone holding
1056
+ // the conversation's trip id - links nothing: a membership could otherwise
1057
+ // be put on somebody else's account, or somebody else's taken onto ours.
1058
+ const linkState = (r) => {
1059
+ const st = linkRequests.state(r, false);
1060
+ if (st !== 'open')
1061
+ return st;
1062
+ // The account's sign-in it was made for is over: so is the link.
1063
+ return store.get(r.key)?.sid === r.link?.sid ? 'open' : 'expired';
1064
+ };
1065
+ const ownerOf = (c, r) => {
1066
+ const at = sessionOf(c);
1067
+ return at.ws && at.s && at.ws.key === r.key && at.s.sid === r.link?.sid
1068
+ ? { id: at.id, s: at.s }
1069
+ : null;
1070
+ };
1071
+ const accountNameOf = (s) => s.shown.displayName || s.shown.userName || '';
1072
+ const groupPage = (c, code, r, s, lang, mode, error, values) => {
1073
+ const m = groupOf(r.link?.group);
1074
+ return send(c, 200, linkGroupPage(brandPage, {
1075
+ lang,
1076
+ short: r.short,
1077
+ code,
1078
+ csrf: linkCsrf(r),
1079
+ words: r.words,
1080
+ group: m ? groupName(m) : String(r.link?.group),
1081
+ accountName: accountNameOf(s),
1082
+ mode: mode === 'up' && m?.join === true ? 'up' : 'in',
1083
+ ...(error ? { error: say(lang, error, m ? groupName(m) : brand) } : {}),
1084
+ ...(values ? { values } : {}),
1085
+ }));
1086
+ };
1087
+ const reauthPage = (c, code, r, lang, error) => {
1088
+ const m = groupOf(r.link?.group);
1089
+ return send(c, 200, linkReauthPage(brandPage, {
1090
+ lang,
1091
+ short: r.short,
1092
+ code,
1093
+ csrf: linkCsrf(r),
1094
+ words: r.words,
1095
+ group: m ? groupName(m) : String(r.link?.group),
1096
+ ...(error ? { error: say(lang, error, brand) } : {}),
1097
+ }));
1098
+ };
1099
+ const linkGet = (c, code, r) => {
1100
+ const lang = langFor(c, r);
1101
+ if (over(c, 'pages', ipOf(c), ACCOUNT_LIMITS.pagesPerIp))
1102
+ return send(c, 429, statePage(brandPage, lang, 'limited', plainHref('/login')));
1103
+ const state = linkState(r);
1104
+ if (state !== 'open')
1105
+ return notOpen(c, code, state, lang, c.req.query('wait') === '1');
1106
+ const owner = ownerOf(c, r);
1107
+ if (!owner)
1108
+ return reauthPage(c, code, r, lang);
1109
+ if (owner.id)
1110
+ setCookie(c, owner.id);
1111
+ const view = c.req.query('view');
1112
+ return groupPage(c, code, r, owner.s, lang, view === 'register' ? 'up' : view === 'in' ? 'in' : (r.link?.mode ?? 'in'));
1113
+ };
1114
+ const linkPost = async (c, body, code, r, lang) => {
1115
+ const state = linkState(r);
1116
+ if (state !== 'open')
1117
+ return notOpen(c, code, state, lang, false);
1118
+ if (!same(body.csrf, linkCsrf(r))) {
1119
+ refusals.csrf++;
1120
+ return send(c, 403, statePage(brandPage, lang, 'checked', linkHref(code)));
1121
+ }
1122
+ if (!linkRequests.tried(r)) {
1123
+ log(`[account] a membership link for ${tag(r.key)} refused after too many tries`);
1124
+ return send(c, 429, statePage(brandPage, lang, 'tries', linkHref(code)));
1125
+ }
1126
+ const m = groupOf(r.link?.group);
1127
+ const s = store.get(r.key);
1128
+ if (!m || !s || s.sid !== r.link?.sid)
1129
+ return notOpen(c, code, 'expired', lang, false);
1130
+ // The account's own sign-in, again: it proves the browser is that account's.
1131
+ if (body.form === 'reauth') {
1132
+ const account = formStr(body.account, LIMITS.account).trim();
1133
+ const password = formStr(body.password, LIMITS.password);
1134
+ if (!account || !password)
1135
+ return reauthPage(c, code, r, lang, 'missing_in');
1136
+ // ⚠️ COUNTED AS A SIGN-IN OF THE ACCOUNT IS (总线程 11-06): by the name -
1137
+ // the SAME `nameFailures` as the sign-in page (C8: only a no from the mall
1138
+ // counts, a success clears the name) - and for everyone.
1139
+ const named = `a:${account.toLowerCase()}`;
1140
+ if (nameFailures.shut(named, ACCOUNT_LIMITS.perName)) {
1141
+ refusals.names++;
1142
+ return reauthPage(c, code, r, lang, 'too_many');
1143
+ }
1144
+ if (over(c, 'all', 'in', ACCOUNT_LIMITS.signInsPerMinute))
1145
+ return send(c, 429, statePage(brandPage, lang, 'limited', linkHref(code)));
1146
+ if (!linkRequests.begin(r))
1147
+ return notOpen(c, code, 'pending', lang, false);
1148
+ if (!nameFailures.enter(named, ACCOUNT_LIMITS.perName)) {
1149
+ linkRequests.reopen(r);
1150
+ refusals.names++;
1151
+ return reauthPage(c, code, r, lang, 'too_many');
1152
+ }
1153
+ let proved = null;
1154
+ let triedOutcome = 'unknown';
1155
+ try {
1156
+ proved = await mall.login({ account, password });
1157
+ triedOutcome = 'ok';
1158
+ }
1159
+ catch (e) {
1160
+ linkRequests.reopen(r);
1161
+ triedOutcome = notThere(e) ? 'unknown' : 'failed';
1162
+ log(`[account] a re-sign-in for a membership link of ${tag(r.key)} refused (${codeOf(e)})`);
1163
+ return reauthPage(c, code, r, lang, notThere(e) ? 'busy' : 'sign_in_failed');
1164
+ }
1165
+ finally {
1166
+ nameFailures.leave(named, triedOutcome);
1167
+ }
1168
+ linkRequests.reopen(r);
1169
+ // Only to prove who: its tokens are ended at once - the account's own sign-in stands.
1170
+ mall.logout(proved.tokens).catch(() => { });
1171
+ const still = store.get(r.key);
1172
+ if (!still || still.sid !== r.link?.sid)
1173
+ return notOpen(c, code, 'expired', lang, false);
1174
+ // ⚠️ ANOTHER ACCOUNT: refused, and nothing of the link's account said (总线程 11-06 (b)).
1175
+ if (!proved.member || proved.member.id !== still.shown.id) {
1176
+ log(`[account] a membership link of ${tag(r.key)} opened by another account: refused`);
1177
+ return reauthPage(c, code, r, lang, 'reauth_other');
1178
+ }
1179
+ const id = web.open(r.key, still.sid);
1180
+ if (id)
1181
+ setCookie(c, id);
1182
+ return groupPage(c, code, r, still, lang, r.link.mode);
1183
+ }
1184
+ const owner = ownerOf(c, r);
1185
+ if (!owner)
1186
+ return reauthPage(c, code, r, lang);
1187
+ const up = body.form === 'join' && m.join === true;
1188
+ const password = formStr(body.password, LIMITS.password);
1189
+ const values = up
1190
+ ? {
1191
+ name: formStr(body.name, 60).trim(),
1192
+ email: formStr(body.email, LIMITS.email).trim(),
1193
+ phone: formStr(body.phone, LIMITS.mobile).trim(),
1194
+ }
1195
+ : { identity: formStr(body.identity, 120).trim() };
1196
+ const again = (error, as = up ? 'up' : 'in', kept = values) => groupPage(c, code, r, owner.s, lang, as, error, kept);
1197
+ const phone = (values.phone ?? '').replace(/[\s().-]/g, '');
1198
+ if (up) {
1199
+ if (!values.name || !values.email || !password)
1200
+ return again('missing_join');
1201
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email ?? ''))
1202
+ return again('bad_email');
1203
+ if (phone && !/^\+\d{6,15}$/.test(phone))
1204
+ return again('bad_mobile');
1205
+ if (password.length < 6)
1206
+ return again('short_password');
1207
+ }
1208
+ else if (!values.identity || !password)
1209
+ return again('missing_link');
1210
+ const who = `${up ? 'j' : 'g'}:${m.code}:${(up ? values.email : values.identity)?.toLowerCase()}`;
1211
+ // The same table as the sign-in's (C8): a wrong guess is counted, a link that works clears it.
1212
+ if (nameFailures.shut(who, ACCOUNT_LIMITS.perName)) {
1213
+ refusals.names++;
1214
+ return again('too_many');
1215
+ }
1216
+ if (over(c, 'all', up ? 'up' : 'in', up ? ACCOUNT_LIMITS.registersPerMinute : ACCOUNT_LIMITS.signInsPerMinute))
1217
+ return send(c, 429, statePage(brandPage, lang, 'limited', linkHref(code)));
1218
+ if (!linkRequests.begin(r))
1219
+ return notOpen(c, code, 'pending', lang, false);
1220
+ if (!nameFailures.enter(who, ACCOUNT_LIMITS.perName)) {
1221
+ linkRequests.reopen(r);
1222
+ refusals.names++;
1223
+ return again('too_many');
1224
+ }
1225
+ let outcome = 'unknown';
1226
+ try {
1227
+ const auth = owner.s.tokens.access;
1228
+ let memberNo;
1229
+ if (up) {
1230
+ try {
1231
+ ({ memberNo } = await ota.register({
1232
+ group: m.code,
1233
+ name: values.name ?? '',
1234
+ email: values.email ?? '',
1235
+ password,
1236
+ ...(phone ? { phone } : {}),
1237
+ auth,
1238
+ }));
1239
+ }
1240
+ catch (e) {
1241
+ linkRequests.reopen(r);
1242
+ outcome = otaNotThere(e) ? 'unknown' : 'failed';
1243
+ log(`[account] a membership for ${tag(r.key)} refused (${codeOf(e)})`);
1244
+ return again(otaNotThere(e) ? 'link_busy' : 'join_failed');
1245
+ }
1246
+ }
1247
+ let link;
1248
+ try {
1249
+ link = await ota.signIn({
1250
+ group: m.code,
1251
+ identity: (up ? values.email : values.identity) ?? '',
1252
+ password,
1253
+ auth,
1254
+ });
1255
+ }
1256
+ catch (e) {
1257
+ linkRequests.reopen(r);
1258
+ outcome = otaNotThere(e) ? 'unknown' : 'failed';
1259
+ log(`[account] a membership link for ${tag(r.key)} refused (${codeOf(e)})`);
1260
+ if (up)
1261
+ return again('joined_not_linked', 'in', { identity: values.email ?? '' });
1262
+ return again(otaNotThere(e) ? 'link_busy' : 'link_failed');
1263
+ }
1264
+ outcome = 'ok';
1265
+ // Still that sign-in, after the backend kept us waiting?
1266
+ const now2 = store.get(r.key);
1267
+ if (!now2 || now2.sid !== r.link?.sid) {
1268
+ linkRequests.reopen(r);
1269
+ ota
1270
+ .signOut({ group: m.code, ...(link.session ? { session: link.session } : {}), auth })
1271
+ .catch(() => { });
1272
+ return notOpen(c, code, 'expired', lang, false);
1273
+ }
1274
+ if (memberNo)
1275
+ link.numberMasked = maskNumber(memberNo);
1276
+ const was = now2.links?.get(m.code);
1277
+ if (was)
1278
+ unlink(now2, m.code);
1279
+ now2.links ??= new Map();
1280
+ now2.links.set(m.code, link);
1281
+ linkRequests.done(r);
1282
+ log(`[account] ${tag(r.key)} linked a ${m.code} membership${up ? ' it made' : ''}`);
1283
+ return send(c, 200, linkedPage(brandPage, {
1284
+ lang,
1285
+ group: groupName(m),
1286
+ ...(link.label ? { label: link.label } : {}),
1287
+ }));
1288
+ }
1289
+ finally {
1290
+ nameFailures.leave(who, outcome);
1291
+ }
1292
+ };
648
1293
  app.get('/login', (c) => {
649
1294
  const code = c.req.query('code') ?? '';
650
1295
  const r = requests.find(code);
1296
+ const lr = r || !linking ? null : linkRequests.find(code);
1297
+ if (lr)
1298
+ return linkGet(c, code, lr);
651
1299
  const lang = langFor(c, r);
652
1300
  if (over(c, 'pages', ipOf(c), ACCOUNT_LIMITS.pagesPerIp))
653
1301
  return send(c, 429, statePage(brandPage, lang, 'limited', plainHref('/login')));
@@ -678,6 +1326,9 @@ export const makeAccount = (opts) => {
678
1326
  refusals.origin++;
679
1327
  return send(c, 403, statePage(brandPage, lang, 'checked', plainHref('/login')));
680
1328
  }
1329
+ const lr = r || !linking ? null : linkRequests.find(code);
1330
+ if (lr)
1331
+ return linkPost(c, body, code, lr, lang);
681
1332
  const state = requests.state(r, isSignedIn(r));
682
1333
  if (state !== 'open' || !r)
683
1334
  return notOpen(c, code, state === 'open' ? 'unknown' : state, lang, false);
@@ -723,11 +1374,15 @@ export const makeAccount = (opts) => {
723
1374
  }
724
1375
  else if (!values.account || !password)
725
1376
  return again('missing_in');
726
- // ⚠️ BY THE NAME TOO (Nexva's member_sign_in): one user name's guesses,
727
- // from however many links and addresses.
1377
+ // ⚠️ BY THE NAME TOO (Nexva's member_sign_in): one user name's WRONG
1378
+ // guesses, from however many links and addresses. Only a no from the mall
1379
+ // counts (C8, robin 11-09); the check here is a look, the try is reserved
1380
+ // below once nothing else can turn this post away.
728
1381
  const who = `${up ? 'r' : 'a'}:${(up ? values.userName : values.account)?.toLowerCase()}`;
729
- if (over(c, 'names', who, ACCOUNT_LIMITS.perName))
1382
+ if (nameFailures.shut(who, ACCOUNT_LIMITS.perName)) {
1383
+ refusals.names++;
730
1384
  return again('too_many');
1385
+ }
731
1386
  // ⚠️ AND FOR EVERYONE (Nexva's review P2-2) - taken only here, after the
732
1387
  // link, the Origin, the form's token and the link's tries have passed, so
733
1388
  // posts with no good link cannot spend it for everyone.
@@ -736,6 +1391,14 @@ export const makeAccount = (opts) => {
736
1391
  // One POST at a time on a link: another meanwhile is told to wait.
737
1392
  if (!requests.begin(r))
738
1393
  return notOpen(c, code, 'pending', lang, false);
1394
+ // The try is reserved with no await since the look above, and settled in
1395
+ // the `finally`: in flight it counts with the failures.
1396
+ if (!nameFailures.enter(who, ACCOUNT_LIMITS.perName)) {
1397
+ requests.reopen(r);
1398
+ refusals.names++;
1399
+ return again('too_many');
1400
+ }
1401
+ let outcome = 'unknown';
739
1402
  let tokens;
740
1403
  let member;
741
1404
  try {
@@ -751,9 +1414,11 @@ export const makeAccount = (opts) => {
751
1414
  }
752
1415
  catch (e) {
753
1416
  requests.reopen(r);
1417
+ outcome = notThere(e) ? 'unknown' : 'failed';
754
1418
  log(`[account] an account for ${tag(r.key)} refused (${codeOf(e)})`);
755
1419
  return again(notThere(e) ? 'busy' : 'register_failed');
756
1420
  }
1421
+ outcome = 'ok';
757
1422
  try {
758
1423
  ({ tokens, member } = await mall.login({ account: values.userName ?? '', password }));
759
1424
  }
@@ -765,15 +1430,20 @@ export const makeAccount = (opts) => {
765
1430
  }
766
1431
  else {
767
1432
  ({ tokens, member } = await mall.login({ account: values.account ?? '', password }));
1433
+ outcome = 'ok';
768
1434
  }
769
1435
  }
770
1436
  catch (e) {
771
1437
  requests.reopen(r);
1438
+ outcome = notThere(e) ? 'unknown' : 'failed';
772
1439
  log(`[account] a sign-in for ${tag(r.key)} refused (${codeOf(e)})`);
773
1440
  // ⚠️ OUR WORDS, NOT THE MALL'S (Nexva's review P3): theirs told a taken
774
1441
  // user name from a wrong password - a way to probe for accounts.
775
1442
  return again(notThere(e) ? 'busy' : 'sign_in_failed');
776
1443
  }
1444
+ finally {
1445
+ nameFailures.leave(who, outcome);
1446
+ }
777
1447
  // The whole account, for its page: their sign-in's user_info is short of
778
1448
  // the email and phone. Theirs only if it is the same member.
779
1449
  const full = await mall.info(tokens).catch(() => null);
@@ -816,7 +1486,12 @@ export const makeAccount = (opts) => {
816
1486
  }
817
1487
  if (at.id)
818
1488
  setCookie(c, at.id);
819
- return send(c, 200, accountPage(brandPage, { lang, shown: at.s.shown, csrf: at.ws.csrf }));
1489
+ return send(c, 200, accountPage(brandPage, {
1490
+ lang,
1491
+ shown: at.s.shown,
1492
+ csrf: at.ws.csrf,
1493
+ ...(linking ? { memberships: membershipRows(at.s, true) } : {}),
1494
+ }));
820
1495
  });
821
1496
  app.post('/account', form, async (c) => {
822
1497
  const body = await readForm(c);
@@ -839,6 +1514,30 @@ export const makeAccount = (opts) => {
839
1514
  refusals.csrf++;
840
1515
  return send(c, 403, statePage(brandPage, lang, 'checked', plainHref('/account')));
841
1516
  }
1517
+ // A hotel group's membership, from the account page itself (0.58.0): this
1518
+ // browser is the account's, so a link is made for it and opened here.
1519
+ const m = linking ? groupOf(body.group) : undefined;
1520
+ if (m && body.action === 'unlink') {
1521
+ if (unlink(at.s, m.code))
1522
+ log(`[account] ${tag(at.ws.key)} unlinked a membership on the account page`);
1523
+ return c.redirect(`${base}/account?lang=${lang}`, 303);
1524
+ }
1525
+ if (m && body.action === 'link') {
1526
+ const mode = body.mode === 'up' && m.join === true ? 'up' : 'in';
1527
+ if (liveLink(at.s, m.code) || (mode === 'in' && m.signIn === false))
1528
+ return c.redirect(`${base}/account?lang=${lang}`, 303);
1529
+ if (over(c, 'links', `link:${at.ws.key}`, ACCOUNT_LIMITS.linksPerConversation))
1530
+ return send(c, 429, statePage(brandPage, lang, 'limited', plainHref('/account')));
1531
+ const made = linkRequests.create({
1532
+ key: at.ws.key,
1533
+ lang,
1534
+ words: false,
1535
+ link: { group: m.code, mode, sid: at.s.sid },
1536
+ });
1537
+ if (!made)
1538
+ return send(c, 429, statePage(brandPage, lang, 'limited', plainHref('/account')));
1539
+ return c.redirect(`${base}/login?code=${encodeURIComponent(made.code)}${mode === 'up' ? '&view=register' : ''}&lang=${lang}`, 303);
1540
+ }
842
1541
  if (body.action !== 'signout')
843
1542
  return send(c, 400, statePage(brandPage, lang, 'checked', plainHref('/account')));
844
1543
  signOut(at.ws.key);
@@ -852,32 +1551,67 @@ export const makeAccount = (opts) => {
852
1551
  names,
853
1552
  tools,
854
1553
  outputSchemas,
855
- has: (name) => name === names.signIn || name === names.view || name === names.signOut || name === names.card,
1554
+ has: (name) => name === names.signIn ||
1555
+ name === names.view ||
1556
+ name === names.signOut ||
1557
+ name === names.card ||
1558
+ (linking && name === names.link),
856
1559
  handle,
857
- meta: (key, cards) => {
1560
+ meta: (key, { cards, ours }) => {
858
1561
  const s = store.get(key);
1562
+ // ⚠️ THE USER NAME ON THE CARD ONLY (robin 11-06: 「登录完,我们卡片不显示
1563
+ // 用户名之类的吗」; 总线程 0.56.1): where a card is drawn its name is the
1564
+ // nickname, else the user name; where none is - and a client may hand
1565
+ // `_meta` to its model - the nickname or nothing, as every answer the
1566
+ // model reads (review P2-2).
1567
+ //
1568
+ // ⚠️ AND ONLY TO ITS OWN CONVERSATION (0.59.0, review C2). A call that names
1569
+ // another conversation's trip is the card's - or risk A's attacker, with
1570
+ // the trip id and a client that says it draws cards, which the server
1571
+ // cannot tell from the card. The user name signs in: handed to them, with
1572
+ // the per-name limit, it locks the member out. Such a call is given the
1573
+ // nickname at most - what the card's own account answer says anyway - and
1574
+ // no `name` at all where there is none; the card keeps the name its
1575
+ // conversation's answers gave it (card.ts `readAccountMeta`).
1576
+ const name = !s
1577
+ ? undefined
1578
+ : cards && ours
1579
+ ? s.shown.displayName || s.shown.userName || ''
1580
+ : s.shown.displayName || undefined;
859
1581
  return {
860
1582
  [ACCOUNT_META_KEY]: {
861
1583
  from: opts.from,
862
- tools: names,
1584
+ // The link tool only where a group can be linked: elsewhere the card is handed what it was before.
1585
+ tools: linking
1586
+ ? names
1587
+ : { signIn: names.signIn, view: names.view, signOut: names.signOut, card: names.card },
863
1588
  signedIn: !!s,
864
- // ⚠️ THE USER NAME ON THE CARD ONLY (robin 11-06: 「登录完,我们卡片不显示
865
- // 用户名之类的吗」; 总线程 0.56.1): where a card is drawn its name is the
866
- // nickname, else the user name; where none is - and a client may hand
867
- // `_meta` to its model - the nickname or nothing, as every answer the
868
- // model reads (review P2-2).
869
- ...(s
870
- ? { name: cards ? s.shown.displayName || s.shown.userName || '' : s.shown.displayName }
871
- : {}),
1589
+ ...(name !== undefined ? { name } : {}),
1590
+ // The hotel memberships, one row a group (0.59.0) - ONLY TO ITS OWN
1591
+ // CONVERSATION (C2: a call naming another's trip is given none), and the
1592
+ // number, hidden, only where a card is drawn.
1593
+ ...(linking && ours && cards ? { memberships: membershipRows(s, true) } : {}),
872
1594
  },
873
1595
  };
874
1596
  },
1597
+ tokenFor: (key, group) => {
1598
+ if (!linking)
1599
+ return undefined;
1600
+ const s = store.get(key);
1601
+ return s ? liveLink(s, group)?.token : undefined;
1602
+ },
1603
+ expired: (key, group) => {
1604
+ const s = store.get(key);
1605
+ if (s?.links?.delete(group))
1606
+ log(`[account] ${tag(key)}: a ${group} membership's session is over`);
1607
+ },
875
1608
  instructions,
876
1609
  mount,
877
1610
  health: () => ({
878
1611
  accountsSignedIn: store.size,
879
1612
  accountLinksOpen: requests.open(),
880
1613
  accountPages: web.size,
1614
+ ...(linking ? { membershipLinksOpen: linkRequests.open() } : {}),
881
1615
  ...Object.fromEntries(Object.entries(refusals).map(([k, v]) => [`accountRefused_${k}`, v])),
882
1616
  }),
883
1617
  };