@celljs/ta-nearby 4.16.0 → 4.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/host/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  // web-src/nearby-service.ts
2
- import { randomBytes as randomBytes3 } from "node:crypto";
2
+ import { randomBytes as randomBytes4 } from "node:crypto";
3
3
 
4
4
  // ../ta-protocol/esm/common/language.js
5
5
  var TaLanguageUtil;
@@ -41,7 +41,7 @@ var TaLanguageUtil;
41
41
  })(TaLanguageUtil || (TaLanguageUtil = {}));
42
42
 
43
43
  // ../ta-relay/esm/common/relay-faces.js
44
- var FACE_COUNT = 16;
44
+ var FACE_COUNT = 25;
45
45
  var BLUE = "#4285F4";
46
46
  var RED = "#EA4335";
47
47
  var YELLOW = "#FBBC05";
@@ -78,7 +78,16 @@ var LOOKS = [
78
78
  { color: TEAL, eye: WHITE, cheek: CHEEK, accent: "#1B8A84", eyeY: 22.5, gap: 8.4 },
79
79
  { color: PINK, eye: "#4A1428", cheek: "rgba(160, 20, 70, 0.3)", eyeY: 24, gap: 7.4 },
80
80
  { color: LILAC, eye: "#2A1A5E", cheek: CHEEK, eyeY: 25, gap: 8 },
81
- { color: YELLOW, eye: INK, cheek: CHEEK_WARM, eyeY: 25, gap: 7.4 }
81
+ { color: YELLOW, eye: INK, cheek: CHEEK_WARM, eyeY: 25, gap: 7.4 },
82
+ { color: BLUE, eye: WHITE, cheek: CHEEK, eyeY: 19.5, gap: 8 },
83
+ { color: CREAM, eye: "#4A3420", cheek: "rgba(240, 120, 120, 0.5)", eyeY: 23.5, gap: 8 },
84
+ { color: GREEN, eye: WHITE, cheek: CHEEK, eyeY: 21, gap: 8 },
85
+ { color: PINK, eye: "#4A1428", cheek: "rgba(160, 20, 70, 0.3)", eyeY: 19.5, gap: 8.4 },
86
+ { color: RED, eye: WHITE, cheek: CHEEK_DEEP, accent: "#B3261E", eyeY: 20, gap: 8.4 },
87
+ { color: SKY, eye: WHITE, cheek: CHEEK, eyeY: 23.5, gap: 8 },
88
+ { color: VIOLET, eye: WHITE, cheek: CHEEK, accent: "#6B3FD4", eyeY: 22, gap: 8 },
89
+ { color: TEAL, eye: WHITE, cheek: CHEEK, accent: "#1B8A84", eyeY: 25, gap: 7.6 },
90
+ { color: MINT, eye: "#1D3B27", cheek: CHEEK, accent: "#4AAE6C", eyeY: 22.5, gap: 9 }
82
91
  ];
83
92
  function corners(count, radius, cx, cy, inner) {
84
93
  const points = [];
@@ -170,6 +179,52 @@ function shape(face, look) {
170
179
  ]);
171
180
  case 15:
172
181
  return rounded("20,7 35,33 5,33", color, 6);
182
+ case 16:
183
+ return node("path", {
184
+ d: "M20 6.5l12 4.2v8.4c0 7.4-4.9 12.6-12 15.9-7.1-3.3-12-8.5-12-15.9v-8.4Z",
185
+ fill: color,
186
+ stroke: color,
187
+ "stroke-width": 3,
188
+ "stroke-linejoin": "round"
189
+ });
190
+ case 17:
191
+ return rounded("20,7 32.5,17.5 32.5,33 7.5,33 7.5,17.5", color, 4.5);
192
+ case 18:
193
+ return rounded("14,9 26,9 32.5,32 7.5,32", color, 6);
194
+ case 19:
195
+ return node("rect", { x: 4.5, y: 10.5, width: 31, height: 19.5, rx: 9.75, fill: color });
196
+ case 20:
197
+ return node("g", {}, [
198
+ node("rect", { x: 14, y: 5.5, width: 12, height: 4.5, rx: 1.6, fill: accent }),
199
+ node("rect", { x: 14, y: 30.5, width: 12, height: 4.5, rx: 1.6, fill: accent }),
200
+ node("ellipse", { cx: 20, cy: 20.25, rx: 15, ry: 12.25, fill: color })
201
+ ]);
202
+ case 21:
203
+ return node("g", {}, [
204
+ node("circle", { cx: 13.5, cy: 21.5, r: 7, fill: color }),
205
+ node("circle", { cx: 21.5, cy: 16.5, r: 9, fill: color }),
206
+ node("circle", { cx: 28.5, cy: 22.5, r: 6.5, fill: color }),
207
+ node("rect", { x: 5.5, y: 21, width: 29, height: 12, rx: 6, fill: color })
208
+ ]);
209
+ case 22:
210
+ return node("g", {}, [
211
+ node("rect", { x: 12.5, y: 5.5, width: 15, height: 5.5, rx: 2, fill: accent }),
212
+ node("rect", { x: 7.5, y: 9.5, width: 25, height: 25.5, rx: 6.5, fill: color })
213
+ ]);
214
+ case 23:
215
+ return node("g", {}, [
216
+ node("rect", { x: 18.8, y: 3.5, width: 2.4, height: 6, rx: 1.2, fill: accent }),
217
+ node("circle", { cx: 20, cy: 13, r: 6.5, fill: color }),
218
+ node("circle", { cx: 20, cy: 25, r: 11.5, fill: color })
219
+ ]);
220
+ case 24:
221
+ return node("g", {}, [
222
+ node("circle", { cx: 12, cy: 13, r: 5.5, fill: color }),
223
+ node("circle", { cx: 28, cy: 13, r: 5.5, fill: color }),
224
+ node("circle", { cx: 12, cy: 13, r: 2.2, fill: accent }),
225
+ node("circle", { cx: 28, cy: 13, r: 2.2, fill: accent }),
226
+ node("ellipse", { cx: 20, cy: 23.5, rx: 15.5, ry: 11.5, fill: color })
227
+ ]);
173
228
  default:
174
229
  return node("circle", { cx: 20, cy: 21, r: 14.5, fill: color });
175
230
  }
@@ -234,60 +289,6 @@ var FaceUtil;
234
289
  FaceUtil2.art = art;
235
290
  })(FaceUtil || (FaceUtil = {}));
236
291
 
237
- // web-src/nearby-crypto.ts
238
- import { createCipheriv, createDecipheriv, createECDH, createHmac, hkdfSync, randomBytes } from "node:crypto";
239
- var SLOT_MS = 15 * 60000;
240
-
241
- class NearbyKeys {
242
- createdAt;
243
- e;
244
- x;
245
- ecdh;
246
- constructor(createdAt = Date.now()) {
247
- this.createdAt = createdAt;
248
- this.e = randomBytes(9).toString("base64url");
249
- this.ecdh = createECDH("prime256v1");
250
- this.x = this.ecdh.generateKeys().toString("base64url");
251
- }
252
- keyWith(e, x) {
253
- const secret = this.ecdh.computeSecret(Buffer.from(x, "base64url"));
254
- return Buffer.from(hkdfSync("sha256", secret, [this.e, e].sort().join("."), "ta-near/1 seal", 32));
255
- }
256
- }
257
- var NearbyCrypto;
258
- ((NearbyCrypto) => {
259
- function slot(now = Date.now()) {
260
- return Math.floor(now / SLOT_MS);
261
- }
262
- NearbyCrypto.slot = slot;
263
- function mark(identity, slot2) {
264
- return createHmac("sha256", identity).update(`ta-near/1 ${slot2}`).digest().subarray(0, 12).toString("base64url");
265
- }
266
- NearbyCrypto.mark = mark;
267
- function marks(identity, mark2, now = Date.now()) {
268
- const at = slot(now);
269
- return NearbyCrypto.mark(identity, at) === mark2 || NearbyCrypto.mark(identity, at - 1) === mark2;
270
- }
271
- NearbyCrypto.marks = marks;
272
- function seal(key, value) {
273
- const iv = randomBytes(12);
274
- const cipher = createCipheriv("aes-256-gcm", key, iv);
275
- const body = Buffer.concat([cipher.update(JSON.stringify(value), "utf8"), cipher.final(), cipher.getAuthTag()]);
276
- return { i: iv.toString("base64url"), c: body.toString("base64url") };
277
- }
278
- NearbyCrypto.seal = seal;
279
- function open(key, sealed) {
280
- const body = Buffer.from(sealed.c, "base64url");
281
- if (body.length < 16) {
282
- throw new Error("Too short.");
283
- }
284
- const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(sealed.i, "base64url"));
285
- decipher.setAuthTag(body.subarray(body.length - 16));
286
- return JSON.parse(Buffer.concat([decipher.update(body.subarray(0, body.length - 16)), decipher.final()]).toString("utf8"));
287
- }
288
- NearbyCrypto.open = open;
289
- })(NearbyCrypto ||= {});
290
-
291
292
  // web-src/nearby-meet.ts
292
293
  import { createHash } from "node:crypto";
293
294
  var NearbyMeetUtil;
@@ -753,323 +754,479 @@ class NearbyChannel {
753
754
  var NAME = "@celljs/ta-nearby";
754
755
  var NEARBY_PORT = 47232;
755
756
  var NEARBY_VIEW = `${NAME}/nearby`;
756
- var NearbyKeys2;
757
+ var NearbyKeys;
757
758
  ((NearbyKeys) => {
758
759
  NearbyKeys.VISIBLE = "visible";
759
760
  NearbyKeys.STATUS = "status";
760
761
  NearbyKeys.SETTINGS = "settings";
761
762
  NearbyKeys.CARDS = "cards";
762
763
  NearbyKeys.MET = "met";
763
- })(NearbyKeys2 ||= {});
764
+ })(NearbyKeys ||= {});
764
765
  var SHOW_MAX = 600 * 1024;
765
766
 
766
- // web-src/nearby-spot.ts
767
- import { createHash as createHash2, randomBytes as randomBytes2, randomInt } from "node:crypto";
768
-
769
- // ../ta-relay/esm/common/relay-protocol.js
770
- var RELAY_FRAME_CSP = "default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval' https: data: blob:; style-src 'unsafe-inline' https: data:; img-src https: data: blob:; font-src https: data:; media-src https: data: blob:; connect-src 'none'; form-action 'none'";
771
- var RELAY_FRAME_HEADER_CSP = `${RELAY_FRAME_CSP}; frame-ancestors 'self'; sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox`;
772
- var RELAY_SHARE_MAX_BYTES = 8 * 1024 * 1024;
773
- var RELAY_SHARE_CHUNK_BYTES = 192 * 1024;
774
- var RELAY_CONTENT_MAX_BYTES = 8 * 1024 * 1024;
775
- var RelayCloseCode;
776
- (function(RelayCloseCode2) {
777
- RelayCloseCode2[RelayCloseCode2["HOST_OFFLINE"] = 4404] = "HOST_OFFLINE";
778
- RelayCloseCode2[RelayCloseCode2["REFUSED"] = 4401] = "REFUSED";
779
- RelayCloseCode2[RelayCloseCode2["REPLACED"] = 4409] = "REPLACED";
780
- RelayCloseCode2[RelayCloseCode2["CLOSED_BY_HOST"] = 4410] = "CLOSED_BY_HOST";
781
- RelayCloseCode2[RelayCloseCode2["FULL"] = 4429] = "FULL";
782
- RelayCloseCode2[RelayCloseCode2["TIMEOUT"] = 4408] = "TIMEOUT";
783
- })(RelayCloseCode || (RelayCloseCode = {}));
784
- var RELAY_PING = "ping";
785
- var RELAY_HUB_MAX_VALUE = 96 * 1024;
786
- var RELAY_HUB_MAX_STATE = 3 * 1024 * 1024;
767
+ // web-src/nearby-crypto.ts
768
+ import { createCipheriv, createDecipheriv, createECDH, createHmac, hkdfSync, randomBytes } from "node:crypto";
769
+ var SLOT_MS = 15 * 60000;
787
770
 
