@curless/hotel-storefront 0.61.1 → 0.63.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 (86) hide show
  1. package/dist/account/fake-ota.d.ts +78 -0
  2. package/dist/account/fake-ota.d.ts.map +1 -0
  3. package/dist/account/fake-ota.js +269 -0
  4. package/dist/account/fake-ota.js.map +1 -0
  5. package/dist/account/index.d.ts +60 -22
  6. package/dist/account/index.d.ts.map +1 -1
  7. package/dist/account/index.js +596 -197
  8. package/dist/account/index.js.map +1 -1
  9. package/dist/account/mask.d.ts +15 -0
  10. package/dist/account/mask.d.ts.map +1 -0
  11. package/dist/account/mask.js +51 -0
  12. package/dist/account/mask.js.map +1 -0
  13. package/dist/account/ota-member.d.ts +99 -14
  14. package/dist/account/ota-member.d.ts.map +1 -1
  15. package/dist/account/ota-member.js +167 -48
  16. package/dist/account/ota-member.js.map +1 -1
  17. package/dist/account/pages.d.ts +101 -1
  18. package/dist/account/pages.d.ts.map +1 -1
  19. package/dist/account/pages.js +238 -9
  20. package/dist/account/pages.js.map +1 -1
  21. package/dist/account/requests.d.ts +12 -2
  22. package/dist/account/requests.d.ts.map +1 -1
  23. package/dist/account/requests.js +4 -3
  24. package/dist/account/requests.js.map +1 -1
  25. package/dist/account/said.js +2 -2
  26. package/dist/account/said.js.map +1 -1
  27. package/dist/account/store.d.ts +16 -15
  28. package/dist/account/store.d.ts.map +1 -1
  29. package/dist/account/store.js +29 -23
  30. package/dist/account/store.js.map +1 -1
  31. package/dist/backend.d.ts +27 -0
  32. package/dist/backend.d.ts.map +1 -1
  33. package/dist/backend.js.map +1 -1
  34. package/dist/card.generated.d.ts +1 -1
  35. package/dist/card.generated.js +2 -2
  36. package/dist/card.generated.js.map +1 -1
  37. package/dist/config.d.ts +23 -0
  38. package/dist/config.d.ts.map +1 -1
  39. package/dist/config.js +10 -0
  40. package/dist/config.js.map +1 -1
  41. package/dist/legal.d.ts.map +1 -1
  42. package/dist/legal.js +34 -22
  43. package/dist/legal.js.map +1 -1
  44. package/dist/otaless/backend.d.ts +50 -4
  45. package/dist/otaless/backend.d.ts.map +1 -1
  46. package/dist/otaless/backend.js +77 -32
  47. package/dist/otaless/backend.js.map +1 -1
  48. package/dist/otaless/booking.d.ts +202 -0
  49. package/dist/otaless/booking.d.ts.map +1 -0
  50. package/dist/otaless/booking.js +1234 -0
  51. package/dist/otaless/booking.js.map +1 -0
  52. package/dist/otaless/client.d.ts +191 -0
  53. package/dist/otaless/client.d.ts.map +1 -1
  54. package/dist/otaless/client.js +185 -17
  55. package/dist/otaless/client.js.map +1 -1
  56. package/dist/otaless/fake.d.ts +73 -0
  57. package/dist/otaless/fake.d.ts.map +1 -1
  58. package/dist/otaless/fake.js +270 -2
  59. package/dist/otaless/fake.js.map +1 -1
  60. package/dist/otaless/make.d.ts +2 -0
  61. package/dist/otaless/make.d.ts.map +1 -1
  62. package/dist/otaless/make.js +49 -1
  63. package/dist/otaless/make.js.map +1 -1
  64. package/dist/server.d.ts +2 -2
  65. package/dist/server.d.ts.map +1 -1
  66. package/dist/server.js +76 -3
  67. package/dist/server.js.map +1 -1
  68. package/dist/surface.d.ts +6 -0
  69. package/dist/surface.d.ts.map +1 -1
  70. package/dist/surface.js +71 -23
  71. package/dist/surface.js.map +1 -1
  72. package/dist/tools.d.ts +230 -52
  73. package/dist/tools.d.ts.map +1 -1
  74. package/dist/tools.js +838 -225
  75. package/dist/tools.js.map +1 -1
  76. package/dist/types.d.ts +32 -0
  77. package/dist/types.d.ts.map +1 -1
  78. package/package.json +1 -1
  79. package/dist/account/fake-mall.d.ts +0 -61
  80. package/dist/account/fake-mall.d.ts.map +0 -1
  81. package/dist/account/fake-mall.js +0 -239
  82. package/dist/account/fake-mall.js.map +0 -1
  83. package/dist/account/mall.d.ts +0 -94
  84. package/dist/account/mall.d.ts.map +0 -1
  85. package/dist/account/mall.js +0 -255
  86. package/dist/account/mall.js.map +0 -1
@@ -1,9 +1,9 @@
1
1
  import { createHmac, randomBytes } from 'node:crypto';
2
2
  import { bodyLimit } from 'hono/body-limit';
3
3
  import { WindowCounter } from '../limits.js';
4
- import { LIMITS, MallError, makeMall, } from './mall.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';
4
+ import { formatMoney } from '../money.js';
5
+ import { LIMITS, OtaMemberError, linkOf, makeOtaMembers, maskNumber, } from './ota-member.js';
6
+ import { PAGE_HEADERS, accountPage, linkGroupPage, linkReauthPage, linkedPage, loginPage, say, signedInPage, statePage, termsDonePage, termsPage, termsStatePage, } from './pages.js';
7
7
  import { CODE, createSignIns, hashOf, same, } from './requests.js';
8
8
  import { AccountStore, WEB_IDLE_MS, WebSessions, shownOf } from './store.js';
9
9
  /**
@@ -32,8 +32,6 @@ export const ACCOUNT_META_KEY = 'curless/account';
32
32
  export const SIGN_IN_META_KEY = 'curless/account-sign-in';
33
33
  /** …and beside a membership link's answer (0.58.0): the link and its group - no code (0.61.0). */
34
34
  export const LINK_META_KEY = 'curless/account-link';
35
- /** The mall is asked at most this often whether a sign-in is still theirs. */
36
- export const CHECK_EVERY_MS = 5 * 60_000;
37
35
  export const COOKIE = '__Host-hotel_account';
38
36
  /** How many of what, and over how long - each refusal said as "too many requests". */
39
37
  export const ACCOUNT_LIMITS = {
@@ -58,6 +56,8 @@ export const ACCOUNT_LIMITS = {
58
56
  };
59
57
  /** The largest form our pages post (Caddy is told 16KB). */
60
58
  export const FORM_MAX_BYTES = 8 * 1024;
59
+ /** A refusal's code on a log line: short, plain characters only. */
60
+ const printableCode = (s) => s.replace(/[^a-z0-9_-]/gi, '').slice(0, 40) || 'other';
61
61
  /** The conversation, on a log line: never the key itself. */
62
62
  const tag = (key) => hashOf(key).slice(0, 8);
63
63
  /** The address the edge proxy saw - the LAST X-Forwarded-For entry (server.ts `clientIp`). */
@@ -106,24 +106,6 @@ export const acceptLang = (h) => {
106
106
  }
107
107
  return 'en';
108
108
  };
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;
127
109
  /**
128
110
  * ⚠️ A POST COMES FROM OUR OWN PAGE (and with the form's token): its Origin is
129
111
  * this site - the public origin, or the Host it was sent to (https; http only
@@ -156,8 +138,8 @@ export const readForm = async (c) => {
156
138
  };
157
139
  /**
158
140
  * ⚠️ 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
141
+ * backend counts - a sign-in that works clears the name, and a backend that did
142
+ * not answer is nobody's mistake. `enter` reserves a try BEFORE the backend is asked
161
143
  * (it counts the tries still in flight with the failures, so a burst of posts
162
144
  * on many links cannot all pass at "7 of 8"); `leave` settles it. No await sits
163
145
  * between the check and the reservation. Idle names are forgotten first when
@@ -223,17 +205,18 @@ export class NameFailures {
223
205
  }
224
206
  }
225
207
  }
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 &&
208
+ /**
209
+ * The backend did not answer - not a no: a timeout, no connection, or an HTTP 5xx
210
+ * that is not their envelope's. The only failures a name's wrong tries do not count.
211
+ */
212
+ const notThere = (e) => e instanceof OtaMemberError &&
230
213
  (e.code === 'timeout' ||
231
214
  e.code === 'unreachable' ||
232
215
  (typeof e.code === 'number' && e.code >= 500 && !e.envelope));
233
216
  /**
234
217
  * The backend answered and said no to the credentials (0.59.1, robin 11-09,
235
218
  * questions #49): an HTTP 4xx, or its envelope's own no (`code: 500` in an HTTP
236
- * 200 is its "wrong", as the mall's). The only answers that are the guest's
219
+ * 200 is its "wrong"). The only answers that are the guest's
237
220
  * mistake for certain - the only ones the page says "the password" for. A
238
221
  * `form`, `not_signed_in`, `wrong_group` or `not_json` is the backend not
239
222
  * confirming (the dev backend answers a form for a good password): the page
@@ -243,18 +226,13 @@ const otaNotThere = (e) => e instanceof OtaMemberError &&
243
226
  * review of 0.60.1): a backend may well say "wrong password" with a form one
244
227
  * day - Spark's shops answer a form to everything now - and an uncounted form
245
228
  * would make this page a way to guess a group member's password, eight at a
246
- * time no more. Only no answer at all (`otaNotThere`) is not counted.
229
+ * time no more. Only no answer at all (`notThere`) is not counted.
247
230
  */
248
- const otaWrong = (e) => e instanceof OtaMemberError &&
231
+ const wrong = (e) => e instanceof OtaMemberError &&
249
232
  typeof e.code === 'number' &&
250
233
  ((e.code >= 400 && e.code < 500) || e.envelope);
251
234
  /** What the backend said for its no, cleaned (said.ts) - undefined when it said nothing. */