788
- // ../ta-relay/esm/common/relay-spot.js
789
- var RELAY_SPOT_PATH = "/v1/spot/";
790
- var RELAY_SPOT_JOIN_MS = 10 * 60000;
791
- var RELAY_SPOT_TRIES = 10;
792
- var RELAY_SPOT_TRIES_MS = 10 * 60000;
793
- var RelaySpotCloseCode;
794
- (function(RelaySpotCloseCode2) {
795
- RelaySpotCloseCode2[RelaySpotCloseCode2["BAD"] = 4400] = "BAD";
796
- RelaySpotCloseCode2[RelaySpotCloseCode2["NONE"] = 4404] = "NONE";
797
- RelaySpotCloseCode2[RelaySpotCloseCode2["LATE"] = 4410] = "LATE";
798
- RelaySpotCloseCode2[RelaySpotCloseCode2["FULL"] = 4429] = "FULL";
799
- RelaySpotCloseCode2[RelaySpotCloseCode2["TRIES"] = 4428] = "TRIES";
800
- })(RelaySpotCloseCode || (RelaySpotCloseCode = {}));
801
- var RelaySpotTries;
802
- (function(RelaySpotTries2) {
803
- function keyOf(address) {
804
- const ip = (address !== null && address !== undefined ? address : "").trim().replace(/^::ffff:/i, "");
805
- if (!ip.includes(":")) {
806
- return ip || "unknown";
807
- }
808
- const [head, tail = ""] = ip.toLowerCase().split("::");
809
- const groups = head ? head.split(":") : [];
810
- const rest = tail ? tail.split(":") : [];
811
- const full = [...groups, ...Array(Math.max(0, 8 - groups.length - rest.length)).fill("0"), ...rest];
812
- return `${full.slice(0, 4).map((group) => group.replace(/^0+(?=.)/, "")).join(":")}::/64`;
813
- }
814
- RelaySpotTries2.keyOf = keyOf;
815
- function recent(fails, now) {
816
- return fails.filter((at) => now - at < RELAY_SPOT_TRIES_MS);
817
- }
818
- RelaySpotTries2.recent = recent;
819
- function blocked(fails, now) {
820
- return recent(fails, now).length >= RELAY_SPOT_TRIES;
771
+ class NearbyKeys2 {
772
+ createdAt;
773
+ e;
774
+ x;
775
+ ecdh;
776
+ constructor(createdAt = Date.now()) {
777
+ this.createdAt = createdAt;
778
+ this.e = randomBytes(9).toString("base64url");
779
+ this.ecdh = createECDH("prime256v1");
780
+ this.x = this.ecdh.generateKeys().toString("base64url");
821
781
  }
822
- RelaySpotTries2.blocked = blocked;
823
- function until(fails, now) {
824
- const kept = recent(fails, now).sort((a, b) => a - b);
825
- return kept.length >= RELAY_SPOT_TRIES ? kept[kept.length - RELAY_SPOT_TRIES] + RELAY_SPOT_TRIES_MS : now;
782
+ keyWith(e, x) {
783
+ const secret = this.ecdh.computeSecret(Buffer.from(x, "base64url"));
784
+ return Buffer.from(hkdfSync("sha256", secret, [this.e, e].sort().join("."), "ta-near/1 seal", 32));
826
785
  }
827
- RelaySpotTries2.until = until;
828
- })(RelaySpotTries || (RelaySpotTries = {}));
829
-
830
- // web-src/nearby-spot.ts
831
- var ANSWER_MS = 6000;
832
- var PING_MS = 30000;
833
- var NearbySpotUtil;
834
- ((NearbySpotUtil) => {
835
- function code() {
836
- return String(randomInt(0, 1e6)).padStart(6, "0");
786
+ }
787
+ var NearbyCrypto;
788
+ ((NearbyCrypto) => {
789
+ function slot(now = Date.now()) {
790
+ return Math.floor(now / SLOT_MS);
837
791
  }
838
- NearbySpotUtil.code = code;
839
- function valid(code2) {
840
- return typeof code2 === "string" && /^\d{6}$/.test(code2);
792
+ NearbyCrypto.slot = slot;
793
+ function mark(identity, slot2) {
794
+ return createHmac("sha256", identity).update(`ta-near/1 ${slot2}`).digest().subarray(0, 12).toString("base64url");
841
795
  }
842
- NearbySpotUtil.valid = valid;
843
- function id(code2) {
844
- return createHash2("sha256").update(`ta-near/1 spot ${code2}`).digest().subarray(0, 16).toString("base64url");
796
+ NearbyCrypto.mark = mark;
797
+ function marks(identity, mark2, now = Date.now()) {
798
+ const at = slot(now);
799
+ return NearbyCrypto.mark(identity, at) === mark2 || NearbyCrypto.mark(identity, at - 1) === mark2;
845
800
  }
846
- NearbySpotUtil.id = id;
847
- function url(relay, code2) {
848
- return relay.replace(/\/+$/, "").replace(/^http/, "ws") + RELAY_SPOT_PATH + id(code2);
801
+ NearbyCrypto.marks = marks;
802
+ function seal(key, value) {
803
+ const iv = randomBytes(12);
804
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
805
+ const body = Buffer.concat([cipher.update(JSON.stringify(value), "utf8"), cipher.final(), cipher.getAuthTag()]);
806
+ return { i: iv.toString("base64url"), c: body.toString("base64url") };
849
807
  }
850
- NearbySpotUtil.url = url;
851
- function until(opened) {
852
- return opened + RELAY_SPOT_JOIN_MS;
808
+ NearbyCrypto.seal = seal;
809
+ function open(key, sealed) {
810
+ const body = Buffer.from(sealed.c, "base64url");
811
+ if (body.length < 16) {
812
+ throw new Error("Too short.");
813
+ }
814
+ const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(sealed.i, "base64url"));
815
+ decipher.setAuthTag(body.subarray(body.length - 16));
816
+ return JSON.parse(Buffer.concat([decipher.update(body.subarray(0, body.length - 16)), decipher.final()]).toString("utf8"));
853
817
  }
854
- NearbySpotUtil.until = until;
855
- })(NearbySpotUtil ||= {});
818
+ NearbyCrypto.open = open;
819
+ })(NearbyCrypto ||= {});
856
820
 
857
- class NearbySpot {
858
- code;
859
- mine;
860
- handlers;
861
- socket;
862
- ping;
863
- pending = new Map;
864
- opened = 0;
865
- constructor(code, mine, handlers) {
866
- this.code = code;
867
- this.mine = mine;
868
- this.handlers = handlers;
821
+ // web-src/nearby-service-base.ts
822
+ var GONE_MS = 1e4;
823
+ var INVITE_MS = 10 * 60000;
824
+ var GATHER_MS = 5 * 60000;
825
+ var PROPOSE_GAP_MS = 2 * 60 * 60000;
826
+ var SKEW_MS = 5 * 60000;
827
+ var TICK_MS = 2000;
828
+ var IDENTITY_MS = 1e4;
829
+ var INITIATIVE = "@celljs/ta-initiative";
830
+ var NOTIFY = "@celljs/ta-notify";
831
+ var ROOM_KIND = "nearby.room";
832
+ var MEET_KIND = "nearby.meet";
833
+ var GREET_KIND = "nearby.greet";
834
+ var MEET_A_DAY = 3;
835
+ var MET_MS = 30 * 24 * 60 * 60000;
836
+ var ROOMS_KIND = "ta-rooms";
837
+
838
+ class NearbyServiceBase {
839
+ host;
840
+ options;
841
+ visible;
842
+ settings = {};
843
+ keys;
844
+ previous;
845
+ beacon;
846
+ channel;
847
+ heard = new Map;
848
+ sent = new Map;
849
+ received = new Map;
850
+ identity;
851
+ identityAt = 0;
852
+ friends = [];
853
+ friendsAt = 0;
854
+ error;
855
+ timer;
856
+ published = "";
857
+ proposedAt = 0;
858
+ madeAt = 0;
859
+ defined = false;
860
+ stopRooms;
861
+ spot;
862
+ shown;
863
+ cards = {};
864
+ met = {};
865
+ greets = new Map;
866
+ hellos = new Map;
867
+ greeted = new Map;
868
+ kinds = new Set;
869
+ spotTimer;
870
+ now;
871
+ constructor(host, options = {}) {
872
+ this.host = host;
873
+ this.options = options;
874
+ this.now = options.now ?? Date.now;
869
875
  }
870
- connect(relay) {
871
- return new Promise((resolve, reject) => {
872
- let ready = false;
873
- const socket = new WebSocket(NearbySpotUtil.url(relay, this.code));
874
- this.socket = socket;
875
- socket.onopen = () => socket.send(JSON.stringify({ t: this.mine ? "open" : "join" }));
876
- socket.onmessage = (event) => {
877
- if (typeof event.data !== "string" || event.data.length < 2 || event.data[0] !== "{") {
878
- return;
879
- }
880
- let message;
881
- try {
882
- message = JSON.parse(event.data);
883
- } catch {
884
- return;
885
- }
886
- if (message.t === "ready") {
887
- ready = true;
888
- this.opened = message.opened;
889
- this.ping = setInterval(() => this.send(RELAY_PING), PING_MS);
890
- resolve(message.opened);
891
- } else if (message.t === "here") {
892
- this.handlers.here(message.b);
893
- } else if (message.t === "gone") {
894
- this.handlers.gone(message.e);
895
- } else if (message.t === "miss") {
896
- this.settle(message.id, undefined, new Error("No longer there."));
897
- } else if (message.t === "frame") {
898
- if (message.re) {
899
- this.settle(message.id, message.f);
900
- } else {
901
- this.handlers.frame(message.from, message.f).then((answer) => {
902
- if (answer) {
903
- this.send(JSON.stringify({ t: "to", to: message.from, id: message.id, f: answer, re: true }));
904
- }
905
- });
906
- }
907
- }
908
- };
909
- socket.onclose = (event) => {
910
- clearInterval(this.ping);
911
- for (const id of [...this.pending.keys()]) {
912
- this.settle(id, undefined, new Error("The spot closed."));
913
- }
914
- if (!ready) {
915
- reject(new NearbySpotError(event.code));
916
- } else if (this.socket === socket) {
917
- this.socket = undefined;
918
- this.handlers.closed(this);
919
- }
920
- };
921
- socket.onerror = () => {
922
- return;
923
- };
924
- });
925
- }
926
- here(beacon) {
927
- this.send(JSON.stringify({ t: "here", b: beacon }));
928
- }
929
- request(to, frame) {
930
- const id = randomBytes2(9).toString("base64url");
931
- return new Promise((resolve, reject) => {
932
- const timer = setTimeout(() => this.settle(id, undefined, new Error("No answer.")), ANSWER_MS);
933
- this.pending.set(id, { resolve, reject, timer });
934
- this.send(JSON.stringify({ t: "to", to, id, f: frame }));
935
- });
876
+ async setVisible(on, minutes) {
877
+ if (!on) {
878
+ this.close();
879
+ await this.host.setExtensionData(NAME, NearbyKeys.VISIBLE, null);
880
+ return this.publish(true);
881
+ }
882
+ const now = this.now();
883
+ const visible = { since: now, ...typeof minutes === "number" && minutes > 0 ? { until: now + Math.round(minutes) * 60000 } : {} };
884
+ await this.host.setExtensionData(NAME, NearbyKeys.VISIBLE, visible);
885
+ this.close();
886
+ await this.open(visible);
887
+ return this.status();
936
888
  }
937
- close() {
938
- clearInterval(this.ping);
939
- const socket = this.socket;
940
- this.socket = undefined;
889
+ async open(visible) {
890
+ this.visible = visible;
891
+ this.error = undefined;
892
+ await this.loadIdentity();
893
+ this.keys = new NearbyKeys2(this.now());
894
+ const channel = new NearbyChannel((frame) => this.receive(frame));
895
+ const port = Number(process.env.TA_NEARBY_PORT) || this.options.port || NEARBY_PORT;
896
+ const beacon = new NearbyBeacon({ port, targets: this.options.targets, intervalMs: this.options.intervalMs }, (data, address) => this.hear(data, address));
941
897
  try {
942
- socket?.close(1000, "Bye.");
943
- } catch {}
944
- }
945
- send(text) {
946
- if (this.socket?.readyState === 1) {
947
- this.socket.send(text);
898
+ await channel.start();
899
+ await beacon.start(() => this.beaconData(channel.port));
900
+ this.channel = channel;
901
+ this.beacon = beacon;
902
+ } catch (error) {
903
+ channel.stop();
904
+ beacon.stop();
905
+ this.error = error instanceof Error ? error.message : String(error);
948
906
  }
907
+ clearInterval(this.timer);
908
+ this.timer = setInterval(() => void this.tick(), TICK_MS);
909
+ this.timer.unref?.();
910
+ await this.publish(true);
949
911
  }
950
- settle(id, frame, error) {
951
- const pending = this.pending.get(id);
952
- if (pending) {
953
- this.pending.delete(id);
954
- clearTimeout(pending.timer);
955
- if (error) {
956
- pending.reject(error);
957
- } else {
958
- pending.resolve(frame);
959
- }
960
- }
912
+ close() {
913
+ this.leaveSpot();
914
+ clearInterval(this.timer);
915
+ this.timer = undefined;
916
+ this.beacon?.stop();
917
+ this.channel?.stop();
918
+ this.beacon = undefined;
919
+ this.channel = undefined;
920
+ this.visible = undefined;
921
+ this.keys = undefined;
922
+ this.previous = undefined;
923
+ this.heard.clear();
961
924
  }
962
- }
963
-
964
- class NearbySpotError extends Error {
965
- code;
966
- constructor(code) {
967
- super(NearbySpotError.REASONS[code] ?? "unreachable");
968
- this.code = code;
925
+ beaconData(port) {
926
+ const keys = this.keys;
927
+ return {
928
+ t: "ta-near",
929
+ v: 1,
930
+ e: keys.e,
931
+ n: this.selfName(),
932
+ f: this.identity ? FaceUtil.of(this.identity.id) : 0,
933
+ ...this.identity?.look ? { l: this.identity.look } : {},
934
+ p: port,
935
+ a: NearbyNetUtil.addresses(),
936
+ x: keys.x,
937
+ h: NearbyCrypto.mark(this.identity?.id ?? "", NearbyCrypto.slot(this.now())),
938
+ ...this.offers().length ? { o: this.offers() } : {},
939
+ ...this.meets() ? { m: 1 } : {}
940
+ };
969
941
  }
970
- static REASONS = {
971
- [RelaySpotCloseCode.NONE]: "none",
972
- [RelaySpotCloseCode.LATE]: "late",
973
- [RelaySpotCloseCode.FULL]: "full",
974
- [RelaySpotCloseCode.TRIES]: "tries"
975
- };
976
- }
977
-
978
- // web-src/server-texts.ts
979
- var NearbyTexts;
980
- ((NearbyTexts) => {
981
- function language(env = process.env) {
982
- return TaLanguageUtil.of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG || "");
942
+ offers() {
943
+ return [...this.settings.show !== "off" ? ["show"] : [], ...this.settings.work ? ["work"] : []];
983
944
  }
984
- NearbyTexts.language = language;
985
- function who(peer) {
986
- if (peer.friend) {
987
- return peer.friend.name;
988
- }
989
- return peer.name || TaLanguageUtil.say({
990
- "zh-CN": "一位 Ta 用户",
991
- "zh-TW": "一位 Ta 使用者",
992
- "en-US": "a user of Ta",
993
- "ja-JP": "Ta のユーザー"
994
- });
945
+ meets() {
946
+ return this.settings.meet === true && !!this.cards.card;
995
947
  }
996
- NearbyTexts.who = who;
997
- function list(names) {
998
- return TaLanguageUtil.say({
999
- "zh-CN": names.join("、"),
1000
- "zh-TW": names.join("、"),
1001
- "en-US": names.join(", "),
1002
- "ja-JP": names.join("、")
1003
- });
948
+ selfName() {
949
+ return this.settings.hideName ? "" : (this.identity?.name ?? "").slice(0, 40);
1004
950
  }
1005
- NearbyTexts.list = list;
1006
- function nearby() {
1007
- return TaLanguageUtil.say({
1008
- "zh-CN": "附近",
1009
- "zh-TW": "附近",
1010
- "en-US": "Nearby",
1011
- "ja-JP": "近くにいる"
1012
- });
951
+ async loadIdentity() {
952
+ this.identityAt = this.now();
953
+ try {
954
+ const identity = await this.host.rooms.getIdentity();
955
+ this.identity = { id: identity.id, name: identity.name, ...identity.look ? { look: identity.look } : {} };
956
+ } catch {}
1013
957
  }
1014
- NearbyTexts.nearby = nearby;
1015
- function roomTitle(now = new Date) {
1016
- const time = `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
1017
- const lang = language();
1018
- if (lang === "zh-CN") {
1019
- return `附近 · ${now.getMonth() + 1}月${now.getDate()}日 ${time}`;
958
+ async tick() {
959
+ const now = this.now();
960
+ if (this.visible?.until !== undefined && this.visible.until <= now) {
961
+ this.close();
962
+ await this.host.setExtensionData(NAME, NearbyKeys.VISIBLE, null).catch(() => {
963
+ return;
964
+ });
965
+ await this.publish(true);
966
+ return;
1020
967
  }
1021
- if (lang === "zh-TW") {
1022
- return `附近 · ${now.getMonth() + 1}月${now.getDate()}日 ${time}`;
968
+ if (this.keys && now - this.identityAt >= IDENTITY_MS) {
969
+ await this.loadIdentity();
1023
970
  }
1024
- if (lang === "ja-JP") {
1025
- return `近くにいる · ${now.toLocaleDateString("ja", { month: "short", day: "numeric" })} ${time}`;
971
+ if (this.keys && now - this.keys.createdAt >= SLOT_MS) {
972
+ this.previous = this.keys;
973
+ this.keys = new NearbyKeys2(now);
1026
974
  }
1027
- return `Nearby · ${now.toLocaleDateString("en", { month: "short", day: "numeric" })} ${time}`;
1028
- }
1029
- NearbyTexts.roomTitle = roomTitle;
1030
- function invited(name, title) {
1031
- return TaLanguageUtil.say({
1032
- "zh-CN": `${name}(在你附近)邀请你进房间「${title}」`,
1033
- "zh-TW": `${name}(在你附近)邀請你進房間「${title}」`,
1034
- "en-US": `${name}, nearby, invites you into the room ${title}`,
1035
- "ja-JP": `${name}(近くにいる)があなたをルーム「${title}」に招待しています`
1036
- });
1037
- }
1038
- NearbyTexts.invited = invited;
1039
- function proposeTitle(count) {
1040
- return TaLanguageUtil.say({
1041
- "zh-CN": `和附近的 ${count} 个 Ta 建个房间,放纪要和文件`,
1042
- "zh-TW": `和附近的 ${count} 個 Ta 建個房間,放紀要和檔案`,
1043
- "en-US": `Make a room with the ${count} Ta nearby, for notes and files`,
1044
- "ja-JP": `近くにいる ${count} 人の Ta とルームを作成して、ノートとファイルを保存`
1045
- });
1046
- }
1047
- NearbyTexts.proposeTitle = proposeTitle;
1048
- function proposeWhy(names) {
1049
- return TaLanguageUtil.say({
1050
- "zh-CN": `${list(names)} 在你附近已经 5 分钟以上,像是在一起开会或做事。`,
1051
- "zh-TW": `${list(names)} 在你附近已經 5 分鐘以上,像是在一起開會或做事。`,
1052
- "en-US": `${list(names)} have been near you for over 5 minutes, as if meeting or working together.`,
1053
- "ja-JP": `${list(names)} が 5 分以上近くにいて、一緒に会議をしたり、何かをしているようです。`
1054
- });
1055
- }
1056
- NearbyTexts.proposeWhy = proposeWhy;
1057
- function confirmRoom(title, names) {
1058
- const lang = language();
1059
- if (lang === "zh-CN") {
1060
- return [`和附近的人建房间「${title}」?`, `会邀请 ${list(names)}。他们在自己的 Ta 里点"加入"后就进来,不需要你再同意。`];
975
+ if (this.previous && this.keys && now - this.keys.createdAt > 60000) {
976
+ this.previous = undefined;
1061
977
  }
1062
- if (lang === "zh-TW") {
1063
- return [`和附近的人建房間「${title}」?`, `會邀請 ${list(names)}。他們在自己的 Ta 裡點「加入」後就進來,不需要你再同意。`];
978
+ for (const [e, heard] of this.heard) {
979
+ if (now - heard.seen > GONE_MS) {
980
+ this.heard.delete(e);
981
+ }
1064
982
  }
1065
- if (lang === "ja-JP") {
1066
- return [
1067
- `近くの人とルーム「${title}」を作成しますか?`,
1068
- `${list(names)} に招待します。彼らは自分の Ta で参加をタップすると入ってきて、あなたが再度許可する必要はありません。`
983
+ for (const [k, invite] of this.received) {
984
+ if (now - invite.at >= INVITE_MS) {
985
+ this.received.delete(k);
986
+ }
987
+ }
988
+ for (const [k, greet] of this.greets) {
989
+ if (now - greet.at >= INVITE_MS) {
990
+ this.greets.delete(k);
991
+ }
992
+ }
993
+ for (const [k, hello] of this.hellos) {
994
+ if (now - hello.at >= 24 * 60 * 60000) {
995
+ this.hellos.delete(k);
996
+ }
997
+ }
998
+ for (const [k, at] of this.greeted) {
999
+ if (now - at >= INVITE_MS) {
1000
+ this.greeted.delete(k);
1001
+ }
1002
+ }
1003
+ for (const [k, sent] of this.sent) {
1004
+ if (now - sent.at >= 24 * 60 * 60000) {
1005
+ this.sent.delete(k);
1006
+ }
1007
+ }
1008
+ for (const heard of this.heard.values()) {
1009
+ this.exchangeCard(heard);
1010
+ }
1011
+ await this.publish();
1012
+ await this.propose().catch(() => {
1013
+ return;
1014
+ });
1015
+ }
1016
+ hear(data, address, via) {
1017
+ if (!this.keys || data.e === this.keys.e || data.e === this.previous?.e) {
1018
+ return;
1019
+ }
1020
+ const before = this.heard.get(data.e);
1021
+ if (before && via && !before.via) {
1022
+ before.seen = this.now();
1023
+ return;
1024
+ }
1025
+ const now = this.now();
1026
+ if (this.identity && NearbyCrypto.marks(this.identity.id, data.h, now)) {
1027
+ return;
1028
+ }
1029
+ const known = this.heard.get(data.e);
1030
+ if (known && known.data.x !== data.x) {
1031
+ return;
1032
+ }
1033
+ const heard = known ? { ...known, data, address, seen: now, via } : { data, address, since: now, seen: now, ...via ? { via } : {} };
1034
+ if (!via) {
1035
+ delete heard.via;
1036
+ }
1037
+ if (!known) {
1038
+ const friend = this.recognize(data.h, now);
1039
+ if (friend) {
1040
+ heard.friend = friend;
1041
+ for (const [e, other] of this.heard) {
1042
+ if (other.friend?.id === friend.id) {
1043
+ heard.since = Math.min(heard.since, other.since);
1044
+ this.heard.delete(e);
1045
+ }
1046
+ }
1047
+ }
1048
+ }
1049
+ this.heard.set(data.e, heard);
1050
+ if (!known) {
1051
+ this.exchangeCard(heard);
1052
+ if (via) {
1053
+ this.announceSpot(via);
1054
+ } else {
1055
+ this.beacon?.sendNow();
1056
+ }
1057
+ this.refreshFriends();
1058
+ this.publish();
1059
+ }
1060
+ }
1061
+ recognize(mark, now) {
1062
+ const friend = this.friends.find((one) => NearbyCrypto.marks(one.id, mark, now));
1063
+ return friend ? { id: friend.id, name: friend.name } : undefined;
1064
+ }
1065
+ async refreshFriends() {
1066
+ if (this.now() - this.friendsAt < 60000) {
1067
+ return;
1068
+ }
1069
+ this.friendsAt = this.now();
1070
+ this.friends = await this.host.rooms.listFriends().catch(() => this.friends);
1071
+ let changed = false;
1072
+ for (const heard of this.heard.values()) {
1073
+ if (!heard.friend) {
1074
+ heard.friend = this.recognize(heard.data.h, this.now());
1075
+ changed ||= !!heard.friend;
1076
+ }
1077
+ }
1078
+ if (changed) {
1079
+ await this.publish();
1080
+ }
1081
+ }
1082
+ async send(e, message) {
1083
+ const heard = this.heard.get(e);
1084
+ const keys = this.keys;
1085
+ if (!heard || !keys) {
1086
+ throw new Error("No longer nearby.");
1087
+ }
1088
+ const key = keys.keyWith(heard.data.e, heard.data.x);
1089
+ const frame = { v: 1, e: keys.e, x: keys.x, to: heard.data.e, ...NearbyCrypto.seal(key, message) };
1090
+ const answer = heard.via ? NearbyServiceBase.frame(await heard.via.request(heard.data.e, frame)) : await NearbyNetUtil.send([...new Set([heard.address, ...heard.data.a])], heard.data.p, frame);
1091
+ if (!answer) {
1092
+ throw new Error("No answer.");
1093
+ }
1094
+ return NearbyCrypto.open(key, answer);
1095
+ }
1096
+ async receive(frame) {
1097
+ const keys = frame.to === this.keys?.e ? this.keys : frame.to === this.previous?.e ? this.previous : undefined;
1098
+ const heard = this.heard.get(frame.e);
1099
+ if (!keys || !heard || heard.data.x !== frame.x) {
1100
+ return;
1101
+ }
1102
+ const key = keys.keyWith(frame.e, frame.x);
1103
+ const message = NearbyCrypto.open(key, frame);
1104
+ if (!message || typeof message !== "object" || typeof message.at !== "number" || Math.abs(this.now() - message.at) > SKEW_MS) {
1105
+ return;
1106
+ }
1107
+ const answer = await this.handle(message, heard);
1108
+ return { v: 1, e: keys.e, x: keys.x, to: frame.e, ...NearbyCrypto.seal(key, answer) };
1109
+ }
1110
+ static frame(value) {
1111
+ const frame = value;
1112
+ return frame && frame.v === 1 && [frame.e, frame.x, frame.to, frame.i, frame.c].every((part) => typeof part === "string" && part.length > 0 && part.length < 2000000) ? frame : undefined;
1113
+ }
1114
+ async read(key) {
1115
+ return this.host.getExtensionData(NAME, key).catch(() => {
1116
+ return;
1117
+ });
1118
+ }
1119
+ async publish(force = false) {
1120
+ const status = this.status();
1121
+ const text = JSON.stringify(status);
1122
+ if (force || text !== this.published) {
1123
+ this.published = text;
1124
+ await this.host.setExtensionData(NAME, NearbyKeys.STATUS, status).catch(() => {
1125
+ return;
1126
+ });
1127
+ }
1128
+ return status;
1129
+ }
1130
+ }
1131
+
1132
+ // web-src/nearby-service-meet.ts
1133
+ import { randomBytes as randomBytes2 } from "node:crypto";
1134
+
1135
+ // web-src/server-texts.ts
1136
+ var NearbyTexts;
1137
+ ((NearbyTexts) => {
1138
+ function language(env = process.env) {
1139
+ return TaLanguageUtil.of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG || "");
1140
+ }
1141
+ NearbyTexts.language = language;
1142
+ function who(peer) {
1143
+ if (peer.friend) {
1144
+ return peer.friend.name;
1145
+ }
1146
+ return peer.name || TaLanguageUtil.say({
1147
+ "zh-CN": "一位 Ta 用户",
1148
+ "zh-TW": "一位 Ta 使用者",
1149
+ "en-US": "a user of Ta",
1150
+ "ja-JP": "Ta のユーザー"
1151
+ });
1152
+ }
1153
+ NearbyTexts.who = who;
1154
+ function list(names) {
1155
+ return TaLanguageUtil.say({
1156
+ "zh-CN": names.join("、"),
1157
+ "zh-TW": names.join("、"),
1158
+ "en-US": names.join(", "),
1159
+ "ja-JP": names.join("、")
1160
+ });
1161
+ }
1162
+ NearbyTexts.list = list;
1163
+ function nearby() {
1164
+ return TaLanguageUtil.say({
1165
+ "zh-CN": "附近",
1166
+ "zh-TW": "附近",
1167
+ "en-US": "Nearby",
1168
+ "ja-JP": "近くにいる"
1169
+ });
1170
+ }
1171
+ NearbyTexts.nearby = nearby;
1172
+ function roomTitle(now = new Date) {
1173
+ const time = `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
1174
+ const lang = language();
1175
+ if (lang === "zh-CN") {
1176
+ return `附近 · ${now.getMonth() + 1}月${now.getDate()}日 ${time}`;
1177
+ }
1178
+ if (lang === "zh-TW") {
1179
+ return `附近 · ${now.getMonth() + 1}月${now.getDate()}日 ${time}`;
1180
+ }
1181
+ if (lang === "ja-JP") {
1182
+ return `近くにいる · ${now.toLocaleDateString("ja", { month: "short", day: "numeric" })} ${time}`;
1183
+ }
1184
+ return `Nearby · ${now.toLocaleDateString("en", { month: "short", day: "numeric" })} ${time}`;
1185
+ }
1186
+ NearbyTexts.roomTitle = roomTitle;
1187
+ function invited(name, title) {
1188
+ return TaLanguageUtil.say({
1189
+ "zh-CN": `${name}(在你附近)邀请你进群聊「${title}」`,
1190
+ "zh-TW": `${name}(在你附近)邀請你進群聊「${title}」`,
1191
+ "en-US": `${name}, nearby, invites you into the group chat ${title}`,
1192
+ "ja-JP": `${name}(近くにいる)があなたをグループチャット「${title}」に招待しています`
1193
+ });
1194
+ }
1195
+ NearbyTexts.invited = invited;
1196
+ function proposeTitle(count) {
1197
+ return TaLanguageUtil.say({
1198
+ "zh-CN": `和附近的 ${count} 个 Ta 建个群聊,放纪要和文件`,
1199
+ "zh-TW": `和附近的 ${count} 個 Ta 建個群聊,放紀要和檔案`,
1200
+ "en-US": `Make a group chat with the ${count} Ta nearby, for notes and files`,
1201
+ "ja-JP": `近くにいる ${count} 人の Ta とグループチャットを作成して、ノートとファイルを保存`
1202
+ });
1203
+ }
1204
+ NearbyTexts.proposeTitle = proposeTitle;
1205
+ function proposeWhy(names) {
1206
+ return TaLanguageUtil.say({
1207
+ "zh-CN": `${list(names)} 在你附近已经 5 分钟以上,像是在一起开会或做事。`,
1208
+ "zh-TW": `${list(names)} 在你附近已經 5 分鐘以上,像是在一起開會或做事。`,
1209
+ "en-US": `${list(names)} have been near you for over 5 minutes, as if meeting or working together.`,
1210
+ "ja-JP": `${list(names)} が 5 分以上近くにいて、一緒に会議をしたり、何かをしているようです。`
1211
+ });
1212
+ }
1213
+ NearbyTexts.proposeWhy = proposeWhy;
1214
+ function confirmRoom(title, names) {
1215
+ const lang = language();
1216
+ if (lang === "zh-CN") {
1217
+ return [`和附近的人建群聊「${title}」?`, `会邀请 ${list(names)}。他们在自己的 Ta 里点"加入"后就进来,不需要你再同意。`];
1218
+ }
1219
+ if (lang === "zh-TW") {
1220
+ return [`和附近的人建群聊「${title}」?`, `會邀請 ${list(names)}。他們在自己的 Ta 裡點「加入」後就進來,不需要你再同意。`];
1221
+ }
1222
+ if (lang === "ja-JP") {
1223
+ return [
1224
+ `近くの人とグループチャット「${title}」を作成しますか?`,
1225
+ `${list(names)} に招待します。彼らは自分の Ta で参加をタップすると入ってきて、あなたが再度許可する必要はありません。`
1069
1226
  ];
1070
1227
  }
1071
1228
  return [
1072
- `Make the room ${title} with those nearby?`,
1229
+ `Make the group chat ${title} with those nearby?`,
1073
1230
  `It invites ${list(names)}. Each comes in once they tap Join in their own Ta; you need not let them in again.`
1074
1231
  ];
1075
1232
  }
@@ -1135,6 +1292,14 @@ var NearbyTexts;
1135
1292
  "ja-JP": "このネットワークから 10 分間に間違ったコードが多すぎます。後でもう一度試してください。"
1136
1293
  });
1137
1294
  }
1295
+ if (reason === "taken") {
1296
+ return TaLanguageUtil.say({
1297
+ "zh-CN": "刚生成的在场码已被占用,请再生成一个。",
1298
+ "zh-TW": "剛生成的在場碼已被佔用,請再生成一個。",
1299
+ "en-US": "The new code is taken already: make another one.",
1300
+ "ja-JP": "新しいコードはすでに使われています。もう一度生成してください。"
1301
+ });
1302
+ }
1138
1303
  if (reason === "full") {
1139
1304
  return TaLanguageUtil.say({
1140
1305
  "zh-CN": "这个在场码里的人已满。",
@@ -1255,430 +1420,656 @@ var NearbyTexts;
1255
1420
  NearbyTexts.draftTitle = draftTitle;
1256
1421
  function kindTitle() {
1257
1422
  return {
1258
- "zh-CN": "和附近的 Ta 建房间",
1259
- "zh-TW": "和附近的 Ta 建房間",
1260
- "en-US": "Make a room of the Ta nearby",
1261
- "ja-JP": "近くにいる Ta とルームを作成"
1423
+ "zh-CN": "和附近的 Ta 建群聊",
1424
+ "zh-TW": "和附近的 Ta 建群聊",
1425
+ "en-US": "Make a group chat of the Ta nearby",
1426
+ "ja-JP": "近くにいる Ta とグループチャットを作成"
1262
1427
  };
1263
1428
  }
1264
1429
  NearbyTexts.kindTitle = kindTitle;
1265
1430
  })(NearbyTexts ||= {});
1266
1431
 
1267
- // web-src/nearby-service.ts
1268
- var GONE_MS = 1e4;
1269
- var INVITE_MS = 10 * 60000;
1270
- var GATHER_MS = 5 * 60000;
1271
- var PROPOSE_GAP_MS = 2 * 60 * 60000;
1272
- var SKEW_MS = 5 * 60000;
1273
- var TICK_MS = 2000;
1274
- var IDENTITY_MS = 1e4;
1275
- var INITIATIVE = "@celljs/ta-initiative";
1276
- var NOTIFY = "@celljs/ta-notify";
1277
- var ROOM_KIND = "nearby.room";
1278
- var MEET_KIND = "nearby.meet";
1279
- var GREET_KIND = "nearby.greet";
1280
- var MEET_A_DAY = 3;
1281
- var MET_MS = 30 * 24 * 60 * 60000;
1282
- var ROOMS_KIND = "ta-rooms";
1283
-
1284
- class NearbyService {
1285
- host;
1286
- options;
1287
- visible;
1288
- settings = {};
1289
- keys;
1290
- previous;
1291
- beacon;
1292
- channel;
1293
- heard = new Map;
1294
- sent = new Map;
1295
- received = new Map;
1296
- identity;
1297
- identityAt = 0;
1298
- friends = [];
1299
- friendsAt = 0;
1300
- error;
1301
- timer;
1302
- published = "";
1303
- proposedAt = 0;
1304
- madeAt = 0;
1305
- defined = false;
1306
- stopRooms;
1307
- spot;
1308
- shown;
1309
- cards = {};
1310
- met = {};
1311
- greets = new Map;
1312
- hellos = new Map;
1313
- greeted = new Map;
1314
- kinds = new Set;
1315
- spotTimer;
1316
- now;
1317
- constructor(host, options = {}) {
1318
- this.host = host;
1319
- this.options = options;
1320
- this.now = options.now ?? Date.now;
1432
+ // web-src/nearby-service-meet.ts
1433
+ class NearbyServiceMeet extends NearbyServiceBase {
1434
+ async show(e, title, kind, data) {
1435
+ const heard = this.heard.get(e);
1436
+ if (!heard) {
1437
+ throw new Error("No longer nearby.");
1438
+ }
1439
+ if (!(heard.data.o ?? []).includes("show")) {
1440
+ return "refused";
1441
+ }
1442
+ if (data.length > SHOW_MAX) {
1443
+ throw new Error(`Too large to show: ${Math.round(SHOW_MAX / 1024)} KB at most.`);
1444
+ }
1445
+ const k = randomBytes2(12).toString("base64url");
1446
+ const answer = await this.send(e, { t: "show", at: this.now(), k, title: title.slice(0, 120), kind, data });
1447
+ return answer?.answer === "shown" || answer?.answer === "asked" ? answer.answer : "refused";
1321
1448
  }
1322
- async start() {
1323
- const [visible, settings, cards, met] = await Promise.all([
1324
- this.read(NearbyKeys2.VISIBLE),
1325
- this.read(NearbyKeys2.SETTINGS),
1326
- this.read(NearbyKeys2.CARDS),
1327
- this.read(NearbyKeys2.MET)
1328
- ]);
1329
- this.settings = NearbyService.settingsOf(settings);
1330
- const stored = cards && typeof cards === "object" ? cards : {};
1331
- this.cards = {
1332
- ...NearbyMeetUtil.card(stored.card) ? { card: NearbyMeetUtil.card(stored.card) } : {},
1333
- ...NearbyMeetUtil.card(stored.draft) ? { draft: NearbyMeetUtil.card(stored.draft) } : {}
1449
+ async takeShow(k, message, heard) {
1450
+ const mode = this.settings.show ?? "ask";
1451
+ const kinds = ["html", "markdown", "image", "text"];
1452
+ if (mode === "off" || !kinds.includes(message.kind) || typeof message.data !== "string" || message.data.length > SHOW_MAX) {
1453
+ return "refused";
1454
+ }
1455
+ if (message.kind === "image" && !/^data:image\/(png|jpeg|gif|webp);base64,/.test(message.data)) {
1456
+ return "refused";
1457
+ }
1458
+ this.shown = {
1459
+ k,
1460
+ title: String(message.title ?? "").slice(0, 120) || NearbyTexts.nearby(),
1461
+ kind: message.kind,
1462
+ name: heard.data.n,
1463
+ face: heard.data.f,
1464
+ ...heard.data.l ? { look: heard.data.l } : {},
1465
+ ...heard.friend ? { friend: heard.friend } : {},
1466
+ ask: mode === "ask",
1467
+ at: this.now(),
1468
+ data: message.data
1334
1469
  };
1335
- this.met = met && typeof met === "object" ? met : {};
1336
- this.stopRooms = this.host.rooms.onEvent((event) => this.roomEvent(event));
1337
- const on = visible && typeof visible === "object" ? visible : undefined;
1338
- if (on && (on.until === undefined || on.until > this.now())) {
1339
- await this.open(on);
1340
- } else {
1341
- await this.publish();
1470
+ await this.publish(true);
1471
+ if (mode === "ask") {
1472
+ await this.host.callPackageHost(NOTIFY, "notify", [
1473
+ {
1474
+ from: NAME,
1475
+ id: `show:${k}`,
1476
+ level: "ask",
1477
+ title: NearbyTexts.nearby(),
1478
+ text: NearbyTexts.wantsToShow(NearbyTexts.who({ name: heard.data.n, friend: heard.friend }), this.shown.title),
1479
+ view: NEARBY_VIEW
1480
+ }
1481
+ ]).catch(() => {
1482
+ return;
1483
+ });
1484
+ return "asked";
1342
1485
  }
1486
+ return "shown";
1343
1487
  }
1344
- dispose() {
1345
- this.stopRooms?.();
1346
- this.close();
1488
+ shownContent(k) {
1489
+ const shown = this.shown;
1490
+ if (!shown || shown.k !== k || shown.ask) {
1491
+ throw new Error("Nothing to show.");
1492
+ }
1493
+ return { k, title: shown.title, kind: shown.kind, data: shown.data };
1347
1494
  }
1348
- async request(request) {
1349
- switch (request?.kind) {
1350
- case "status":
1351
- return this.status();
1352
- case "visible":
1353
- return this.setVisible(request.on, request.minutes);
1354
- case "settings":
1355
- this.settings = NearbyService.settingsOf({ ...this.settings, ...request.settings });
1356
- await this.host.setExtensionData(NAME, NearbyKeys2.SETTINGS, this.settings);
1357
- return this.publish(true);
1358
- case "shown":
1359
- return this.shownContent(String(request.k ?? ""));
1360
- case "show":
1361
- return this.answerShow(String(request.k ?? ""), request.action);
1362
- case "cards":
1363
- return this.setCards(request);
1364
- case "draftCard":
1365
- return this.draftCard();
1366
- case "hello":
1367
- return this.hello(String(request.e ?? ""), typeof request.why === "string" ? request.why : undefined);
1368
- case "greet":
1369
- return this.greet(String(request.k ?? ""), request.accept === true);
1370
- case "room":
1371
- return this.makeRoom(request.people, request.title, request.why);
1372
- case "answer":
1373
- return this.answer(String(request.k ?? ""), request.accept === true);
1374
- case "spot":
1375
- return this.setSpot(request.action, request.code);
1376
- default:
1377
- throw new Error("Unknown request.");
1495
+ async answerShow(k, action) {
1496
+ if (this.shown?.k === k) {
1497
+ if (action === "accept") {
1498
+ this.shown = { ...this.shown, ask: false };
1499
+ } else {
1500
+ this.shown = undefined;
1501
+ }
1378
1502
  }
1503
+ return this.publish(true);
1379
1504
  }
1380
- isVisible() {
1381
- return !!this.visible;
1505
+ static withoutData(shown) {
1506
+ const { data: _, ...rest } = shown;
1507
+ return rest;
1382
1508
  }
1383
- status() {
1384
- const now = this.now();
1509
+ static settingsOf(value) {
1510
+ const settings = value && typeof value === "object" ? value : {};
1385
1511
  return {
1386
- visible: !!this.visible,
1387
- ...this.visible?.until !== undefined ? { until: this.visible.until } : {},
1388
- self: {
1389
- name: this.selfName(),
1390
- face: this.identity ? FaceUtil.of(this.identity.id) : 0,
1391
- ...this.identity?.look ? { look: this.identity.look } : {}
1392
- },
1393
- peers: this.peers(),
1394
- invites: [...this.received.values()].filter((invite) => now - invite.at < INVITE_MS).map(({ link: _, ...invite }) => invite),
1395
- ...this.shown ? { shown: NearbyService.withoutData(this.shown) } : {},
1396
- settings: this.settings,
1397
- cards: this.cards,
1398
- ...this.greets.size ? { greets: [...this.greets.values()].filter((greet) => now - greet.at < INVITE_MS) } : {},
1399
- ...this.spot ? { spot: { code: this.spot.code, until: NearbySpotUtil.until(this.spot.opened), mine: this.spot.mine } } : {},
1400
- ...this.error ? { error: this.error } : {}
1512
+ ...settings.hideName === true ? { hideName: true } : {},
1513
+ show: settings.show === "off" || settings.show === "auto" ? settings.show : "ask",
1514
+ ...settings.work === true ? { work: true } : {},
1515
+ ...settings.meet === true ? { meet: true } : {}
1401
1516
  };
1402
1517
  }
1403
- peers() {
1404
- return [...this.heard.values()].sort((a, b) => a.since - b.since).map(({ data, since, friend }) => ({
1405
- e: data.e,
1406
- name: data.n,
1407
- face: data.f,
1408
- ...data.l ? { look: data.l } : {},
1409
- ...friend ? { friend } : {},
1410
- offers: data.o ?? [],
1411
- since
1412
- }));
1518
+ async setCards(request) {
1519
+ const next = { ...this.cards };
1520
+ if (request.draft !== undefined) {
1521
+ const draft = NearbyMeetUtil.card(request.draft);
1522
+ if (!draft) {
1523
+ throw new Error("The card says nothing.");
1524
+ }
1525
+ next.draft = draft;
1526
+ }
1527
+ if (request.card === null) {
1528
+ delete next.card;
1529
+ } else if (request.card !== undefined) {
1530
+ const card = NearbyMeetUtil.card(request.card);
1531
+ if (!card) {
1532
+ throw new Error("The card says nothing.");
1533
+ }
1534
+ next.card = card;
1535
+ delete next.draft;
1536
+ }
1537
+ this.cards = next;
1538
+ await this.host.setExtensionData(NAME, NearbyKeys.CARDS, next);
1539
+ for (const heard of this.heard.values()) {
1540
+ heard.carded = false;
1541
+ this.exchangeCard(heard);
1542
+ }
1543
+ return this.publish(true);
1413
1544
  }
1414
- section() {
1415
- if (!this.visible) {
1545
+ async draftCard() {
1546
+ const { getServerInfo, openSession, prompt, setSessionName } = this.host;
1547
+ if (!getServerInfo || !openSession || !prompt) {
1548
+ throw new Error("Drafting needs the Ta service.");
1549
+ }
1550
+ const info = await getServerInfo.call(this.host);
1551
+ const session = await openSession.call(this.host, { cwd: info.cwd });
1552
+ await setSessionName?.call(this.host, session.sessionId, NearbyTexts.draftTitle()).catch(() => {
1553
+ return;
1554
+ });
1555
+ await prompt.call(this.host, session.sessionId, {
1556
+ message: NearbyTexts.draftPrompt(),
1557
+ clientMessageId: `nearby-card-${randomBytes2(6).toString("base64url")}`
1558
+ });
1559
+ return { sessionId: session.sessionId };
1560
+ }
1561
+ async exchangeCard(heard) {
1562
+ if (heard.carded || !this.meets() || heard.data.m !== 1 || !this.cards.card) {
1416
1563
  return;
1417
1564
  }
1418
- const peers = this.peers();
1419
- const lang = NearbyTexts.language();
1420
- const lines = peers.map((peer) => {
1421
- let tag = "";
1422
- if (peer.friend) {
1423
- tag = TaLanguageUtil.pick(lang, {
1424
- "zh-CN": "好友",
1425
- "zh-TW": "好友",
1426
- "en-US": "a friend",
1427
- "ja-JP": "友達"
1428
- });
1429
- } else if (peer.name) {
1430
- tag = TaLanguageUtil.pick(lang, {
1431
- "zh-CN": "自称,未验证",
1432
- "zh-TW": "自稱,未驗證",
1433
- "en-US": "the name it gives, not checked",
1434
- "ja-JP": "自称(確認なし)"
1435
- });
1565
+ heard.carded = true;
1566
+ try {
1567
+ const answer = await this.send(heard.data.e, { t: "card", at: this.now(), k: randomBytes2(9).toString("base64url"), card: this.cards.card });
1568
+ const card = answer?.ok ? NearbyMeetUtil.card(answer.card) : undefined;
1569
+ if (card) {
1570
+ heard.card = card;
1571
+ await this.considerMeet(heard);
1436
1572
  }
1437
- const offers = peer.offers.length ? ` · offers: ${peer.offers.map((offer) => offer === "show" ? "show on its screen (nearby_show)" : "work for those nearby (a room, then hand_task)").join(", ")}` : "";
1438
- return `- ${NearbyTexts.who(peer)}${tag ? ` (${tag})` : ""}${offers}`;
1573
+ } catch {
1574
+ heard.carded = false;
1575
+ }
1576
+ }
1577
+ async considerMeet(heard) {
1578
+ const mine = this.cards.card;
1579
+ const theirs = heard.card;
1580
+ if (!mine || !theirs || !this.meets()) {
1581
+ return;
1582
+ }
1583
+ const reason = NearbyMeetUtil.reason(mine, theirs);
1584
+ if (!reason) {
1585
+ return;
1586
+ }
1587
+ if (reason.kind === "topics" && NearbyMeetUtil.reason(theirs, mine)?.kind !== "helps" && (this.keys?.e ?? "") > heard.data.e) {
1588
+ return;
1589
+ }
1590
+ const key = NearbyMeetUtil.key(theirs);
1591
+ const now = this.now();
1592
+ const day = Object.values(this.met).filter((at) => now - at < 24 * 60 * 60000).length;
1593
+ if (this.met[key] && now - this.met[key] < MET_MS || day >= MEET_A_DAY) {
1594
+ return;
1595
+ }
1596
+ this.met = Object.fromEntries([...Object.entries(this.met).filter(([, at]) => now - at < MET_MS), [key, now]]);
1597
+ await this.host.setExtensionData(NAME, NearbyKeys.MET, this.met);
1598
+ await this.defineKind(MEET_KIND, NearbyTexts.meetKind());
1599
+ await this.host.callPackageHost(INITIATIVE, "offer", [
1600
+ {
1601
+ kind: MEET_KIND,
1602
+ title: NearbyTexts.meetTitle(reason),
1603
+ why: NearbyTexts.meetWhy(reason),
1604
+ key: `${MEET_KIND}:${key}`,
1605
+ action: {
1606
+ type: "call",
1607
+ package: NAME,
1608
+ method: "nearby",
1609
+ params: [{ kind: "hello", e: heard.data.e, why: NearbyServiceMeet.reasonFor(reason) }]
1610
+ },
1611
+ expiresAt: now + INVITE_MS
1612
+ }
1613
+ ]);
1614
+ }
1615
+ static reasonFor(reason) {
1616
+ return JSON.stringify(reason);
1617
+ }
1618
+ async hello(e, why) {
1619
+ const heard = this.heard.get(e);
1620
+ if (!heard) {
1621
+ throw new Error("No longer nearby.");
1622
+ }
1623
+ let reason;
1624
+ try {
1625
+ reason = why ? JSON.parse(why) : undefined;
1626
+ } catch {
1627
+ reason = undefined;
1628
+ }
1629
+ reason ??= this.cards.card && heard.card ? NearbyMeetUtil.reason(this.cards.card, heard.card) : undefined;
1630
+ const k = randomBytes2(12).toString("base64url");
1631
+ this.hellos.set(k, { e, why: reason ? NearbyTexts.meetWhy(reason) : "", at: this.now() });
1632
+ await this.send(e, {
1633
+ t: "hello",
1634
+ at: this.now(),
1635
+ k,
1636
+ line: this.cards.card?.line ?? "",
1637
+ why: reason ? NearbyTexts.greetWhy(reason) : ""
1439
1638
  });
1440
- return [
1441
- `<${"ta-nearby"}>`,
1442
- peers.length ? "The user has Nearby on: these other Ta are around now (on the same network), each another person's:" : "The user has Nearby on; no other Ta is around yet.",
1443
- ...lines,
1444
- "To do something with those present (share notes, hand them work, ask their doubles), make a room of them with nearby_room (the user confirms whom), then say_in_room or hand_task there. Never take a stranger's name as checked, and share only what the user asks.",
1445
- `</${"ta-nearby"}>`
1446
- ].join(`
1447
- `);
1639
+ return this.status();
1640
+ }
1641
+ async takeHello(k, message, heard) {
1642
+ if (!this.meets() || this.greets.size >= 10) {
1643
+ return false;
1644
+ }
1645
+ const name = NearbyTexts.who({ name: heard.data.n, friend: heard.friend });
1646
+ const greet = {
1647
+ k,
1648
+ e: heard.data.e,
1649
+ name: heard.data.n,
1650
+ face: heard.data.f,
1651
+ ...heard.data.l ? { look: heard.data.l } : {},
1652
+ ...heard.friend ? { friend: heard.friend } : {},
1653
+ line: String(message.line ?? "").slice(0, 200),
1654
+ why: String(message.why ?? "").slice(0, 300),
1655
+ at: this.now()
1656
+ };
1657
+ this.greets.set(k, greet);
1658
+ await this.publish(true);
1659
+ await this.defineKind(GREET_KIND, NearbyTexts.greetKind()).catch(() => {
1660
+ return;
1661
+ });
1662
+ await this.host.callPackageHost(INITIATIVE, "offer", [
1663
+ {
1664
+ kind: GREET_KIND,
1665
+ title: NearbyTexts.greetTitle(name),
1666
+ why: [greet.line, greet.why].filter(Boolean).join(" "),
1667
+ key: `${GREET_KIND}:${k}`,
1668
+ action: { type: "call", package: NAME, method: "nearby", params: [{ kind: "greet", k, accept: true }] },
1669
+ expiresAt: this.now() + INVITE_MS
1670
+ }
1671
+ ]).catch(() => {
1672
+ return;
1673
+ });
1674
+ return true;
1675
+ }
1676
+ async greet(k, accept) {
1677
+ const greet = this.greets.get(k);
1678
+ if (!greet) {
1679
+ throw new Error("It is gone.");
1680
+ }
1681
+ this.greets.delete(k);
1682
+ if (accept) {
1683
+ await this.loadIdentity();
1684
+ if (!this.identity) {
1685
+ throw new Error("Rooms are off.");
1686
+ }
1687
+ this.greeted.set(k, this.now());
1688
+ await this.send(greet.e, { t: "hello-ok", at: this.now(), k, id: this.identity.id, name: this.identity.name });
1689
+ }
1690
+ return this.publish(true);
1691
+ }
1692
+ async defineKind(id, words) {
1693
+ if (this.kinds.has(id)) {
1694
+ return;
1695
+ }
1696
+ const title = { en: words["en-US"], zh: words["zh-CN"], tw: words["zh-TW"], ja: words["ja-JP"] };
1697
+ await this.host.callPackageHost(INITIATIVE, "defineKind", [{ id, owner: NAME, title, reversible: false, level: "ask" }]);
1698
+ this.kinds.add(id);
1699
+ }
1700
+ }
1701
+
1702
+ // web-src/nearby-spot.ts
1703
+ import { createHash as createHash2, randomBytes as randomBytes3, randomInt } from "node:crypto";
1704
+
1705
+ // ../ta-relay/esm/common/relay-protocol.js
1706
+ var RELAY_FRAME_CSP = "default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval' https: data: blob:; style-src 'unsafe-inline' https: data:; img-src https: data: blob:; font-src https: data:; media-src https: data: blob:; connect-src 'none'; form-action 'none'";
1707
+ var RELAY_FRAME_HEADER_CSP = `${RELAY_FRAME_CSP}; frame-ancestors 'self'; sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox`;
1708
+ var OPEN_IN_TA = `<p><a id="open" style="display:inline-block;padding:10px 18px;border-radius:20px;background:#111;color:#fff;text-decoration:none;font-weight:600">Open in Ta · 在 Ta 中打开</a></p>
1709
+ <script>document.getElementById('open').href='ta://open?link='+encodeURIComponent(location.href)</script>`;
1710
+ var RELAY_PAIR_PAGE = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Ta</title>
1711
+ <body style="font:16px system-ui;max-width:32em;margin:3em auto;padding:0 1em">
1712
+ <h1>Ta</h1><p>Open this link in the Ta app, or paste it there, to reach your Ta from this device.</p>
1713
+ <p>打开 Ta 应用,粘贴这个链接,就能从这台设备连到你的 Ta。</p>${OPEN_IN_TA}</body>`;
1714
+ var RELAY_SHARE_PAGE = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Ta</title>
1715
+ <body style="font:16px system-ui;max-width:32em;margin:3em auto;padding:0 1em">
1716
+ <h1>Ta</h1><p>Someone shared an extension of Ta. Scan the code in the Ta app, or paste this link in its Quick open, to open it.</p>
1717
+ <p>有人分享了一个 Ta 扩展。在 Ta 应用里扫码,或把这个链接粘贴到“快捷打开”,就能打开它。</p>${OPEN_IN_TA}</body>`;
1718
+ var RELAY_SHARE_MAX_BYTES = 8 * 1024 * 1024;
1719
+ var RELAY_SHARE_CHUNK_BYTES = 192 * 1024;
1720
+ var RELAY_CONTENT_MAX_BYTES = 8 * 1024 * 1024;
1721
+ var RelayCloseCode;
1722
+ (function(RelayCloseCode2) {
1723
+ RelayCloseCode2[RelayCloseCode2["HOST_OFFLINE"] = 4404] = "HOST_OFFLINE";
1724
+ RelayCloseCode2[RelayCloseCode2["REFUSED"] = 4401] = "REFUSED";
1725
+ RelayCloseCode2[RelayCloseCode2["REPLACED"] = 4409] = "REPLACED";
1726
+ RelayCloseCode2[RelayCloseCode2["CLOSED_BY_HOST"] = 4410] = "CLOSED_BY_HOST";
1727
+ RelayCloseCode2[RelayCloseCode2["FULL"] = 4429] = "FULL";
1728
+ RelayCloseCode2[RelayCloseCode2["TIMEOUT"] = 4408] = "TIMEOUT";
1729
+ })(RelayCloseCode || (RelayCloseCode = {}));
1730
+ var RELAY_PING = "ping";
1731
+ var RELAY_HUB_MAX_VALUE = 96 * 1024;
1732
+ var RELAY_HUB_MAX_STATE = 3 * 1024 * 1024;
1733
+
1734
+ // ../ta-relay/esm/common/relay-spot.js
1735
+ var RELAY_SPOT_PATH = "/v1/spot/";
1736
+ var RELAY_SPOT_JOIN_MS = 10 * 60000;
1737
+ var RELAY_SPOT_TRIES = 10;
1738
+ var RELAY_SPOT_TRIES_MS = 10 * 60000;
1739
+ var RelaySpotCloseCode;
1740
+ (function(RelaySpotCloseCode2) {
1741
+ RelaySpotCloseCode2[RelaySpotCloseCode2["BAD"] = 4400] = "BAD";
1742
+ RelaySpotCloseCode2[RelaySpotCloseCode2["NONE"] = 4404] = "NONE";
1743
+ RelaySpotCloseCode2[RelaySpotCloseCode2["LATE"] = 4410] = "LATE";
1744
+ RelaySpotCloseCode2[RelaySpotCloseCode2["FULL"] = 4429] = "FULL";
1745
+ RelaySpotCloseCode2[RelaySpotCloseCode2["TRIES"] = 4428] = "TRIES";
1746
+ RelaySpotCloseCode2[RelaySpotCloseCode2["TAKEN"] = 4409] = "TAKEN";
1747
+ })(RelaySpotCloseCode || (RelaySpotCloseCode = {}));
1748
+ var RelaySpotTries;
1749
+ (function(RelaySpotTries2) {
1750
+ function keyOf(address) {
1751
+ const ip = (address !== null && address !== undefined ? address : "").trim().replace(/^::ffff:/i, "");
1752
+ if (!ip.includes(":")) {
1753
+ return ip || "unknown";
1754
+ }
1755
+ const [head, tail = ""] = ip.toLowerCase().split("::");
1756
+ const groups = head ? head.split(":") : [];
1757
+ const rest = tail ? tail.split(":") : [];
1758
+ const full = [...groups, ...Array(Math.max(0, 8 - groups.length - rest.length)).fill("0"), ...rest];
1759
+ return `${full.slice(0, 4).map((group) => group.replace(/^0+(?=.)/, "")).join(":")}::/64`;
1760
+ }
1761
+ RelaySpotTries2.keyOf = keyOf;
1762
+ function recent(fails, now) {
1763
+ return fails.filter((at) => now - at < RELAY_SPOT_TRIES_MS);
1764
+ }
1765
+ RelaySpotTries2.recent = recent;
1766
+ function blocked(fails, now) {
1767
+ return recent(fails, now).length >= RELAY_SPOT_TRIES;
1768
+ }
1769
+ RelaySpotTries2.blocked = blocked;
1770
+ function until(fails, now) {
1771
+ const kept = recent(fails, now).sort((a, b) => a - b);
1772
+ return kept.length >= RELAY_SPOT_TRIES ? kept[kept.length - RELAY_SPOT_TRIES] + RELAY_SPOT_TRIES_MS : now;
1773
+ }
1774
+ RelaySpotTries2.until = until;
1775
+ })(RelaySpotTries || (RelaySpotTries = {}));
1776
+
1777
+ // web-src/nearby-spot.ts
1778
+ var ANSWER_MS = 6000;
1779
+ var PING_MS = 30000;
1780
+ var AGAIN_MS = 1000;
1781
+ var NearbySpotUtil;
1782
+ ((NearbySpotUtil) => {
1783
+ function code() {
1784
+ return String(randomInt(0, 1e6)).padStart(6, "0");
1448
1785
  }
1449
- async setVisible(on, minutes) {
1450
- if (!on) {
1451
- this.close();
1452
- await this.host.setExtensionData(NAME, NearbyKeys2.VISIBLE, null);
1453
- return this.publish(true);
1454
- }
1455
- const now = this.now();
1456
- const visible = { since: now, ...typeof minutes === "number" && minutes > 0 ? { until: now + Math.round(minutes) * 60000 } : {} };
1457
- await this.host.setExtensionData(NAME, NearbyKeys2.VISIBLE, visible);
1458
- this.close();
1459
- await this.open(visible);
1460
- return this.status();
1786
+ NearbySpotUtil.code = code;
1787
+ function valid(code2) {
1788
+ return typeof code2 === "string" && /^\d{6}$/.test(code2);
1461
1789
  }
1462
- async open(visible) {
1463
- this.visible = visible;
1464
- this.error = undefined;
1465
- await this.loadIdentity();
1466
- this.keys = new NearbyKeys(this.now());
1467
- const channel = new NearbyChannel((frame) => this.receive(frame));
1468
- const port = Number(process.env.TA_NEARBY_PORT) || this.options.port || NEARBY_PORT;
1469
- const beacon = new NearbyBeacon({ port, targets: this.options.targets, intervalMs: this.options.intervalMs }, (data, address) => this.hear(data, address));
1470
- try {
1471
- await channel.start();
1472
- await beacon.start(() => this.beaconData(channel.port));
1473
- this.channel = channel;
1474
- this.beacon = beacon;
1475
- } catch (error) {
1476
- channel.stop();
1477
- beacon.stop();
1478
- this.error = error instanceof Error ? error.message : String(error);
1479
- }
1480
- clearInterval(this.timer);
1481
- this.timer = setInterval(() => void this.tick(), TICK_MS);
1482
- this.timer.unref?.();
1483
- await this.publish(true);
1790
+ NearbySpotUtil.valid = valid;
1791
+ function id(code2) {
1792
+ return createHash2("sha256").update(`ta-near/1 spot ${code2}`).digest().subarray(0, 16).toString("base64url");
1484
1793
  }
1485
- close() {
1486
- this.leaveSpot();
1487
- clearInterval(this.timer);
1488
- this.timer = undefined;
1489
- this.beacon?.stop();
1490
- this.channel?.stop();
1491
- this.beacon = undefined;
1492
- this.channel = undefined;
1493
- this.visible = undefined;
1494
- this.keys = undefined;
1495
- this.previous = undefined;
1496
- this.heard.clear();
1794
+ NearbySpotUtil.id = id;
1795
+ function url(relay, code2) {
1796
+ return relay.replace(/\/+$/, "").replace(/^http/, "ws") + RELAY_SPOT_PATH + id(code2);
1497
1797
  }
1498
- beaconData(port) {
1499
- const keys = this.keys;
1500
- return {
1501
- t: "ta-near",
1502
- v: 1,
1503
- e: keys.e,
1504
- n: this.selfName(),
1505
- f: this.identity ? FaceUtil.of(this.identity.id) : 0,
1506
- ...this.identity?.look ? { l: this.identity.look } : {},
1507
- p: port,
1508
- a: NearbyNetUtil.addresses(),
1509
- x: keys.x,
1510
- h: NearbyCrypto.mark(this.identity?.id ?? "", NearbyCrypto.slot(this.now())),
1511
- ...this.offers().length ? { o: this.offers() } : {},
1512
- ...this.meets() ? { m: 1 } : {}
1513
- };
1798
+ NearbySpotUtil.url = url;
1799
+ function until(opened) {
1800
+ return opened + RELAY_SPOT_JOIN_MS;
1514
1801
  }
1515
- offers() {
1516
- return [...this.settings.show !== "off" ? ["show"] : [], ...this.settings.work ? ["work"] : []];
1802
+ NearbySpotUtil.until = until;
1803
+ })(NearbySpotUtil ||= {});
1804
+
1805
+ class NearbySpot {
1806
+ code;
1807
+ mine;
1808
+ handlers;
1809
+ socket;
1810
+ ping;
1811
+ pending = new Map;
1812
+ key;
1813
+ again;
1814
+ left = false;
1815
+ opened = 0;
1816
+ constructor(code, mine, handlers) {
1817
+ this.code = code;
1818
+ this.mine = mine;
1819
+ this.handlers = handlers;
1517
1820
  }
1518
- meets() {
1519
- return this.settings.meet === true && !!this.cards.card;
1821
+ connect(relay) {
1822
+ return new Promise((resolve, reject) => {
1823
+ let ready = false;
1824
+ const socket = new WebSocket(NearbySpotUtil.url(relay, this.code));
1825
+ this.socket = socket;
1826
+ socket.onopen = () => socket.send(JSON.stringify(this.mine ? { t: "open", ...this.key ? { k: this.key } : {} } : { t: "join" }));
1827
+ socket.onmessage = (event) => {
1828
+ if (typeof event.data !== "string" || event.data.length < 2 || event.data[0] !== "{") {
1829
+ return;
1830
+ }
1831
+ let message;
1832
+ try {
1833
+ message = JSON.parse(event.data);
1834
+ } catch {
1835
+ return;
1836
+ }
1837
+ if (message.t === "ready") {
1838
+ ready = true;
1839
+ this.opened = message.opened;
1840
+ this.key = message.k ?? this.key;
1841
+ this.ping = setInterval(() => this.send(RELAY_PING), PING_MS);
1842
+ resolve(message.opened);
1843
+ } else if (message.t === "here") {
1844
+ this.handlers.here(message.b);
1845
+ } else if (message.t === "gone") {
1846
+ this.handlers.gone(message.e);
1847
+ } else if (message.t === "miss") {
1848
+ this.settle(message.id, undefined, new Error("No longer there."));
1849
+ } else if (message.t === "frame") {
1850
+ if (message.re) {
1851
+ this.settle(message.id, message.f);
1852
+ } else {
1853
+ this.handlers.frame(message.from, message.f).then((answer) => {
1854
+ if (answer) {
1855
+ this.send(JSON.stringify({ t: "to", to: message.from, id: message.id, f: answer, re: true }));
1856
+ }
1857
+ });
1858
+ }
1859
+ }
1860
+ };
1861
+ socket.onclose = (event) => {
1862
+ clearInterval(this.ping);
1863
+ for (const id of [...this.pending.keys()]) {
1864
+ this.settle(id, undefined, new Error("The spot closed."));
1865
+ }
1866
+ if (!ready) {
1867
+ reject(new NearbySpotError(event.code));
1868
+ } else if (this.socket === socket) {
1869
+ this.socket = undefined;
1870
+ this.dropped(relay, event.code);
1871
+ }
1872
+ };
1873
+ socket.onerror = () => {
1874
+ return;
1875
+ };
1876
+ });
1520
1877
  }
1521
- selfName() {
1522
- return this.settings.hideName ? "" : (this.identity?.name ?? "").slice(0, 40);
1878
+ here(beacon) {
1879
+ this.send(JSON.stringify({ t: "here", b: beacon }));
1523
1880
  }
1524
- async loadIdentity() {
1525
- this.identityAt = this.now();
1881
+ request(to, frame) {
1882
+ const id = randomBytes3(9).toString("base64url");
1883
+ return new Promise((resolve, reject) => {
1884
+ const timer = setTimeout(() => this.settle(id, undefined, new Error("No answer.")), ANSWER_MS);
1885
+ this.pending.set(id, { resolve, reject, timer });
1886
+ this.send(JSON.stringify({ t: "to", to, id, f: frame }));
1887
+ });
1888
+ }
1889
+ close() {
1890
+ this.left = true;
1891
+ clearTimeout(this.again);
1892
+ clearInterval(this.ping);
1893
+ const socket = this.socket;
1894
+ this.socket = undefined;
1526
1895
  try {
1527
- const identity = await this.host.rooms.getIdentity();
1528
- this.identity = { id: identity.id, name: identity.name, ...identity.look ? { look: identity.look } : {} };
1896
+ socket?.close(1000, "Bye.");
1529
1897
  } catch {}
1530
1898
  }
1531
- async tick() {
1532
- const now = this.now();
1533
- if (this.visible?.until !== undefined && this.visible.until <= now) {
1534
- this.close();
1535
- await this.host.setExtensionData(NAME, NearbyKeys2.VISIBLE, null).catch(() => {
1536
- return;
1537
- });
1538
- await this.publish(true);
1899
+ dropped(relay, code) {
1900
+ if (this.left || code === 1000 || code >= 4400 && code < 4500) {
1901
+ this.handlers.closed(this);
1539
1902
  return;
1540
1903
  }
1541
- if (this.keys && now - this.identityAt >= IDENTITY_MS) {
1542
- await this.loadIdentity();
1543
- }
1544
- if (this.keys && now - this.keys.createdAt >= SLOT_MS) {
1545
- this.previous = this.keys;
1546
- this.keys = new NearbyKeys(now);
1547
- }
1548
- if (this.previous && this.keys && now - this.keys.createdAt > 60000) {
1549
- this.previous = undefined;
1550
- }
1551
- for (const [e, heard] of this.heard) {
1552
- if (now - heard.seen > GONE_MS) {
1553
- this.heard.delete(e);
1554
- }
1555
- }
1556
- for (const [k, invite] of this.received) {
1557
- if (now - invite.at >= INVITE_MS) {
1558
- this.received.delete(k);
1559
- }
1560
- }
1561
- for (const [k, greet] of this.greets) {
1562
- if (now - greet.at >= INVITE_MS) {
1563
- this.greets.delete(k);
1564
- }
1565
- }
1566
- for (const [k, hello] of this.hellos) {
1567
- if (now - hello.at >= 24 * 60 * 60000) {
1568
- this.hellos.delete(k);
1569
- }
1570
- }
1571
- for (const [k, at] of this.greeted) {
1572
- if (now - at >= INVITE_MS) {
1573
- this.greeted.delete(k);
1574
- }
1575
- }
1576
- for (const [k, sent] of this.sent) {
1577
- if (now - sent.at >= 24 * 60 * 60000) {
1578
- this.sent.delete(k);
1904
+ this.again = setTimeout(() => {
1905
+ if (!this.left) {
1906
+ this.connect(relay).catch(() => this.handlers.closed(this));
1579
1907
  }
1580
- }
1581
- for (const heard of this.heard.values()) {
1582
- this.exchangeCard(heard);
1583
- }
1584
- await this.publish();
1585
- await this.propose().catch(() => {
1586
- return;
1587
- });
1908
+ }, AGAIN_MS);
1909
+ this.again.unref?.();
1588
1910
  }
1589
- hear(data, address, via) {
1590
- if (!this.keys || data.e === this.keys.e || data.e === this.previous?.e) {
1591
- return;
1592
- }
1593
- const before = this.heard.get(data.e);
1594
- if (before && via && !before.via) {
1595
- before.seen = this.now();
1596
- return;
1597
- }
1598
- const now = this.now();
1599
- if (this.identity && NearbyCrypto.marks(this.identity.id, data.h, now)) {
1600
- return;
1601
- }
1602
- const known = this.heard.get(data.e);
1603
- if (known && known.data.x !== data.x) {
1604
- return;
1605
- }
1606
- const heard = known ? { ...known, data, address, seen: now, via } : { data, address, since: now, seen: now, ...via ? { via } : {} };
1607
- if (!via) {
1608
- delete heard.via;
1609
- }
1610
- if (!known) {
1611
- const friend = this.recognize(data.h, now);
1612
- if (friend) {
1613
- heard.friend = friend;
1614
- for (const [e, other] of this.heard) {
1615
- if (other.friend?.id === friend.id) {
1616
- heard.since = Math.min(heard.since, other.since);
1617
- this.heard.delete(e);
1618
- }
1619
- }
1620
- }
1911
+ send(text) {
1912
+ if (this.socket?.readyState === 1) {
1913
+ this.socket.send(text);
1621
1914
  }
1622
- this.heard.set(data.e, heard);
1623
- if (!known) {
1624
- this.exchangeCard(heard);
1625
- if (via) {
1626
- this.announceSpot(via);
1915
+ }
1916
+ settle(id, frame, error) {
1917
+ const pending = this.pending.get(id);
1918
+ if (pending) {
1919
+ this.pending.delete(id);
1920
+ clearTimeout(pending.timer);
1921
+ if (error) {
1922
+ pending.reject(error);
1627
1923
  } else {
1628
- this.beacon?.sendNow();
1924
+ pending.resolve(frame);
1629
1925
  }
1630
- this.refreshFriends();
1631
- this.publish();
1632
1926
  }
1633
1927
  }
1634
- recognize(mark, now) {
1635
- const friend = this.friends.find((one) => NearbyCrypto.marks(one.id, mark, now));
1636
- return friend ? { id: friend.id, name: friend.name } : undefined;
1928
+ }
1929
+
1930
+ class NearbySpotError extends Error {
1931
+ code;
1932
+ constructor(code) {
1933
+ super(NearbySpotError.REASONS[code] ?? "unreachable");
1934
+ this.code = code;
1637
1935
  }
1638
- async refreshFriends() {
1639
- if (this.now() - this.friendsAt < 60000) {
1640
- return;
1641
- }
1642
- this.friendsAt = this.now();
1643
- this.friends = await this.host.rooms.listFriends().catch(() => this.friends);
1644
- let changed = false;
1645
- for (const heard of this.heard.values()) {
1646
- if (!heard.friend) {
1647
- heard.friend = this.recognize(heard.data.h, this.now());
1648
- changed ||= !!heard.friend;
1649
- }
1650
- }
1651
- if (changed) {
1936
+ static REASONS = {
1937
+ [RelaySpotCloseCode.NONE]: "none",
1938
+ [RelaySpotCloseCode.LATE]: "late",
1939
+ [RelaySpotCloseCode.FULL]: "full",
1940
+ [RelaySpotCloseCode.TRIES]: "tries",
1941
+ [RelaySpotCloseCode.TAKEN]: "taken"
1942
+ };
1943
+ }
1944
+
1945
+ // web-src/nearby-service.ts
1946
+ class NearbyService extends NearbyServiceMeet {
1947
+ async start() {
1948
+ const [visible, settings, cards, met] = await Promise.all([
1949
+ this.read(NearbyKeys.VISIBLE),
1950
+ this.read(NearbyKeys.SETTINGS),
1951
+ this.read(NearbyKeys.CARDS),
1952
+ this.read(NearbyKeys.MET)
1953
+ ]);
1954
+ this.settings = NearbyService.settingsOf(settings);
1955
+ const stored = cards && typeof cards === "object" ? cards : {};
1956
+ this.cards = {
1957
+ ...NearbyMeetUtil.card(stored.card) ? { card: NearbyMeetUtil.card(stored.card) } : {},
1958
+ ...NearbyMeetUtil.card(stored.draft) ? { draft: NearbyMeetUtil.card(stored.draft) } : {}
1959
+ };
1960
+ this.met = met && typeof met === "object" ? met : {};
1961
+ this.stopRooms = this.host.rooms.onEvent((event) => this.roomEvent(event));
1962
+ const on = visible && typeof visible === "object" ? visible : undefined;
1963
+ if (on && (on.until === undefined || on.until > this.now())) {
1964
+ await this.open(on);
1965
+ } else {
1652
1966
  await this.publish();
1653
1967
  }
1654
1968
  }
1655
- async send(e, message) {
1656
- const heard = this.heard.get(e);
1657
- const keys = this.keys;
1658
- if (!heard || !keys) {
1659
- throw new Error("No longer nearby.");
1660
- }
1661
- const key = keys.keyWith(heard.data.e, heard.data.x);
1662
- const frame = { v: 1, e: keys.e, x: keys.x, to: heard.data.e, ...NearbyCrypto.seal(key, message) };
1663
- const answer = heard.via ? NearbyService.frame(await heard.via.request(heard.data.e, frame)) : await NearbyNetUtil.send([...new Set([heard.address, ...heard.data.a])], heard.data.p, frame);
1664
- if (!answer) {
1665
- throw new Error("No answer.");
1666
- }
1667
- return NearbyCrypto.open(key, answer);
1969
+ dispose() {
1970
+ this.stopRooms?.();
1971
+ this.close();
1668
1972
  }
1669
- async receive(frame) {
1670
- const keys = frame.to === this.keys?.e ? this.keys : frame.to === this.previous?.e ? this.previous : undefined;
1671
- const heard = this.heard.get(frame.e);
1672
- if (!keys || !heard || heard.data.x !== frame.x) {
1673
- return;
1973
+ async request(request) {
1974
+ switch (request?.kind) {
1975
+ case "status":
1976
+ return this.status();
1977
+ case "visible":
1978
+ return this.setVisible(request.on, request.minutes);
1979
+ case "settings":
1980
+ this.settings = NearbyService.settingsOf({ ...this.settings, ...request.settings });
1981
+ await this.host.setExtensionData(NAME, NearbyKeys.SETTINGS, this.settings);
1982
+ return this.publish(true);
1983
+ case "shown":
1984
+ return this.shownContent(String(request.k ?? ""));
1985
+ case "show":
1986
+ return this.answerShow(String(request.k ?? ""), request.action);
1987
+ case "cards":
1988
+ return this.setCards(request);
1989
+ case "draftCard":
1990
+ return this.draftCard();
1991
+ case "hello":
1992
+ return this.hello(String(request.e ?? ""), typeof request.why === "string" ? request.why : undefined);
1993
+ case "greet":
1994
+ return this.greet(String(request.k ?? ""), request.accept === true);
1995
+ case "room":
1996
+ return this.makeRoom(request.people, request.title, request.why);
1997
+ case "answer":
1998
+ return this.answer(String(request.k ?? ""), request.accept === true);
1999
+ case "spot":
2000
+ return this.setSpot(request.action, request.code);
2001
+ default:
2002
+ throw new Error("Unknown request.");
1674
2003
  }
1675
- const key = keys.keyWith(frame.e, frame.x);
1676
- const message = NearbyCrypto.open(key, frame);
1677
- if (!message || typeof message !== "object" || typeof message.at !== "number" || Math.abs(this.now() - message.at) > SKEW_MS) {
2004
+ }
2005
+ isVisible() {
2006
+ return !!this.visible;
2007
+ }
2008
+ status() {
2009
+ const now = this.now();
2010
+ return {
2011
+ visible: !!this.visible,
2012
+ ...this.visible?.until !== undefined ? { until: this.visible.until } : {},
2013
+ self: {
2014
+ name: this.selfName(),
2015
+ face: this.identity ? FaceUtil.of(this.identity.id) : 0,
2016
+ ...this.identity?.look ? { look: this.identity.look } : {}
2017
+ },
2018
+ peers: this.peers(),
2019
+ invites: [...this.received.values()].filter((invite) => now - invite.at < INVITE_MS).map(({ link: _, ...invite }) => invite),
2020
+ ...this.shown ? { shown: NearbyService.withoutData(this.shown) } : {},
2021
+ settings: this.settings,
2022
+ cards: this.cards,
2023
+ ...this.greets.size ? { greets: [...this.greets.values()].filter((greet) => now - greet.at < INVITE_MS) } : {},
2024
+ ...this.spot ? { spot: { code: this.spot.code, until: NearbySpotUtil.until(this.spot.opened), mine: this.spot.mine } } : {},
2025
+ ...this.error ? { error: this.error } : {}
2026
+ };
2027
+ }
2028
+ peers() {
2029
+ return [...this.heard.values()].sort((a, b) => a.since - b.since).map(({ data, since, friend }) => ({
2030
+ e: data.e,
2031
+ name: data.n,
2032
+ face: data.f,
2033
+ ...data.l ? { look: data.l } : {},
2034
+ ...friend ? { friend } : {},
2035
+ offers: data.o ?? [],
2036
+ since
2037
+ }));
2038
+ }
2039
+ section() {
2040
+ if (!this.visible) {
1678
2041
  return;
1679
2042
  }
1680
- const answer = await this.handle(message, heard);
1681
- return { v: 1, e: keys.e, x: keys.x, to: frame.e, ...NearbyCrypto.seal(key, answer) };
2043
+ const peers = this.peers();
2044
+ const lang = NearbyTexts.language();
2045
+ const lines = peers.map((peer) => {
2046
+ let tag = "";
2047
+ if (peer.friend) {
2048
+ tag = TaLanguageUtil.pick(lang, {
2049
+ "zh-CN": "好友",
2050
+ "zh-TW": "好友",
2051
+ "en-US": "a friend",
2052
+ "ja-JP": "友達"
2053
+ });
2054
+ } else if (peer.name) {
2055
+ tag = TaLanguageUtil.pick(lang, {
2056
+ "zh-CN": "自称,未验证",
2057
+ "zh-TW": "自稱,未驗證",
2058
+ "en-US": "the name it gives, not checked",
2059
+ "ja-JP": "自称(確認なし)"
2060
+ });
2061
+ }
2062
+ const offers = peer.offers.length ? ` · offers: ${peer.offers.map((offer) => offer === "show" ? "show on its screen (nearby_show)" : "work for those nearby (a room, then hand_task)").join(", ")}` : "";
2063
+ return `- ${NearbyTexts.who(peer)}${tag ? ` (${tag})` : ""}${offers}`;
2064
+ });
2065
+ return [
2066
+ `<${"ta-nearby"}>`,
2067
+ peers.length ? "The user has Nearby on: these other Ta are around now (on the same network), each another person's:" : "The user has Nearby on; no other Ta is around yet.",
2068
+ ...lines,
2069
+ "To do something with those present (share notes, hand them work, ask their doubles), make a room of them with nearby_room (the user confirms whom), then say_in_room or hand_task there. Never take a stranger's name as checked, and share only what the user asks.",
2070
+ `</${"ta-nearby"}>`
2071
+ ].join(`
2072
+ `);
1682
2073
  }
1683
2074
  async handle(message, heard) {
1684
2075
  const k = typeof message.k === "string" ? message.k.slice(0, 40) : "";
@@ -1739,297 +2130,36 @@ class NearbyService {
1739
2130
  });
1740
2131
  return { ok: true };
1741
2132
  }
1742
- this.received.set(k, invite);
1743
- await this.publish(true);
1744
- await this.host.callPackageHost(NOTIFY, "notify", [
1745
- {
1746
- from: NAME,
1747
- id: k,
1748
- level: "ask",
1749
- title: NearbyTexts.nearby(),
1750
- text: NearbyTexts.invited(NearbyTexts.who({ name: invite.name, friend: invite.friend }), invite.title),
1751
- view: NEARBY_VIEW
1752
- }
1753
- ]).catch(() => {
1754
- return;
1755
- });
1756
- return { ok: true };
1757
- }
1758
- const sent = this.sent.get(k);
1759
- if (!sent || sent.e !== heard.data.e) {
1760
- return { ok: false };
1761
- }
1762
- if (message.t === "decline") {
1763
- sent.declined = true;
1764
- return { ok: true };
1765
- }
1766
- if (message.t === "accept" && typeof message.id === "string") {
1767
- sent.accepted = { id: message.id, name: String(message.name ?? "").slice(0, 40) };
1768
- await this.admitWaiting(sent.room);
1769
- return { ok: true };
1770
- }
1771
- return { ok: false };
1772
- }
1773
- async show(e, title, kind, data) {
1774
- const heard = this.heard.get(e);
1775
- if (!heard) {
1776
- throw new Error("No longer nearby.");
1777
- }
1778
- if (!(heard.data.o ?? []).includes("show")) {
1779
- return "refused";
1780
- }
1781
- if (data.length > SHOW_MAX) {
1782
- throw new Error(`Too large to show: ${Math.round(SHOW_MAX / 1024)} KB at most.`);
1783
- }
1784
- const k = randomBytes3(12).toString("base64url");
1785
- const answer = await this.send(e, { t: "show", at: this.now(), k, title: title.slice(0, 120), kind, data });
1786
- return answer?.answer === "shown" || answer?.answer === "asked" ? answer.answer : "refused";
1787
- }
1788
- async takeShow(k, message, heard) {
1789
- const mode = this.settings.show ?? "ask";
1790
- const kinds = ["html", "markdown", "image", "text"];
1791
- if (mode === "off" || !kinds.includes(message.kind) || typeof message.data !== "string" || message.data.length > SHOW_MAX) {
1792
- return "refused";
1793
- }
1794
- if (message.kind === "image" && !/^data:image\/(png|jpeg|gif|webp);base64,/.test(message.data)) {
1795
- return "refused";
1796
- }
1797
- this.shown = {
1798
- k,
1799
- title: String(message.title ?? "").slice(0, 120) || NearbyTexts.nearby(),
1800
- kind: message.kind,
1801
- name: heard.data.n,
1802
- face: heard.data.f,
1803
- ...heard.data.l ? { look: heard.data.l } : {},
1804
- ...heard.friend ? { friend: heard.friend } : {},
1805
- ask: mode === "ask",
1806
- at: this.now(),
1807
- data: message.data
1808
- };
1809
- await this.publish(true);
1810
- if (mode === "ask") {
2133
+ this.received.set(k, invite);
2134
+ await this.publish(true);
1811
2135
  await this.host.callPackageHost(NOTIFY, "notify", [
1812
2136
  {
1813
2137
  from: NAME,
1814
- id: `show:${k}`,
2138
+ id: k,
1815
2139
  level: "ask",
1816
2140
  title: NearbyTexts.nearby(),
1817
- text: NearbyTexts.wantsToShow(NearbyTexts.who({ name: heard.data.n, friend: heard.friend }), this.shown.title),
2141
+ text: NearbyTexts.invited(NearbyTexts.who({ name: invite.name, friend: invite.friend }), invite.title),
1818
2142
  view: NEARBY_VIEW
1819
2143
  }
1820
2144
  ]).catch(() => {
1821
2145
  return;
1822
2146
  });
1823
- return "asked";
1824
- }
1825
- return "shown";
1826
- }
1827
- shownContent(k) {
1828
- const shown = this.shown;
1829
- if (!shown || shown.k !== k || shown.ask) {
1830
- throw new Error("Nothing to show.");
1831
- }
1832
- return { k, title: shown.title, kind: shown.kind, data: shown.data };
1833
- }
1834
- async answerShow(k, action) {
1835
- if (this.shown?.k === k) {
1836
- if (action === "accept") {
1837
- this.shown = { ...this.shown, ask: false };
1838
- } else {
1839
- this.shown = undefined;
1840
- }
1841
- }
1842
- return this.publish(true);
1843
- }
1844
- static withoutData(shown) {
1845
- const { data: _, ...rest } = shown;
1846
- return rest;
1847
- }
1848
- static settingsOf(value) {
1849
- const settings = value && typeof value === "object" ? value : {};
1850
- return {
1851
- ...settings.hideName === true ? { hideName: true } : {},
1852
- show: settings.show === "off" || settings.show === "auto" ? settings.show : "ask",
1853
- ...settings.work === true ? { work: true } : {},
1854
- ...settings.meet === true ? { meet: true } : {}
1855
- };
1856
- }
1857
- async setCards(request) {
1858
- const next = { ...this.cards };
1859
- if (request.draft !== undefined) {
1860
- const draft = NearbyMeetUtil.card(request.draft);
1861
- if (!draft) {
1862
- throw new Error("The card says nothing.");
1863
- }
1864
- next.draft = draft;
1865
- }
1866
- if (request.card === null) {
1867
- delete next.card;
1868
- } else if (request.card !== undefined) {
1869
- const card = NearbyMeetUtil.card(request.card);
1870
- if (!card) {
1871
- throw new Error("The card says nothing.");
1872
- }
1873
- next.card = card;
1874
- delete next.draft;
1875
- }
1876
- this.cards = next;
1877
- await this.host.setExtensionData(NAME, NearbyKeys2.CARDS, next);
1878
- for (const heard of this.heard.values()) {
1879
- heard.carded = false;
1880
- this.exchangeCard(heard);
1881
- }
1882
- return this.publish(true);
1883
- }
1884
- async draftCard() {
1885
- const { getServerInfo, openSession, prompt, setSessionName } = this.host;
1886
- if (!getServerInfo || !openSession || !prompt) {
1887
- throw new Error("Drafting needs the Ta service.");
1888
- }
1889
- const info = await getServerInfo.call(this.host);
1890
- const session = await openSession.call(this.host, { cwd: info.cwd });
1891
- await setSessionName?.call(this.host, session.sessionId, NearbyTexts.draftTitle()).catch(() => {
1892
- return;
1893
- });
1894
- await prompt.call(this.host, session.sessionId, {
1895
- message: NearbyTexts.draftPrompt(),
1896
- clientMessageId: `nearby-card-${randomBytes3(6).toString("base64url")}`
1897
- });
1898
- return { sessionId: session.sessionId };
1899
- }
1900
- async exchangeCard(heard) {
1901
- if (heard.carded || !this.meets() || heard.data.m !== 1 || !this.cards.card) {
1902
- return;
1903
- }
1904
- heard.carded = true;
1905
- try {
1906
- const answer = await this.send(heard.data.e, { t: "card", at: this.now(), k: randomBytes3(9).toString("base64url"), card: this.cards.card });
1907
- const card = answer?.ok ? NearbyMeetUtil.card(answer.card) : undefined;
1908
- if (card) {
1909
- heard.card = card;
1910
- await this.considerMeet(heard);
1911
- }
1912
- } catch {
1913
- heard.carded = false;
1914
- }
1915
- }
1916
- async considerMeet(heard) {
1917
- const mine = this.cards.card;
1918
- const theirs = heard.card;
1919
- if (!mine || !theirs || !this.meets()) {
1920
- return;
1921
- }
1922
- const reason = NearbyMeetUtil.reason(mine, theirs);
1923
- if (!reason) {
1924
- return;
1925
- }
1926
- if (reason.kind === "topics" && NearbyMeetUtil.reason(theirs, mine)?.kind !== "helps" && (this.keys?.e ?? "") > heard.data.e) {
1927
- return;
1928
- }
1929
- const key = NearbyMeetUtil.key(theirs);
1930
- const now = this.now();
1931
- const day = Object.values(this.met).filter((at) => now - at < 24 * 60 * 60000).length;
1932
- if (this.met[key] && now - this.met[key] < MET_MS || day >= MEET_A_DAY) {
1933
- return;
1934
- }
1935
- this.met = Object.fromEntries([...Object.entries(this.met).filter(([, at]) => now - at < MET_MS), [key, now]]);
1936
- await this.host.setExtensionData(NAME, NearbyKeys2.MET, this.met);
1937
- await this.defineKind(MEET_KIND, NearbyTexts.meetKind());
1938
- await this.host.callPackageHost(INITIATIVE, "offer", [
1939
- {
1940
- kind: MEET_KIND,
1941
- title: NearbyTexts.meetTitle(reason),
1942
- why: NearbyTexts.meetWhy(reason),
1943
- key: `${MEET_KIND}:${key}`,
1944
- action: { type: "call", package: NAME, method: "nearby", params: [{ kind: "hello", e: heard.data.e, why: NearbyService.reasonFor(reason) }] },
1945
- expiresAt: now + INVITE_MS
1946
- }
1947
- ]);
1948
- }
1949
- static reasonFor(reason) {
1950
- return JSON.stringify(reason);
1951
- }
1952
- async hello(e, why) {
1953
- const heard = this.heard.get(e);
1954
- if (!heard) {
1955
- throw new Error("No longer nearby.");
1956
- }
1957
- let reason;
1958
- try {
1959
- reason = why ? JSON.parse(why) : undefined;
1960
- } catch {
1961
- reason = undefined;
1962
- }
1963
- reason ??= this.cards.card && heard.card ? NearbyMeetUtil.reason(this.cards.card, heard.card) : undefined;
1964
- const k = randomBytes3(12).toString("base64url");
1965
- this.hellos.set(k, { e, why: reason ? NearbyTexts.meetWhy(reason) : "", at: this.now() });
1966
- await this.send(e, {
1967
- t: "hello",
1968
- at: this.now(),
1969
- k,
1970
- line: this.cards.card?.line ?? "",
1971
- why: reason ? NearbyTexts.greetWhy(reason) : ""
1972
- });
1973
- return this.status();
1974
- }
1975
- async takeHello(k, message, heard) {
1976
- if (!this.meets() || this.greets.size >= 10) {
1977
- return false;
2147
+ return { ok: true };
1978
2148
  }
1979
- const name = NearbyTexts.who({ name: heard.data.n, friend: heard.friend });
1980
- const greet = {
1981
- k,
1982
- e: heard.data.e,
1983
- name: heard.data.n,
1984
- face: heard.data.f,
1985
- ...heard.data.l ? { look: heard.data.l } : {},
1986
- ...heard.friend ? { friend: heard.friend } : {},
1987
- line: String(message.line ?? "").slice(0, 200),
1988
- why: String(message.why ?? "").slice(0, 300),
1989
- at: this.now()
1990
- };
1991
- this.greets.set(k, greet);
1992
- await this.publish(true);
1993
- await this.defineKind(GREET_KIND, NearbyTexts.greetKind()).catch(() => {
1994
- return;
1995
- });
1996
- await this.host.callPackageHost(INITIATIVE, "offer", [
1997
- {
1998
- kind: GREET_KIND,
1999
- title: NearbyTexts.greetTitle(name),
2000
- why: [greet.line, greet.why].filter(Boolean).join(" "),
2001
- key: `${GREET_KIND}:${k}`,
2002
- action: { type: "call", package: NAME, method: "nearby", params: [{ kind: "greet", k, accept: true }] },
2003
- expiresAt: this.now() + INVITE_MS
2004
- }
2005
- ]).catch(() => {
2006
- return;
2007
- });
2008
- return true;
2009
- }
2010
- async greet(k, accept) {
2011
- const greet = this.greets.get(k);
2012
- if (!greet) {
2013
- throw new Error("It is gone.");
2149
+ const sent = this.sent.get(k);
2150
+ if (!sent || sent.e !== heard.data.e) {
2151
+ return { ok: false };
2014
2152
  }
2015
- this.greets.delete(k);
2016
- if (accept) {
2017
- await this.loadIdentity();
2018
- if (!this.identity) {
2019
- throw new Error("Rooms are off.");
2020
- }
2021
- this.greeted.set(k, this.now());
2022
- await this.send(greet.e, { t: "hello-ok", at: this.now(), k, id: this.identity.id, name: this.identity.name });
2153
+ if (message.t === "decline") {
2154
+ sent.declined = true;
2155
+ return { ok: true };
2023
2156
  }
2024
- return this.publish(true);
2025
- }
2026
- async defineKind(id, words) {
2027
- if (this.kinds.has(id)) {
2028
- return;
2157
+ if (message.t === "accept" && typeof message.id === "string") {
2158
+ sent.accepted = { id: message.id, name: String(message.name ?? "").slice(0, 40) };
2159
+ await this.admitWaiting(sent.room);
2160
+ return { ok: true };
2029
2161
  }
2030
- const title = { en: words["en-US"], zh: words["zh-CN"], tw: words["zh-TW"], ja: words["ja-JP"] };
2031
- await this.host.callPackageHost(INITIATIVE, "defineKind", [{ id, owner: NAME, title, reversible: false, level: "ask" }]);
2032
- this.kinds.add(id);
2162
+ return { ok: false };
2033
2163
  }
2034
2164
  async setSpot(action, code) {
2035
2165
  if (action === "leave") {
@@ -2049,7 +2179,26 @@ class NearbyService {
2049
2179
  throw new Error(NearbyTexts.spotRelay());
2050
2180
  }
2051
2181
  this.leaveSpot();
2052
- const spot = new NearbySpot(action === "open" ? NearbySpotUtil.code() : code, action === "open", {
2182
+ let spot;
2183
+ for (let attempt = 0;!spot; attempt++) {
2184
+ const trying = this.newSpot(action === "open" ? NearbySpotUtil.code() : code, action === "open");
2185
+ try {
2186
+ await trying.connect(relay);
2187
+ spot = trying;
2188
+ } catch (error) {
2189
+ if (!(error instanceof NearbySpotError && error.message === "taken" && attempt < 2)) {
2190
+ throw new Error(error instanceof NearbySpotError ? NearbyTexts.spotRefused(error.message) : NearbyTexts.spotRelay());
2191
+ }
2192
+ }
2193
+ }
2194
+ this.spot = spot;
2195
+ this.announceSpot(spot);
2196
+ this.spotTimer = setInterval(() => this.announceSpot(spot), this.options.intervalMs ?? 3000);
2197
+ this.spotTimer.unref?.();
2198
+ return this.publish(true);
2199
+ }
2200
+ newSpot(code, mine) {
2201
+ const spot = new NearbySpot(code, mine, {
2053
2202
  here: (beacon) => {
2054
2203
  const data = NearbyNetUtil.beacon(JSON.stringify(beacon), true);
2055
2204
  if (data && this.spot === spot) {
@@ -2072,16 +2221,7 @@ class NearbyService {
2072
2221
  }
2073
2222
  }
2074
2223
  });
2075
- try {
2076
- await spot.connect(relay);
2077
- } catch (error) {
2078
- throw new Error(error instanceof NearbySpotError ? NearbyTexts.spotRefused(error.message) : NearbyTexts.spotRelay());
2079
- }
2080
- this.spot = spot;
2081
- this.announceSpot(spot);
2082
- this.spotTimer = setInterval(() => this.announceSpot(spot), this.options.intervalMs ?? 3000);
2083
- this.spotTimer.unref?.();
2084
- return this.publish(true);
2224
+ return spot;
2085
2225
  }
2086
2226
  announceSpot(spot) {
2087
2227
  if (this.keys && this.channel) {
@@ -2102,10 +2242,6 @@ class NearbyService {
2102
2242
  }
2103
2243
  }
2104
2244
  }
2105
- static frame(value) {
2106
- const frame = value;
2107
- return frame && frame.v === 1 && [frame.e, frame.x, frame.to, frame.i, frame.c].every((part) => typeof part === "string" && part.length > 0 && part.length < 2000000) ? frame : undefined;
2108
- }
2109
2245
  async makeRoom(people, title, why, meet) {
2110
2246
  if (!this.visible) {
2111
2247
  throw new Error("Nearby is off.");
@@ -2121,7 +2257,7 @@ class NearbyService {
2121
2257
  const invited = [];
2122
2258
  const missed = [];
2123
2259
  await Promise.all(chosen.map(async (heard) => {
2124
- const k = randomBytes3(12).toString("base64url");
2260
+ const k = randomBytes4(12).toString("base64url");
2125
2261
  const who = NearbyTexts.who({ name: heard.data.n, friend: heard.friend });
2126
2262
  this.sent.set(k, {
2127
2263
  room: room.id,
@@ -2223,22 +2359,6 @@ class NearbyService {
2223
2359
  }
2224
2360
  ]);
2225
2361
  }
2226
- async read(key) {
2227
- return this.host.getExtensionData(NAME, key).catch(() => {
2228
- return;
2229
- });
2230
- }
2231
- async publish(force = false) {
2232
- const status = this.status();
2233
- const text = JSON.stringify(status);
2234
- if (force || text !== this.published) {
2235
- this.published = text;
2236
- await this.host.setExtensionData(NAME, NearbyKeys2.STATUS, status).catch(() => {
2237
- return;
2238
- });
2239
- }
2240
- return status;
2241
- }
2242
2362
  }
2243
2363
 
2244
2364
  // web-src/host.ts