252
- const saidBy = (e) => e instanceof MallError || e instanceof OtaMemberError ? e.said : undefined;
253
- /** The mall did not answer - not a no. */
254
- const notThere = (e) => e instanceof MallError &&
255
- (e.code === 'timeout' ||
256
- e.code === 'unreachable' ||
257
- (typeof e.code === 'number' && e.code >= 500 && !e.envelope));
235
+ const saidBy = (e) => e instanceof OtaMemberError ? e.said : undefined;
258
236
  export const makeAccount = (opts) => {
259
237
  const now = opts.now ?? (() => Date.now());
260
238
  const env = opts.env ?? process.env;
@@ -262,8 +240,21 @@ export const makeAccount = (opts) => {
262
240
  const baseUrl = env[`${prefix}_API_URL`] || opts.account.baseUrl;
263
241
  const tenant = env[`${prefix}_TENANT_ID`] || opts.account.tenant;
264
242
  if (!baseUrl || !tenant)
265
- throw new Error(`account: no mall address or tenant (account.baseUrl / account.tenant, or ${prefix}_API_URL / ${prefix}_TENANT_ID)`);
266
- const mall = makeMall({
243
+ throw new Error(`account: no backend address or tenant (account.baseUrl / account.tenant, or ${prefix}_API_URL / ${prefix}_TENANT_ID)`);
244
+ // ⚠️ ONE KIND OF ACCOUNT (0.62.0): the mall's (`source: 'mall'`) is gone, and a
245
+ // config still naming it is a mistake to stop on, not to guess past.
246
+ if (opts.account.source !== 'ota')
247
+ throw new Error(`account: source must be "ota" (the backend's /api/v1/ota/*), not ${JSON.stringify(opts.account.source)}`);
248
+ // The channel the account signs in on - see the top of this file (questions #50).
249
+ const signInProvider = (env[`${prefix}_SIGN_IN_PROVIDER`] ||
250
+ opts.account.signInProvider ||
251
+ 'ascott')
252
+ .trim()
253
+ .toLowerCase();
254
+ if (!/^[a-z0-9_-]{1,32}$/.test(signInProvider))
255
+ throw new Error('account: signInProvider is not a channel code');
256
+ // The backend's `/ota/*`: the account's own sign-in, and its hotel memberships'.
257
+ const ota = makeOtaMembers({
267
258
  baseUrl,
268
259
  tenant,
269
260
  ...(opts.fetch ? { fetch: opts.fetch } : {}),
@@ -272,8 +263,8 @@ export const makeAccount = (opts) => {
272
263
  const log = opts.log ?? ((l) => console.log(l));
273
264
  const names = accountToolNames(opts.prefix);
274
265
  const requests = createSignIns({ now });
275
- // A sign-in forgotten here - left two hours, past its tokens, or pushed out -
276
- // is ended at the mall too (review P3-3).
266
+ // A sign-in forgotten here - left two hours, past its session, or pushed out -
267
+ // is ended at the backend too (review P3-3).
277
268
  const store = new AccountStore(now, (s) => end(s));
278
269
  const web = new WebSessions(now);
279
270
  // The form's token, from a secret of this process: a restart voids open
@@ -353,15 +344,13 @@ export const makeAccount = (opts) => {
353
344
  return undefined;
354
345
  }
355
346
  };
356
- const ota = makeOtaMembers({
357
- baseUrl,
358
- tenant,
359
- ...(opts.fetch ? { fetch: opts.fetch } : {}),
360
- now,
361
- });
362
347
  // A request table of their own: a link used does not void the account's sign-in links.
363
348
  const linkRequests = createSignIns({ now });
364
349
  const linkCsrf = (r) => createHmac('sha256', secretKey).update(`link:${r.codeHash}`).digest('base64url').slice(0, 32);
350
+ // …and one for a group's booking terms (0.63.0): used once, ten minutes at most.
351
+ const TERMS_MS_MAX = 10 * 60_000;
352
+ const termsRequests = createSignIns({ now, ttlMs: TERMS_MS_MAX, perKey: 10 });
353
+ const termsCsrf = (r) => createHmac('sha256', secretKey).update(`terms:${r.codeHash}`).digest('base64url').slice(0, 32);
365
354
  /** A linked membership, alive - one whose group session is over is dropped, as an unlink. */
366
355
  const liveLink = (s, code) => {
367
356
  const l = s.links?.get(code);
@@ -372,17 +361,26 @@ export const makeAccount = (opts) => {
372
361
  s.links?.delete(code);
373
362
  return undefined;
374
363
  };
375
- /** Unlinked: forgotten here, and the group's session ended at the backend (not waited for). */
376
- const unlink = (s, code) => {
364
+ /**
365
+ * Unlinked: forgotten here, and the group's session ended at the backend - the
366
+ * promise of that, or null where there was no link.
367
+ *
368
+ * ⚠️ NOT THE ACCOUNT'S OWN CHANNEL SESSION: a group linked on the channel the
369
+ * account signed in on may come back with the account's own `mcpToken` (one
370
+ * local session, their document) - ending it would end the account's too.
371
+ */
372
+ const dropLink = (s, code) => {
377
373
  const l = s.links?.get(code);
378
374
  if (!l)
379
- return false;
375
+ return null;
380
376
  s.links?.delete(code);
381
- ota
382
- .signOut({ group: code, ...(l.session ? { session: l.session } : {}), auth: s.tokens.access })
377
+ if (l.session && l.session === s.platform.mcpToken)
378
+ return Promise.resolve();
379
+ return ota
380
+ .signOut({ group: code, ...(l.session ? { session: l.session } : {}), auth: l.token })
383
381
  .catch((e) => log(`[account] a membership's sign-out did not answer (${codeOf(e)})`));
384
- return true;
385
382
  };
383
+ const unlink = (s, code) => dropLink(s, code) !== null;
386
384
  /** "ASR Member (AS82••36)" → "ASR Member": a label with its hidden number taken out. */
387
385
  const tierOf = (label) => label
388
386
  .replace(/\s*[([(][^)\])]*••[^)\])]*[)\])]/g, '')
@@ -436,27 +434,38 @@ export const makeAccount = (opts) => {
436
434
  };
437
435
  // ── Signing in and out ───────────────────────────────────────────────────
438
436
  /** Signed in now, for this conversation: whatever was there before is ended. */
439
- const signInWith = (key, member, tokens) => {
437
+ const signInWith = (key, shown, platform) => {
440
438
  const was = store.clear(key);
441
439
  if (was)
442
440
  end(was);
443
441
  requests.cancelFor(key);
444
442
  linkRequests.cancelFor(key);
445
- return store.set(key, member, tokens);
443
+ termsRequests.cancelFor(key);
444
+ return store.set(key, shown, platform);
446
445
  };
447
- /** A sign-in that is over: its pages closed, its tokens ended at the mall (not waited for). */
446
+ /** A channel session of the account's own, ended at the backend (not waited for). */
447
+ const endSession = (p) => ota
448
+ .signOut({
449
+ group: p.provider,
450
+ ...(p.mcpToken ? { session: p.mcpToken } : {}),
451
+ auth: p.access,
452
+ })
453
+ .catch((e) => log(`[account] the backend's sign-out did not answer (${codeOf(e)})`));
454
+ /**
455
+ * A sign-in that is over: its pages closed, its memberships unlinked, its session
456
+ * ended at the backend (not waited for) - ⚠️ THE MEMBERSHIPS FIRST: they share the
457
+ * account's local session (their document), so it is ended only after theirs.
458
+ */
448
459
  const end = (s) => {
449
460
  web.dropFor(s.sid);
450
- for (const code of [...(s.links?.keys() ?? [])])
451
- unlink(s, code);
452
- mall
453
- .logout(s.tokens)
454
- .catch((e) => log(`[account] the mall's sign-out did not answer (${codeOf(e)})`));
461
+ const links = [...(s.links?.keys() ?? [])].map((code) => dropLink(s, code));
462
+ void Promise.allSettled(links).then(() => endSession(s.platform));
455
463
  };
456
464
  const signOut = (key) => {
457
465
  const was = store.clear(key);
458
466
  requests.cancelFor(key);
459
467
  linkRequests.cancelFor(key);
468
+ termsRequests.cancelFor(key);
460
469
  if (was)
461
470
  end(was);
462
471
  return was;
@@ -464,92 +473,18 @@ export const makeAccount = (opts) => {
464
473
  // The code, and the backend's own words for it where it gave any (0.61.1,
465
474
  // questions #55): `refused (500: Password cannot be empty)`. `said` is
466
475
  // already clean (said.ts): one line, 120 characters, nothing of ours in it.
467
- const codeOf = (e) => e instanceof MallError || e instanceof OtaMemberError
476
+ const codeOf = (e) => e instanceof OtaMemberError
468
477
  ? `${String(e.code).slice(0, 16)}${e.said ? `: ${e.said}` : ''}`
469
478
  : e instanceof Error
470
479
  ? e.name
471
480
  : 'error';
472
481
  /**
473
- * Still theirs? Asked of the mall at most every five minutes: a token
474
- * revoked there - signed out on another device - answers as nobody, and the
475
- * sign-in here goes. A blip on the way is not that: kept, asked next time.
482
+ * The conversation's sign-in, while its session stands. ⚠️ NOTHING TO ASK THE
483
+ * BACKEND ANY MORE (0.62.0): their `/ota/*` has no /member/info and no refresh
484
+ * token (「本接口已彻底弃用 refreshToken」) - a sign-in lasts its `expireIn`,
485
+ * held to our own day (`MAX_SESSION_S`), and two idle hours (store.ts).
476
486
  */
477
- // ⚠️ ONE LOOK AT A TIME FOR A CONVERSATION (review P3-5): two at once spent
478
- // the same refresh token, and the mall, rotating it, refused the second -
479
- // read as signed out.
480
- const looking = new Map();
481
- const checked = (key) => {
482
- const s = store.get(key);
483
- if (!s || now() - s.checkedAt < CHECK_EVERY_MS)
484
- return Promise.resolve(s);
485
- const out = looking.get(key);
486
- if (out)
487
- return out;
488
- const p = look(key, s).finally(() => looking.delete(key));
489
- looking.set(key, p);
490
- return p;
491
- };
492
- const look = async (key, s) => {
493
- // ⚠️ ONLY A REFUSED RENEWAL, OR A TOKEN THE MALL SAYS IS NOBODY'S, SIGNS OUT:
494
- // their envelope says 500 for a fault of theirs too (Nexva's audit M-18).
495
- const GONE = new Error('gone');
496
- const renew = async () => {
497
- try {
498
- s.tokens = await mall.refresh(s.tokens);
499
- s.renewFailingSince = undefined;
500
- }
501
- catch (e) {
502
- if (refused(e))
503
- throw GONE;
504
- // ⚠️ A BLIP IS SHORT (0.59.0, review C3). The mall's envelope says 500
505
- // for "no valid buyer" too (apidev, 10-20) - so a 500 here may be a dead
506
- // refresh token, and kept as a blip it would show the guest signed in
507
- // for good. Once the access token has lapsed and no renewal has been
508
- // answered for a quarter of an hour, the sign-in is no use to anyone:
509
- // it goes, as a refused one does.
510
- const since = s.renewFailingSince ?? now();
511
- s.renewFailingSince = since;
512
- if (s.tokens.accessExpires <= now() && now() - since >= RENEW_GIVE_UP_MS)
513
- throw GONE;
514
- throw e;
515
- }
516
- };
517
- const whoIs = () => mall.info(s.tokens).catch((e) => {
518
- if (e instanceof MallError && (e.code === 401 || e.code === 403))
519
- return null;
520
- throw e;
521
- });
522
- try {
523
- if (s.tokens.accessExpires - now() < 60_000)
524
- await renew();
525
- let who = await whoIs();
526
- if (!who || who.id !== s.shown.id) {
527
- await renew();
528
- who = await whoIs();
529
- }
530
- if (!who || who.id !== s.shown.id)
531
- throw GONE;
532
- s.shown = shownOf(who);
533
- s.checkedAt = now();
534
- return s;
535
- }
536
- catch (e) {
537
- // ⚠️ ONLY THE SIGN-IN THIS LOOK WAS FOR (re-review P3-2): signed out and in
538
- // again while the mall kept it waiting, the conversation has a new one,
539
- // which an old token's refusal says nothing about.
540
- const nowIn = store.get(key);
541
- if (nowIn?.sid !== s.sid)
542
- return nowIn;
543
- if (e === GONE) {
544
- log(`[account] ${tag(key)} is not signed in at the mall any more: signed out here`);
545
- signOut(key);
546
- return undefined;
547
- }
548
- // Not now: the sign-in stands, and is asked about again next time.
549
- log(`[account] ${tag(key)}: the mall could not be asked (${codeOf(e)}) - still signed in`);
550
- return nowIn;
551
- }
552
- };
487
+ const checked = (key) => store.get(key);
553
488
  // ── The tools ────────────────────────────────────────────────────────────
554
489
  const NO_PRICE = linking
555
490
  ? `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.`
@@ -568,7 +503,7 @@ export const makeAccount = (opts) => {
568
503
  const shownFor = (s) => (nameOf(s) ? { displayName: nameOf(s) } : {});
569
504
  const whoSaid = (s) => nameOf(s) ? `the ${brand} account of ${nameOf(s)}` : `${aBrand} account`;
570
505
  const signedInAnswer = (s, lead, noCards) => ({
571
- 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, noCards)}` : ''}`.trim(),
506
+ text: `${lead} Signed in to ${whoSaid(s)}. ${linking ? '' : `${NO_PRICE} `}The guest sees the whole account - its user name, and its email 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, noCards)}` : ''}`.trim(),
572
507
  structured: {
573
508
  view: 'account',
574
509
  brand,
@@ -596,7 +531,7 @@ export const makeAccount = (opts) => {
596
531
  isError: true,
597
532
  };
598
533
  const g = groupSaid(m, noCards);
599
- const s = await checked(key);
534
+ const s = checked(key);
600
535
  if (!s)
601
536
  return {
602
537
  text: `Linking a ${g} 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)}.`,
@@ -690,6 +625,50 @@ export const makeAccount = (opts) => {
690
625
  meta: { [LINK_META_KEY]: { url, expiresAt, group: m.code } },
691
626
  };
692
627
  };
628
+ /**
629
+ * A one-time terms request for `ref` (see `Account.termsLink`). It lives as long
630
+ * as the terms (`until`), at most ten minutes. Counted against the conversation
631
+ * like a membership link.
632
+ */
633
+ const makeTerms = (key, ref, lang, until) => {
634
+ const s = store.get(key);
635
+ if (!s)
636
+ return undefined;
637
+ if (counters.links.count(`link:${key}`) >= ACCOUNT_LIMITS.linksPerConversation) {
638
+ refusals.links++;
639
+ return undefined;
640
+ }
641
+ const ends = Date.parse(until);
642
+ if (!Number.isFinite(ends) || ends <= now())
643
+ return undefined;
644
+ const made = termsRequests.create({
645
+ key,
646
+ ...(lang ? { lang } : {}),
647
+ words: true,
648
+ terms: { ref, sid: s.sid },
649
+ });
650
+ if (!made)
651
+ return undefined;
652
+ counters.links.add(`link:${key}`);
653
+ made.request.expires = Math.min(made.request.expires, ends);
654
+ return { code: made.code, expiresAt: made.request.expires };
655
+ };
656
+ const termsLink = (key, ref, lang) => {
657
+ if (!opts.terms)
658
+ return undefined;
659
+ const t = opts.terms.pending(key, ref);
660
+ if (!t)
661
+ return undefined;
662
+ const l = langOf(lang);
663
+ const made = makeTerms(key, ref, l, t.until);
664
+ if (!made)
665
+ return undefined;
666
+ log(`[account] a terms link for ${tag(key)} (${t.group})`);
667
+ return {
668
+ url: `${publicUrl}/account?terms=${made.code}${l ? `&lang=${l}` : ''}`,
669
+ expiresAt: new Date(made.expiresAt).toISOString(),
670
+ };
671
+ };
693
672
  const handle = async (name, args, call) => {
694
673
  const { key, noCards } = call;
695
674
  // The card's own: the same three, by `action`.
@@ -712,7 +691,7 @@ export const makeAccount = (opts) => {
712
691
  return linkAnswer(args, call);
713
692
  }
714
693
  if (name === names.view) {
715
- const s = await checked(key);
694
+ const s = checked(key);
716
695
  if (s)
717
696
  return signedInAnswer(s, '', noCards);
718
697
  const waiting = requests.openFor(key);
@@ -760,7 +739,7 @@ export const makeAccount = (opts) => {
760
739
  }
761
740
  if (name !== names.signIn)
762
741
  throw new Error(`not an account tool: ${name}`);
763
- const s = await checked(key);
742
+ const s = checked(key);
764
743
  if (s)
765
744
  return {
766
745
  ...signedInAnswer(s, '', noCards),
@@ -1133,7 +1112,7 @@ export const makeAccount = (opts) => {
1133
1112
  };
1134
1113
  const ownerOf = (c, r) => {
1135
1114
  const at = sessionOf(c);
1136
- return at.ws && at.s && at.ws.key === r.key && at.s.sid === r.link?.sid
1115
+ return at.ws && at.s && at.ws.key === r.key && at.s.sid === (r.link ?? r.terms)?.sid
1137
1116
  ? { id: at.id, s: at.s }
1138
1117
  : null;
1139
1118
  };
@@ -1204,7 +1183,7 @@ export const makeAccount = (opts) => {
1204
1183
  if (!account || !password)
1205
1184
  return reauthPage(c, code, r, lang, 'missing_in');
1206
1185
  // ⚠️ COUNTED AS A SIGN-IN OF THE ACCOUNT IS (总线程 11-06): by the name -
1207
- // the SAME `nameFailures` as the sign-in page (C8: only a no from the mall
1186
+ // the SAME `nameFailures` as the sign-in page (C8: only a no from the backend
1208
1187
  // counts, a success clears the name) - and for everyone.
1209
1188
  const named = `a:${account.toLowerCase()}`;
1210
1189
  if (nameFailures.shut(named, ACCOUNT_LIMITS.perName)) {
@@ -1223,7 +1202,7 @@ export const makeAccount = (opts) => {
1223
1202
  let proved = null;
1224
1203
  let triedOutcome = 'unknown';
1225
1204
  try {
1226
- proved = await mall.login({ account, password });
1205
+ proved = await ota.signIn({ group: signInProvider, identity: account, password, lang });
1227
1206
  triedOutcome = 'ok';
1228
1207
  }
1229
1208
  catch (e) {
@@ -1233,22 +1212,37 @@ export const makeAccount = (opts) => {
1233
1212
  const said = saidBy(e);
1234
1213
  return said
1235
1214
  ? reauthPage(c, code, r, lang, 'sign_in_refused', said)
1236
- : reauthPage(c, code, r, lang, notThere(e) ? 'busy' : 'sign_in_failed');
1215
+ : reauthPage(c, code, r, lang, notThere(e) ? 'busy' : wrong(e) ? 'sign_in_failed' : 'sign_in_unconfirmed');
1237
1216
  }
1238
1217
  finally {
1239
1218
  nameFailures.leave(named, triedOutcome);
1240
1219
  }
1241
1220
  linkRequests.reopen(r);
1242
- // Only to prove who: its tokens are ended at once - the account's own sign-in stands.
1243
- mall.logout(proved.tokens).catch(() => { });
1244
1221
  const still = store.get(r.key);
1245
- if (!still || still.sid !== r.link?.sid)
1222
+ const same = (p, q) => p.access === q.access || (!!p.mcpToken && p.mcpToken === q.mcpToken);
1223
+ // ⚠️ ANOTHER ACCOUNT: refused, its session ended, and nothing of the link's
1224
+ // account said (总线程 11-06 (b)) - by their member_user id AND user name
1225
+ // (store.ts `shownOf`).
1226
+ const who = shownOf(proved.session, proved.profile, account);
1227
+ if (!still || still.sid !== r.link?.sid) {
1228
+ if (!still || !same(proved.session, still.platform))
1229
+ void endSession(proved.session);
1246
1230
  return notOpen(c, code, 'expired', lang, false);
1247
- // ⚠️ ANOTHER ACCOUNT: refused, and nothing of the link's account said (总线程 11-06 (b)).
1248
- if (!proved.member || proved.member.id !== still.shown.id) {
1231
+ }
1232
+ if (who.id !== still.shown.id) {
1233
+ if (!same(proved.session, still.platform))
1234
+ void endSession(proved.session);
1249
1235
  log(`[account] a membership link of ${tag(r.key)} opened by another account: refused`);
1250
1236
  return reauthPage(c, code, r, lang, 'reauth_other');
1251
1237
  }
1238
+ // ⚠️ THE SAME ACCOUNT: ITS NEWER SESSION IS KEPT, NOT ENDED (0.62.0). Their
1239
+ // document keeps one local session for a member's sign-ins - ending this
1240
+ // one could end the account's own. The older is ended only where it shares
1241
+ // neither token with the newer.
1242
+ const older = still.platform;
1243
+ still.platform = proved.session;
1244
+ if (!same(older, proved.session))
1245
+ void endSession(older);
1252
1246
  const id = web.open(r.key, still.sid);
1253
1247
  if (id)
1254
1248
  setCookie(c, id);
@@ -1297,7 +1291,7 @@ export const makeAccount = (opts) => {
1297
1291
  }
1298
1292
  let outcome = 'unknown';
1299
1293
  try {
1300
- const auth = owner.s.tokens.access;
1294
+ const auth = owner.s.platform.access;
1301
1295
  let memberNo;
1302
1296
  if (up) {
1303
1297
  try {
@@ -1312,33 +1306,39 @@ export const makeAccount = (opts) => {
1312
1306
  }
1313
1307
  catch (e) {
1314
1308
  linkRequests.reopen(r);
1315
- outcome = otaNotThere(e) ? 'unknown' : 'failed';
1309
+ outcome = notThere(e) ? 'unknown' : 'failed';
1316
1310
  log(`[account] a membership for ${tag(r.key)} refused (${codeOf(e)})`);
1317
1311
  const said = saidBy(e);
1318
1312
  if (said)
1319
1313
  return again('join_refused', 'up', values, said);
1320
- return again(otaNotThere(e) ? 'link_busy' : 'join_failed');
1314
+ return again(notThere(e) ? 'link_busy' : 'join_failed');
1321
1315
  }
1322
1316
  }
1323
1317
  let link;
1324
1318
  try {
1325
- link = await ota.signIn({
1319
+ const got = await ota.signIn({
1326
1320
  group: m.code,
1327
1321
  identity: (up ? values.email : values.identity) ?? '',
1328
1322
  password,
1329
1323
  auth,
1324
+ lang,
1330
1325
  });
1326
+ // ⚠️ A LINK NEEDS THE GROUP'S OWN SESSION TOKEN (questions #48, as 0.58.0):
1327
+ // without one there is nothing of the group's to sign out of, or book with.
1328
+ if (!got.session.mcpToken)
1329
+ throw new OtaMemberError('not_signed_in');
1330
+ link = linkOf(m.code, got.session, got.profile, now());
1331
1331
  }
1332
1332
  catch (e) {
1333
1333
  linkRequests.reopen(r);
1334
- outcome = otaNotThere(e) ? 'unknown' : 'failed';
1334
+ outcome = notThere(e) ? 'unknown' : 'failed';
1335
1335
  log(`[account] a membership link for ${tag(r.key)} refused (${codeOf(e)})`);
1336
1336
  const said = saidBy(e);
1337
1337
  if (up)
1338
1338
  return again('joined_not_linked', 'in', { identity: values.email ?? '' }, said);
1339
1339
  if (said)
1340
1340
  return again('link_refused', 'in', values, said);
1341
- return again(otaNotThere(e) ? 'link_busy' : otaWrong(e) ? 'link_failed' : 'link_unconfirmed');
1341
+ return again(notThere(e) ? 'link_busy' : wrong(e) ? 'link_failed' : 'link_unconfirmed');
1342
1342
  }
1343
1343
  outcome = 'ok';
1344
1344
  // Still that sign-in, after the backend kept us waiting?
@@ -1346,17 +1346,30 @@ export const makeAccount = (opts) => {
1346
1346
  if (!now2 || now2.sid !== r.link?.sid) {
1347
1347
  linkRequests.reopen(r);
1348
1348
  ota
1349
- .signOut({ group: m.code, ...(link.session ? { session: link.session } : {}), auth })
1349
+ .signOut({
1350
+ group: m.code,
1351
+ ...(link.session ? { session: link.session } : {}),
1352
+ auth: link.token,
1353
+ })
1350
1354
  .catch(() => { });
1351
1355
  return notOpen(c, code, 'expired', lang, false);
1352
1356
  }
1353
1357
  if (memberNo)
1354
1358
  link.numberMasked = maskNumber(memberNo);
1359
+ // A link there already is replaced - its session ended only where it is not
1360
+ // the one just signed in (one session, their document).
1355
1361
  const was = now2.links?.get(m.code);
1356
- if (was)
1362
+ if (was?.session && was.session === link.session)
1363
+ now2.links?.delete(m.code);
1364
+ else if (was)
1357
1365
  unlink(now2, m.code);
1358
1366
  now2.links ??= new Map();
1359
1367
  now2.links.set(m.code, link);
1368
+ // ⚠️ ONE LOCAL SESSION, AT ITS LONGEST (their document: several channels'
1369
+ // sign-ins share the account's session, renewed to the longest): where the
1370
+ // group came back with the account's own token, the account lasts as long.
1371
+ if (link.token === now2.platform.access && link.expires > now2.platform.expires)
1372
+ now2.platform.expires = link.expires;
1360
1373
  linkRequests.done(r);
1361
1374
  log(`[account] ${tag(r.key)} linked a ${m.code} membership${up ? ' it made' : ''}`);
1362
1375
  return send(c, 200, linkedPage(brandPage, {
@@ -1369,6 +1382,344 @@ export const makeAccount = (opts) => {
1369
1382
  nameFailures.leave(who, outcome);
1370
1383
  }
1371
1384
  };
1385
+ // ── A group's booking terms, read and agreed to (0.63.0, 总线程 11-10) ───────
1386
+ // ⚠️ ON THE EXISTING PATH `/account`, TOLD APART BY ?terms= (Caddy passes fixed paths
1387
+ // only; `/terms` is the legal page). Guarded as the membership link is: only the
1388
+ // browser holding THIS account's sign-in opens it (`ownerOf`), else the same account
1389
+ // signs in again here; a POST comes from our page (Origin) with the request's own
1390
+ // token; one POST at a time (`begin`); used once - agreeing OR declining ends it.
1391
+ // NOTHING OF THE TERMS, THE GUEST OR THE PAYMENT PAGE IS EVER LOGGED.
1392
+ const termsHrefOf = (code) => (l) => `${base}/account?terms=${encodeURIComponent(code)}&lang=${l}`;
1393
+ const termsState = (r) => {
1394
+ const st = termsRequests.state(r, false);
1395
+ if (st !== 'open')
1396
+ return st;
1397
+ return store.get(r.key)?.sid === r.terms?.sid ? 'open' : 'expired';
1398
+ };
1399
+ const termsNotOpen = (c, code, state, lang, wait) => {
1400
+ const href = termsHrefOf(code);
1401
+ if (state === 'pending')
1402
+ return send(c, 202, termsStatePage(brandPage, lang, 'pending', href, href(lang)));
1403
+ if (state === 'tries')
1404
+ return send(c, 429, statePage(brandPage, lang, 'tries', href));
1405
+ const as = state === 'used' ? 'used' : state === 'unknown' ? 'unknown' : 'expired';
1406
+ void wait;
1407
+ return send(c, statusOf(state), termsStatePage(brandPage, lang, as, href));
1408
+ };
1409
+ const groupLabel = (t, lang) => {
1410
+ const m = groupOf(t.group);
1411
+ return t.groupNames?.[lang] ?? (m ? groupIn(m, lang) : t.groupName);
1412
+ };
1413
+ const termsFactsOf = (t, lang) => ({
1414
+ hotel: t.hotelNames?.[lang] ?? t.hotelName,
1415
+ room: t.roomName,
1416
+ checkIn: t.stay.checkIn,
1417
+ checkOut: t.stay.checkOut,
1418
+ rooms: t.rooms,
1419
+ guests: t.stay.guests,
1420
+ total: formatMoney(t.total),
1421
+ });
1422
+ const termsView = (c, code, r, t, lang) => {
1423
+ const logo = logoPath(t.group);
1424
+ return send(c, 200, termsPage(brandPage, {
1425
+ lang,
1426
+ code,
1427
+ csrf: termsCsrf(r),
1428
+ group: groupLabel(t, lang),
1429
+ ...(logo ? { logo } : {}),
1430
+ facts: termsFactsOf(t, lang),
1431
+ text: t.text,
1432
+ until: t.until,
1433
+ }));
1434
+ };
1435
+ const termsReauth = (c, code, r, lang, error, said) => {
1436
+ // Only the group's name before the browser is proved: nothing of the terms.
1437
+ const t = r.terms ? opts.terms?.pending(r.key, r.terms.ref) : undefined;
1438
+ const logo = t ? logoPath(t.group) : undefined;
1439
+ return send(c, 200, linkReauthPage(brandPage, {
1440
+ lang,
1441
+ code,
1442
+ csrf: termsCsrf(r),
1443
+ group: t ? groupLabel(t, lang) : brand,
1444
+ ...(logo ? { logo } : {}),
1445
+ terms: true,
1446
+ ...(error ? { error: say(lang, error, brand) } : {}),
1447
+ ...(error && said ? { said } : {}),
1448
+ }));
1449
+ };
1450
+ const termsGet = (c, code) => {
1451
+ const r = termsRequests.find(code);
1452
+ const lang = langFor(c, r);
1453
+ if (over(c, 'pages', ipOf(c), ACCOUNT_LIMITS.pagesPerIp))
1454
+ return send(c, 429, statePage(brandPage, lang, 'limited', plainHref('/account')));
1455
+ if (!r?.terms || !opts.terms)
1456
+ return termsNotOpen(c, code, 'unknown', lang, false);
1457
+ const state = termsState(r);
1458
+ if (state !== 'open')
1459
+ return termsNotOpen(c, code, state, lang, false);
1460
+ const owner = ownerOf(c, r);
1461
+ if (!owner)
1462
+ return termsReauth(c, code, r, lang);
1463
+ if (owner.id)
1464
+ setCookie(c, owner.id);
1465
+ const t = opts.terms.pending(r.key, r.terms.ref);
1466
+ if (!t)
1467
+ return send(c, 410, termsStatePage(brandPage, lang, 'gone', termsHrefOf(code)));
1468
+ return termsView(c, code, r, t, lang);
1469
+ };
1470
+ /** Used, once - whatever came of it. (Not `done()`: that would end the conversation's other terms links.) */
1471
+ const termsUsed = (r) => {
1472
+ r.state = 'done';
1473
+ r.doneAt = now();
1474
+ };
1475
+ /** Our words for what the group or the tools refused. */
1476
+ const TERMS_ERRORS = {
1477
+ 'sign-in': [
1478
+ '下单需要先登录{g}。回到对话,请助手给你登录{g}的链接。',
1479
+ 'Ordering needs you signed in at {g} first. Go back to your chat and ask for the link to sign in there.',
1480
+ true,
1481
+ ],
1482
+ 'signed-out': [
1483
+ '你在{g}的登录已经退出。请回到对话重新登录{g}。',
1484
+ 'Your sign-in at {g} has ended. Sign in there again from your chat.',
1485
+ true,
1486
+ ],
1487
+ 'session-expired': [
1488
+ '{g}的登录已过期。请回到对话重新登录{g}。',
1489
+ 'Your sign-in at {g} has expired. Sign in there again from your chat.',
1490
+ true,
1491
+ ],
1492
+ guest: [
1493
+ '缺少入住人的姓名或电话。回到对话补上后重新预订。',
1494
+ "The guest's name or phone number is missing. Add it in your chat and book again.",
1495
+ true,
1496
+ ],
1497
+ 'terms-gone': [
1498
+ '这些条款已过期或已用过。',
1499
+ 'These terms have expired or were already used.',
1500
+ true,
1501
+ ],
1502
+ 'price-changed': [
1503
+ '价格和你看到的不一样了,所以没有下单。回到对话重新查价。',
1504
+ 'The price is not the one you were shown, so it was not ordered. Ask for the price again in your chat.',
1505
+ true,
1506
+ ],
1507
+ 'card-only': [
1508
+ '这一步只能在卡片或条款页上完成。',
1509
+ 'This step can only be done on the card or the terms page.',
1510
+ true,
1511
+ ],
1512
+ 'not-offered': ['这里不能同意预订条款。', 'Booking terms cannot be agreed to here.', true],
1513
+ unconfirmed: [
1514
+ '{g}还没有确认订单,现在不知道有没有下单成功。请回到对话,用「我的预订」查看,先不要重复下单。',
1515
+ 'It is not known yet whether {g} took the order. Check My bookings in your chat, and do not order again meanwhile.',
1516
+ false,
1517
+ ],
1518
+ uncertain: [
1519
+ '不确定有没有下单成功。请回到对话,用「我的预订」查看,先不要重复下单。',
1520
+ 'It is not known whether the order went through. Check My bookings in your chat, and do not order again meanwhile.',
1521
+ false,
1522
+ ],
1523
+ };
1524
+ const termsErrorDone = (code, lang, group, logo) => {
1525
+ const e = TERMS_ERRORS[code] ?? [
1526
+ '没能下单。回到对话,请助手再试。',
1527
+ 'The order could not be placed. Go back to your chat and ask the assistant to try again.',
1528
+ true,
1529
+ ];
1530
+ return {
1531
+ kind: 'error',
1532
+ group,
1533
+ ...(logo ? { logo } : {}),
1534
+ said: e[lang === 'zh' ? 0 : 1].replace(/\{g\}/g, group),
1535
+ nothing: e[2],
1536
+ ...(e[2] ? {} : { uncertain: true }),
1537
+ };
1538
+ };
1539
+ const asObj = (v) => v && typeof v === 'object' && !Array.isArray(v) ? v : {};
1540
+ const asStr = (v) => (typeof v === 'string' && v ? v : undefined);
1541
+ const termsPost = async (c, body, code, lang) => {
1542
+ const r = termsRequests.find(code);
1543
+ if (!r?.terms || !opts.terms)
1544
+ return termsNotOpen(c, code, 'unknown', lang, false);
1545
+ const state = termsState(r);
1546
+ if (state !== 'open')
1547
+ return termsNotOpen(c, code, state, lang, false);
1548
+ if (!same(body.csrf, termsCsrf(r))) {
1549
+ refusals.csrf++;
1550
+ return send(c, 403, statePage(brandPage, lang, 'checked', termsHrefOf(code)));
1551
+ }
1552
+ if (!termsRequests.tried(r)) {
1553
+ log(`[account] a terms link for ${tag(r.key)} refused after too many tries`);
1554
+ return send(c, 429, statePage(brandPage, lang, 'tries', termsHrefOf(code)));
1555
+ }
1556
+ const s = store.get(r.key);
1557
+ if (!s || s.sid !== r.terms.sid)
1558
+ return termsNotOpen(c, code, 'expired', lang, false);
1559
+ // The account's own sign-in, again: it proves the browser is that account's.
1560
+ if (body.form === 'reauth') {
1561
+ const account = formStr(body.account, LIMITS.account).trim();
1562
+ const password = formStr(body.password, LIMITS.password);
1563
+ if (!account || !password)
1564
+ return termsReauth(c, code, r, lang, 'missing_in');
1565
+ const named = `a:${account.toLowerCase()}`;
1566
+ if (nameFailures.shut(named, ACCOUNT_LIMITS.perName)) {
1567
+ refusals.names++;
1568
+ return termsReauth(c, code, r, lang, 'too_many');
1569
+ }
1570
+ if (over(c, 'all', 'in', ACCOUNT_LIMITS.signInsPerMinute))
1571
+ return send(c, 429, statePage(brandPage, lang, 'limited', termsHrefOf(code)));
1572
+ if (!termsRequests.begin(r))
1573
+ return termsNotOpen(c, code, 'pending', lang, false);
1574
+ if (!nameFailures.enter(named, ACCOUNT_LIMITS.perName)) {
1575
+ termsRequests.reopen(r);
1576
+ refusals.names++;
1577
+ return termsReauth(c, code, r, lang, 'too_many');
1578
+ }
1579
+ let proved = null;
1580
+ let outcome = 'unknown';
1581
+ try {
1582
+ proved = await ota.signIn({ group: signInProvider, identity: account, password, lang });
1583
+ outcome = 'ok';
1584
+ }
1585
+ catch (e) {
1586
+ termsRequests.reopen(r);
1587
+ outcome = notThere(e) ? 'unknown' : 'failed';
1588
+ log(`[account] a re-sign-in for a terms link of ${tag(r.key)} refused (${codeOf(e)})`);
1589
+ const said = saidBy(e);
1590
+ return said
1591
+ ? termsReauth(c, code, r, lang, 'sign_in_refused', said)
1592
+ : termsReauth(c, code, r, lang, notThere(e) ? 'busy' : wrong(e) ? 'sign_in_failed' : 'sign_in_unconfirmed');
1593
+ }
1594
+ finally {
1595
+ nameFailures.leave(named, outcome);
1596
+ }
1597
+ termsRequests.reopen(r);
1598
+ const still = store.get(r.key);
1599
+ const sameTok = (p, q) => p.access === q.access || (!!p.mcpToken && p.mcpToken === q.mcpToken);
1600
+ const who = shownOf(proved.session, proved.profile, account);
1601
+ if (!still || still.sid !== r.terms.sid) {
1602
+ if (!still || !sameTok(proved.session, still.platform))
1603
+ void endSession(proved.session);
1604
+ return termsNotOpen(c, code, 'expired', lang, false);
1605
+ }
1606
+ if (who.id !== still.shown.id) {
1607
+ if (!sameTok(proved.session, still.platform))
1608
+ void endSession(proved.session);
1609
+ log(`[account] a terms link of ${tag(r.key)} opened by another account: refused`);
1610
+ return termsReauth(c, code, r, lang, 'reauth_other');
1611
+ }
1612
+ const older = still.platform;
1613
+ still.platform = proved.session;
1614
+ if (!sameTok(older, proved.session))
1615
+ void endSession(older);
1616
+ const id = web.open(r.key, still.sid);
1617
+ if (id)
1618
+ setCookie(c, id);
1619
+ const t = opts.terms.pending(r.key, r.terms.ref);
1620
+ if (!t)
1621
+ return send(c, 410, termsStatePage(brandPage, lang, 'gone', termsHrefOf(code)));
1622
+ return termsView(c, code, r, t, lang);
1623
+ }
1624
+ const owner = ownerOf(c, r);
1625
+ if (!owner)
1626
+ return termsReauth(c, code, r, lang);
1627
+ const action = body.action;
1628
+ if (action !== 'agree' && action !== 'decline')
1629
+ return send(c, 400, statePage(brandPage, lang, 'checked', termsHrefOf(code)));
1630
+ if (!termsRequests.begin(r))
1631
+ return termsNotOpen(c, code, 'pending', lang, false);
1632
+ const ref = r.terms.ref;
1633
+ const before = opts.terms.pending(r.key, ref);
1634
+ const groupCode = before?.group ?? '-';
1635
+ const groupName = before ? groupLabel(before, lang) : brand;
1636
+ const logo = before ? logoPath(before.group) : undefined;
1637
+ if (action === 'decline') {
1638
+ termsUsed(r);
1639
+ log(`[account] terms declined k=${tag(r.key)} group=${groupCode} → nothing ordered`);
1640
+ return send(c, 200, termsDonePage(brandPage, lang, code, {
1641
+ kind: 'declined',
1642
+ group: groupName,
1643
+ ...(logo ? { logo } : {}),
1644
+ }));
1645
+ }
1646
+ // ⚠️ AGREE: ONE USE, WHATEVER COMES BACK - the terms are gone at the group's end
1647
+ // before it is sent, and so is this link.
1648
+ let answer;
1649
+ try {
1650
+ answer = await opts.terms.accept(r.key, ref);
1651
+ }
1652
+ catch {
1653
+ answer = { structured: { view: 'error', error: 'uncertain' }, text: '' };
1654
+ }
1655
+ termsUsed(r);
1656
+ const st = answer.structured;
1657
+ const view = asStr(st.view);
1658
+ // The group sent terms again: a new one-time request, its page right away.
1659
+ if (view === 'terms') {
1660
+ const next = Array.isArray(st.terms) ? asObj(st.terms[0]) : {};
1661
+ const nref = asStr(next.ref);
1662
+ const again = nref ? opts.terms.pending(r.key, nref) : undefined;
1663
+ const made = again ? makeTerms(r.key, nref ?? '', r.lang, again.until) : undefined;
1664
+ if (again && made) {
1665
+ const fresh = termsRequests.find(made.code);
1666
+ log(`[account] terms agreed k=${tag(r.key)} group=${groupCode} → terms`);
1667
+ if (fresh)
1668
+ return termsView(c, made.code, fresh, again, lang);
1669
+ }
1670
+ log(`[account] terms agreed k=${tag(r.key)} group=${groupCode} → terms-lost`);
1671
+ return send(c, 200, termsDonePage(brandPage, lang, code, termsErrorDone('terms-gone', lang, groupName, logo)));
1672
+ }
1673
+ const booking = asObj(st.booking);
1674
+ if (view === 'booking' && asStr(booking.hotelName)) {
1675
+ const pay = asObj(booking.payment);
1676
+ const status = asStr(pay.status);
1677
+ const paid = status === 'paid'
1678
+ ? 'paid'
1679
+ : status === 'awaiting' || (!status && asStr(pay.url))
1680
+ ? 'awaiting'
1681
+ : 'confirmed';
1682
+ const stay = asObj(booking.stay);
1683
+ const facts = before
1684
+ ? termsFactsOf(before, lang)
1685
+ : {
1686
+ hotel: asStr(booking.hotelName),
1687
+ checkIn: asStr(stay.checkIn),
1688
+ checkOut: asStr(stay.checkOut),
1689
+ total: asStr(st.total),
1690
+ };
1691
+ log(`[account] terms agreed k=${tag(r.key)} group=${groupCode} → booked${paid === 'awaiting' ? ' (awaiting payment)' : ''}`);
1692
+ const payUrl = asStr(pay.url);
1693
+ const payBy = asStr(pay.payBy);
1694
+ const payByWords = asStr(pay.payByWords);
1695
+ const payHost = asStr(pay.host);
1696
+ const payAmount = asStr(pay.amount);
1697
+ const confirmation = asStr(booking.confirmationCode);
1698
+ return send(c, 200, termsDonePage(brandPage, lang, code, {
1699
+ kind: 'ordered',
1700
+ group: groupName,
1701
+ ...(logo ? { logo } : {}),
1702
+ facts,
1703
+ paid,
1704
+ ...(confirmation && paid !== 'awaiting' ? { code: confirmation } : {}),
1705
+ ...(payHost ? { payHost } : {}),
1706
+ ...(payBy ? { payBy } : {}),
1707
+ ...(payByWords ? { payByWords } : {}),
1708
+ ...(payUrl ? { payUrl } : {}),
1709
+ ...(payAmount ? { payAmount } : {}),
1710
+ }));
1711
+ }
1712
+ // A refusal - or a booking that came back with nothing booked.
1713
+ const failed = Array.isArray(st.failed) ? asObj(st.failed[0]) : {};
1714
+ const errorCode = view === 'error'
1715
+ ? (asStr(st.error) ?? asStr(st.code) ?? 'other')
1716
+ : (asStr(failed.code) ?? 'other');
1717
+ const g = Array.isArray(st.groups) ? asObj(st.groups[0]) : {};
1718
+ const named = asObj(g.names)[lang] ?? g.name;
1719
+ const who = typeof named === 'string' && named ? named : groupName;
1720
+ log(`[account] terms agreed k=${tag(r.key)} group=${groupCode} → ${printableCode(errorCode)}`);
1721
+ return send(c, 200, termsDonePage(brandPage, lang, code, termsErrorDone(errorCode, lang, who, logo)));
1722
+ };
1372
1723
  app.get('/login', (c) => {
1373
1724
  const code = c.req.query('code') ?? '';
1374
1725
  const r = requests.find(code);
@@ -1440,7 +1791,7 @@ export const makeAccount = (opts) => {
1440
1791
  error: errorOf(lang, error),
1441
1792
  ...(said ? { said } : {}),
1442
1793
  }));
1443
- // What the form itself can tell, without asking the mall.
1794
+ // What the form itself can tell, without asking the backend.
1444
1795
  const mobile = (values.mobile ?? '').replace(/[\s().-]/g, '');
1445
1796
  if (up) {
1446
1797
  if (!values.userName || !values.email || !password)
@@ -1455,7 +1806,7 @@ export const makeAccount = (opts) => {
1455
1806
  else if (!values.account || !password)
1456
1807
  return again('missing_in');
1457
1808
  // ⚠️ BY THE NAME TOO (Nexva's member_sign_in): one user name's WRONG
1458
- // guesses, from however many links and addresses. Only a no from the mall
1809
+ // guesses, from however many links and addresses. Only a no from the backend
1459
1810
  // counts (C8, robin 11-09); the check here is a look, the try is reserved
1460
1811
  // below once nothing else can turn this post away.
1461
1812
  const who = `${up ? 'r' : 'a'}:${(up ? values.userName : values.account)?.toLowerCase()}`;
@@ -1479,18 +1830,23 @@ export const makeAccount = (opts) => {
1479
1830
  return again('too_many');
1480
1831
  }
1481
1832
  let outcome = 'unknown';
1482
- let tokens;
1483
- let member;
1833
+ let got;
1834
+ let typed = values.account ?? '';
1484
1835
  try {
1485
1836
  if (up) {
1837
+ let channels;
1486
1838
  try {
1487
- await mall.register({
1839
+ // ⚠️ EVERY CHANNEL AT ONCE (their 聚合模式, total thread 11-10): no
1840
+ // providerCode - the backend opens the account on each channel it has on,
1841
+ // and its own member_user beside.
1842
+ ({ channels } = await ota.registerAccount({
1488
1843
  userName: values.userName ?? '',
1489
1844
  email: values.email ?? '',
1490
1845
  password,
1491
- ...(mobile ? { mobile } : {}),
1492
- ...(values.nickname ? { nickname: values.nickname } : {}),
1493
- });
1846
+ ...(values.nickname ? { name: values.nickname } : {}),
1847
+ ...(mobile ? { phone: mobile } : {}),
1848
+ lang,
1849
+ }));
1494
1850
  }
1495
1851
  catch (e) {
1496
1852
  requests.reopen(r);
@@ -1502,17 +1858,22 @@ export const makeAccount = (opts) => {
1502
1858
  return again(notThere(e) ? 'busy' : 'register_failed');
1503
1859
  }
1504
1860
  outcome = 'ok';
1861
+ // Each channel by its code and whether it took the account - nothing of the guest's.
1862
+ log(`[account] an account was made for ${tag(r.key)} (channels: ${channels.map((x) => `${x.code} ${x.ok ? 'ok' : 'no'}`).join(', ') || 'none said'})`);
1863
+ // Signed in by the EMAIL: the channel it signs in on takes one (Ascott's own
1864
+ // sign-in asks for `identity_field: email`, questions #48).
1865
+ typed = values.email ?? '';
1505
1866
  try {
1506
- ({ tokens, member } = await mall.login({ account: values.userName ?? '', password }));
1867
+ got = await ota.signIn({ group: signInProvider, identity: typed, password, lang });
1507
1868
  }
1508
1869
  catch (e) {
1509
1870
  requests.reopen(r);
1510
1871
  log(`[account] an account was made for ${tag(r.key)}; signing in refused (${codeOf(e)})`);
1511
- return again('registered_not_signed_in', 'in', { account: values.userName ?? '' }, saidBy(e));
1872
+ return again('registered_not_signed_in', 'in', { account: typed }, saidBy(e));
1512
1873
  }
1513
1874
  }
1514
1875
  else {
1515
- ({ tokens, member } = await mall.login({ account: values.account ?? '', password }));
1876
+ got = await ota.signIn({ group: signInProvider, identity: typed, password, lang });
1516
1877
  outcome = 'ok';
1517
1878
  }
1518
1879
  }
@@ -1520,37 +1881,30 @@ export const makeAccount = (opts) => {
1520
1881
  requests.reopen(r);
1521
1882
  outcome = notThere(e) ? 'unknown' : 'failed';
1522
1883
  log(`[account] a sign-in for ${tag(r.key)} refused (${codeOf(e)})`);
1523
- // ⚠️ THE MALL'S OWN WORDS, UNDER A LINE OF OURS THAT GUESSES NOTHING
1884
+ // ⚠️ THE BACKEND'S OWN WORDS, UNDER A LINE OF OURS THAT GUESSES NOTHING
1524
1885
  // (0.61.1, robin: 供应方原文照原样显示; questions #55 - every no is their
1525
1886
  // 500, and our guess 「用户名或密码不对」 was as likely wrong). Nexva's
1526
1887
  // review P3 kept them off the page because they can tell a taken user name
1527
1888
  // from a wrong password; what still bounds that probe is the per-name
1528
1889
  // count above and the sign-ins-per-minute for everyone. No words from
1529
- // them (a timeout, no answer, a fault with nothing said): ours, as before.
1890
+ // them (a timeout, no answer, a fault with nothing said): ours, as before -
1891
+ // and an answer that is no sign-in but no "wrong" either (a form, another
1892
+ // channel) does not blame the password.
1530
1893
  const said = saidBy(e);
1531
1894
  if (said)
1532
1895
  return again('sign_in_refused', 'in', values, said);
1533
- return again(notThere(e) ? 'busy' : 'sign_in_failed');
1896
+ return again(notThere(e) ? 'busy' : wrong(e) ? 'sign_in_failed' : 'sign_in_unconfirmed');
1534
1897
  }
1535
1898
  finally {
1536
1899
  nameFailures.leave(who, outcome);
1537
1900
  }
1538
- // The whole account, for its page: their sign-in's user_info is short of
1539
- // the email and phone. Theirs only if it is the same member.
1540
- const full = await mall.info(tokens).catch(() => null);
1541
- const m = full && (!member || full.id === member.id) ? full : member;
1542
- if (!m) {
1543
- requests.reopen(r);
1544
- mall.logout(tokens).catch(() => { });
1545
- log(`[account] a sign-in for ${tag(r.key)}: the mall named no member`);
1546
- return again('sign_in_failed');
1547
- }
1548
- const s = signInWith(r.key, m, tokens);
1901
+ // ⚠️ WHAT THE SIGN-IN SAID, AND NOTHING ELSE (0.62.0): there is no /member/info.
1902
+ const s = signInWith(r.key, shownOf(got.session, got.profile, typed), got.session);
1549
1903
  // Every place taken by a live sign-in: none is pushed out (review P3-3).
1550
1904
  if (!s) {
1551
1905
  requests.reopen(r);
1552
1906
  refusals.full++;
1553
- mall.logout(tokens).catch(() => { });
1907
+ void endSession(got.session);
1554
1908
  log('[account] a sign-in refused: every place is taken by a live one');
1555
1909
  return again('busy');
1556
1910
  }
@@ -1566,6 +1920,10 @@ export const makeAccount = (opts) => {
1566
1920
  }));
1567
1921
  });
1568
1922
  app.get('/account', (c) => {
1923
+ // A group's booking terms, on this same path (0.63.0): told apart by the query.
1924
+ const termsCode = c.req.query('terms');
1925
+ if (termsCode !== undefined)
1926
+ return termsGet(c, termsCode);
1569
1927
  const lang = langFor(c);
1570
1928
  if (over(c, 'pages', ipOf(c), ACCOUNT_LIMITS.pagesPerIp))
1571
1929
  return send(c, 429, statePage(brandPage, lang, 'limited', plainHref('/account')));
@@ -1613,6 +1971,9 @@ export const makeAccount = (opts) => {
1613
1971
  refusals.origin++;
1614
1972
  return send(c, 403, statePage(brandPage, lang, 'checked', plainHref('/account')));
1615
1973
  }
1974
+ // A group's booking terms (0.63.0): the form's hidden `terms` field, handled first.
1975
+ if (typeof body.terms === 'string')
1976
+ return termsPost(c, body, formStr(body.terms, 64), lang);
1616
1977
  const at = sessionOf(c);
1617
1978
  if (!at.ws || !at.s) {
1618
1979
  if (at.id)
@@ -1677,16 +2038,16 @@ export const makeAccount = (opts) => {
1677
2038
  // name stands with the nickname, and the per-name limit still holds.
1678
2039
  const name = s ? nameOf(s) || undefined : undefined;
1679
2040
  // ⚠️ THE ACCOUNT'S FACTS, FOR A CARD ALONE (0.61.0, robin 11-10: the card's account
1680
- // view is the web page's): the user name, and the email and phone MASKED as the page
1681
- // masks them (store.ts `shownOf`) - never whole, never the real name, never in the
1682
- // words. Only to a session that draws cards: `_meta` may reach the model of one
1683
- // that does not. Whichever conversation the call names, as the hotel memberships'
1684
- // rows are - in claude.ai the card's calls all name the trip.
2041
+ // view is the web page's): the user name, and the email MASKED as the page masks
2042
+ // it (store.ts `shownOf`) - never whole, never in the words. (No phone since
2043
+ // 0.62.0: the sign-in's answer has none.) Only to a session that draws cards:
2044
+ // `_meta` may reach the model of one that does not. Whichever conversation the
2045
+ // call names, as the hotel memberships' rows are - in claude.ai the card's calls
2046
+ // all name the trip.
1685
2047
  const facts = s && cards
1686
2048
  ? {
1687
2049
  ...(s.shown.userName ? { userName: s.shown.userName } : {}),
1688
2050
  ...(s.shown.email ? { email: s.shown.email } : {}),
1689
- ...(s.shown.mobile ? { mobile: s.shown.mobile } : {}),
1690
2051
  }
1691
2052
  : undefined;
1692
2053
  return {
@@ -1717,11 +2078,48 @@ export const makeAccount = (opts) => {
1717
2078
  const s = store.get(key);
1718
2079
  return s ? liveLink(s, group)?.token : undefined;
1719
2080
  },
2081
+ // The backend said the conversation's sign-in at a group is over (a 4012 to a
2082
+ // price; to a booking a 401, or 4012 twice): a linked membership goes - and
2083
+ // where it is the account's own sign-in (its channel, 0.62.0), the account.
1720
2084
  expired: (key, group) => {
1721
2085
  const s = store.get(key);
1722
- if (s?.links?.delete(group))
1723
- log(`[account] ${tag(key)}: a ${group} membership's session is over`);
2086
+ if (!s)
2087
+ return;
2088
+ const code = group.trim().toLowerCase();
2089
+ if (s.links?.delete(code)) {
2090
+ log(`[account] ${tag(key)}: a ${code} membership's session is over`);
2091
+ return;
2092
+ }
2093
+ if (s.platform.provider === code) {
2094
+ log(`[account] ${tag(key)}: the account's own session is over: signed out here`);
2095
+ signOut(key);
2096
+ }
2097
+ },
2098
+ // ⚠️ THE CONVERSATION'S OWN SIGN-IN AT THAT GROUP (see `Account.bookingAuth`).
2099
+ // `account`: their member_user id as the digits they sent (ota-member.ts
2100
+ // `exactId`) - with none given, who `shownOf` says.
2101
+ bookingAuth: (key, group) => {
2102
+ const s = store.get(key);
2103
+ if (!s)
2104
+ return undefined;
2105
+ const code = group.trim().toLowerCase();
2106
+ const account = s.platform.memberUserId || s.shown.id;
2107
+ const l = linking ? liveLink(s, code) : undefined;
2108
+ if (l)
2109
+ return {
2110
+ token: l.token,
2111
+ ...(l.mcpSessionId ? { mcpSessionId: l.mcpSessionId } : {}),
2112
+ account,
2113
+ };
2114
+ if (s.platform.provider !== code)
2115
+ return undefined;
2116
+ return {
2117
+ token: s.platform.access,
2118
+ ...(s.platform.mcpSessionId ? { mcpSessionId: s.platform.mcpSessionId } : {}),
2119
+ account,
2120
+ };
1724
2121
  },
2122
+ termsLink,
1725
2123
  instructions,
1726
2124
  mount,
1727
2125
  health: () => ({
@@ -1729,6 +2127,7 @@ export const makeAccount = (opts) => {
1729
2127
  accountLinksOpen: requests.open(),
1730
2128
  accountPages: web.size,
1731
2129
  ...(linking ? { membershipLinksOpen: linkRequests.open() } : {}),
2130
+ ...(opts.terms ? { termsLinksOpen: termsRequests.open() } : {}),
1732
2131
  ...Object.fromEntries(Object.entries(refusals).map(([k, v]) => [`accountRefused_${k}`, v])),
1733
2132
  }),
1734
2133
  };