@ours.network/messenger-server 2.0.4-nightly.1 → 2.1.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.
|
@@ -10,7 +10,7 @@ import {
|
|
|
10
10
|
publicEngineError,
|
|
11
11
|
publicInternalError,
|
|
12
12
|
reportFailure
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-3JYT7LXJ.js";
|
|
14
14
|
|
|
15
15
|
// node_modules/bn.js/lib/bn.js
|
|
16
16
|
var require_bn = __commonJS({
|
|
@@ -3144,7 +3144,7 @@ var require_buffer = __commonJS({
|
|
|
3144
3144
|
const isCompatible = typeof data === "object" && data.constructor.name === "EncoderBuffer" && typeof data.length === "number" && typeof data.join === "function";
|
|
3145
3145
|
return isCompatible;
|
|
3146
3146
|
};
|
|
3147
|
-
EncoderBuffer.prototype.join = function
|
|
3147
|
+
EncoderBuffer.prototype.join = function join7(out, offset) {
|
|
3148
3148
|
if (!out)
|
|
3149
3149
|
out = Buffer2.alloc(this.length);
|
|
3150
3150
|
if (!offset)
|
|
@@ -3622,17 +3622,17 @@ var require_node = __commonJS({
|
|
|
3622
3622
|
else
|
|
3623
3623
|
return;
|
|
3624
3624
|
}
|
|
3625
|
-
let
|
|
3625
|
+
let content2 = null;
|
|
3626
3626
|
let primitive = false;
|
|
3627
3627
|
if (state.any) {
|
|
3628
3628
|
result = this._createEncoderBuffer(data);
|
|
3629
3629
|
} else if (state.choice) {
|
|
3630
3630
|
result = this._encodeChoice(data, reporter);
|
|
3631
3631
|
} else if (state.contains) {
|
|
3632
|
-
|
|
3632
|
+
content2 = this._getUse(state.contains, parent)._encode(data, reporter);
|
|
3633
3633
|
primitive = true;
|
|
3634
3634
|
} else if (state.children) {
|
|
3635
|
-
|
|
3635
|
+
content2 = state.children.map(function(child) {
|
|
3636
3636
|
if (child._baseState.tag === "null_")
|
|
3637
3637
|
return child._encode(null, reporter, data);
|
|
3638
3638
|
if (child._baseState.key === null)
|
|
@@ -3646,7 +3646,7 @@ var require_node = __commonJS({
|
|
|
3646
3646
|
}, this).filter(function(child) {
|
|
3647
3647
|
return child;
|
|
3648
3648
|
});
|
|
3649
|
-
|
|
3649
|
+
content2 = this._createEncoderBuffer(content2);
|
|
3650
3650
|
} else {
|
|
3651
3651
|
if (state.tag === "seqof" || state.tag === "setof") {
|
|
3652
3652
|
if (!(state.args && state.args.length === 1))
|
|
@@ -3655,14 +3655,14 @@ var require_node = __commonJS({
|
|
|
3655
3655
|
return reporter.error("seqof/setof, but data is not Array");
|
|
3656
3656
|
const child = this.clone();
|
|
3657
3657
|
child._baseState.implicit = null;
|
|
3658
|
-
|
|
3658
|
+
content2 = this._createEncoderBuffer(data.map(function(item) {
|
|
3659
3659
|
const state2 = this._baseState;
|
|
3660
3660
|
return this._getUse(state2.args[0], data)._encode(item, reporter);
|
|
3661
3661
|
}, child));
|
|
3662
3662
|
} else if (state.use !== null) {
|
|
3663
3663
|
result = this._getUse(state.use, parent)._encode(data, reporter);
|
|
3664
3664
|
} else {
|
|
3665
|
-
|
|
3665
|
+
content2 = this._encodePrimitive(state.tag, data);
|
|
3666
3666
|
primitive = true;
|
|
3667
3667
|
}
|
|
3668
3668
|
}
|
|
@@ -3674,7 +3674,7 @@ var require_node = __commonJS({
|
|
|
3674
3674
|
reporter.error("Tag could be omitted only for .use()");
|
|
3675
3675
|
} else {
|
|
3676
3676
|
if (state.use === null)
|
|
3677
|
-
result = this._encodeComposite(tag, primitive, cls,
|
|
3677
|
+
result = this._encodeComposite(tag, primitive, cls, content2);
|
|
3678
3678
|
}
|
|
3679
3679
|
}
|
|
3680
3680
|
if (state.explicit !== null)
|
|
@@ -3803,23 +3803,23 @@ var require_der2 = __commonJS({
|
|
|
3803
3803
|
Node.call(this, "der", parent);
|
|
3804
3804
|
}
|
|
3805
3805
|
inherits(DERNode, Node);
|
|
3806
|
-
DERNode.prototype._encodeComposite = function encodeComposite(tag, primitive, cls,
|
|
3806
|
+
DERNode.prototype._encodeComposite = function encodeComposite(tag, primitive, cls, content2) {
|
|
3807
3807
|
const encodedTag = encodeTag(tag, primitive, cls, this.reporter);
|
|
3808
|
-
if (
|
|
3808
|
+
if (content2.length < 128) {
|
|
3809
3809
|
const header2 = Buffer2.alloc(2);
|
|
3810
3810
|
header2[0] = encodedTag;
|
|
3811
|
-
header2[1] =
|
|
3812
|
-
return this._createEncoderBuffer([header2,
|
|
3811
|
+
header2[1] = content2.length;
|
|
3812
|
+
return this._createEncoderBuffer([header2, content2]);
|
|
3813
3813
|
}
|
|
3814
3814
|
let lenOctets = 1;
|
|
3815
|
-
for (let i =
|
|
3815
|
+
for (let i = content2.length; i >= 256; i >>= 8)
|
|
3816
3816
|
lenOctets++;
|
|
3817
3817
|
const header = Buffer2.alloc(1 + 1 + lenOctets);
|
|
3818
3818
|
header[0] = encodedTag;
|
|
3819
3819
|
header[1] = 128 | lenOctets;
|
|
3820
|
-
for (let i = 1 + lenOctets, j =
|
|
3820
|
+
for (let i = 1 + lenOctets, j = content2.length; j > 0; i--, j >>= 8)
|
|
3821
3821
|
header[i] = j & 255;
|
|
3822
|
-
return this._createEncoderBuffer([header,
|
|
3822
|
+
return this._createEncoderBuffer([header, content2]);
|
|
3823
3823
|
};
|
|
3824
3824
|
DERNode.prototype._encodeStr = function encodeStr(str2, tag) {
|
|
3825
3825
|
if (tag === "bitstr") {
|
|
@@ -6702,8 +6702,8 @@ var require_helpers = __commonJS({
|
|
|
6702
6702
|
function req(url, opts = {}) {
|
|
6703
6703
|
const href = typeof url === "string" ? url : url.href;
|
|
6704
6704
|
const req2 = (href.startsWith("https:") ? https : http).request(url, opts);
|
|
6705
|
-
const promise = new Promise((
|
|
6706
|
-
req2.once("response",
|
|
6705
|
+
const promise = new Promise((resolve5, reject) => {
|
|
6706
|
+
req2.once("response", resolve5).once("error", reject).end();
|
|
6707
6707
|
});
|
|
6708
6708
|
req2.then = promise.then.bind(promise);
|
|
6709
6709
|
return req2;
|
|
@@ -6882,7 +6882,7 @@ var require_parse_proxy_response = __commonJS({
|
|
|
6882
6882
|
var debug_1 = __importDefault(require_src());
|
|
6883
6883
|
var debug = (0, debug_1.default)("https-proxy-agent:parse-proxy-response");
|
|
6884
6884
|
function parseProxyResponse(socket) {
|
|
6885
|
-
return new Promise((
|
|
6885
|
+
return new Promise((resolve5, reject) => {
|
|
6886
6886
|
let buffersLength = 0;
|
|
6887
6887
|
const buffers = [];
|
|
6888
6888
|
function read() {
|
|
@@ -6948,7 +6948,7 @@ var require_parse_proxy_response = __commonJS({
|
|
|
6948
6948
|
}
|
|
6949
6949
|
debug("got proxy server response: %o %o", firstLine, headers);
|
|
6950
6950
|
cleanup2();
|
|
6951
|
-
|
|
6951
|
+
resolve5({
|
|
6952
6952
|
connect: {
|
|
6953
6953
|
statusCode,
|
|
6954
6954
|
statusText,
|
|
@@ -7346,7 +7346,7 @@ var require_web_push_lib = __commonJS({
|
|
|
7346
7346
|
} catch (err) {
|
|
7347
7347
|
return Promise.reject(err);
|
|
7348
7348
|
}
|
|
7349
|
-
return new Promise(function(
|
|
7349
|
+
return new Promise(function(resolve5, reject) {
|
|
7350
7350
|
const httpsOptions = {};
|
|
7351
7351
|
const urlParts = url.parse(requestDetails.endpoint);
|
|
7352
7352
|
httpsOptions.hostname = urlParts.hostname;
|
|
@@ -7379,7 +7379,7 @@ var require_web_push_lib = __commonJS({
|
|
|
7379
7379
|
requestDetails.endpoint
|
|
7380
7380
|
));
|
|
7381
7381
|
} else {
|
|
7382
|
-
|
|
7382
|
+
resolve5({
|
|
7383
7383
|
statusCode: pushResponse.statusCode,
|
|
7384
7384
|
body: responseText,
|
|
7385
7385
|
headers: pushResponse.headers
|
|
@@ -9679,7 +9679,7 @@ var require_websocket = __commonJS({
|
|
|
9679
9679
|
var http = __require("http");
|
|
9680
9680
|
var net = __require("net");
|
|
9681
9681
|
var tls = __require("tls");
|
|
9682
|
-
var { randomBytes:
|
|
9682
|
+
var { randomBytes: randomBytes4, createHash: createHash6 } = __require("crypto");
|
|
9683
9683
|
var { Duplex, Readable } = __require("stream");
|
|
9684
9684
|
var { URL: URL2 } = __require("url");
|
|
9685
9685
|
var PerMessageDeflate2 = require_permessage_deflate();
|
|
@@ -10230,7 +10230,7 @@ var require_websocket = __commonJS({
|
|
|
10230
10230
|
}
|
|
10231
10231
|
}
|
|
10232
10232
|
const defaultPort = isSecure ? 443 : 80;
|
|
10233
|
-
const key =
|
|
10233
|
+
const key = randomBytes4(16).toString("base64");
|
|
10234
10234
|
const request = isSecure ? https.request : http.request;
|
|
10235
10235
|
const protocolSet = /* @__PURE__ */ new Set();
|
|
10236
10236
|
let perMessageDeflate;
|
|
@@ -10360,7 +10360,7 @@ var require_websocket = __commonJS({
|
|
|
10360
10360
|
abortHandshake(websocket, socket, "Invalid Upgrade header");
|
|
10361
10361
|
return;
|
|
10362
10362
|
}
|
|
10363
|
-
const digest =
|
|
10363
|
+
const digest = createHash6("sha1").update(key + GUID).digest("base64");
|
|
10364
10364
|
if (res.headers["sec-websocket-accept"] !== digest) {
|
|
10365
10365
|
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
|
|
10366
10366
|
return;
|
|
@@ -10732,7 +10732,7 @@ var require_websocket_server = __commonJS({
|
|
|
10732
10732
|
var EventEmitter = __require("events");
|
|
10733
10733
|
var http = __require("http");
|
|
10734
10734
|
var { Duplex } = __require("stream");
|
|
10735
|
-
var { createHash:
|
|
10735
|
+
var { createHash: createHash6 } = __require("crypto");
|
|
10736
10736
|
var extension2 = require_extension();
|
|
10737
10737
|
var PerMessageDeflate2 = require_permessage_deflate();
|
|
10738
10738
|
var subprotocol2 = require_subprotocol();
|
|
@@ -11039,7 +11039,7 @@ var require_websocket_server = __commonJS({
|
|
|
11039
11039
|
);
|
|
11040
11040
|
}
|
|
11041
11041
|
if (this._state > RUNNING) return abortHandshake(socket, 503);
|
|
11042
|
-
const digest =
|
|
11042
|
+
const digest = createHash6("sha1").update(key + GUID).digest("base64");
|
|
11043
11043
|
const headers = [
|
|
11044
11044
|
"HTTP/1.1 101 Switching Protocols",
|
|
11045
11045
|
"Upgrade: websocket",
|
|
@@ -11141,13 +11141,22 @@ var contactIdentity = (id) => /^[a-f0-9]{64}$/i.test(id) ? id.toUpperCase() : id
|
|
|
11141
11141
|
function contactTarget(value) {
|
|
11142
11142
|
return object(value) && closed(value, ["kind", "contactId"]) && value.kind === "contact" && contactId(value.contactId);
|
|
11143
11143
|
}
|
|
11144
|
+
var STATUS_ID = /^[A-Za-z0-9_.:-]{1,512}$/;
|
|
11145
|
+
function statusTarget(value) {
|
|
11146
|
+
return object(value) && closed(value, ["kind", "authorCid", "statusId"]) && value.kind === "status" && typeof value.authorCid === "string" && /^[A-F0-9]{64}$/.test(value.authorCid) && typeof value.statusId === "string" && STATUS_ID.test(value.statusId);
|
|
11147
|
+
}
|
|
11148
|
+
var statusEvent = (value) => statusTarget(value.target) && typeof value.eventId === "string" && value.eventId.startsWith(`status:${value.target.statusId}:`) && /^[1-9][0-9]{0,15}$/.test(value.eventId.slice(`status:${value.target.statusId}:`.length));
|
|
11144
11149
|
function notificationInput(value) {
|
|
11145
|
-
if (!object(value) || !closed(value, ["eventId", "title", "body", "target", "anchor"]) || !text(value.eventId, 512) || !text(value.title, 160) || !text(value.body, 512)
|
|
11150
|
+
if (!object(value) || !closed(value, ["eventId", "title", "body", "target", "anchor", "delivery"]) || !text(value.eventId, 512) || !text(value.title, 160) || !text(value.body, 512)) return false;
|
|
11151
|
+
if (statusTarget(value.target))
|
|
11152
|
+
return statusEvent(value) && value.anchor === void 0 && (value.delivery === void 0 || value.delivery === "inbox" || value.delivery === "until-resolved");
|
|
11153
|
+
if (!contactTarget(value.target) || value.delivery !== void 0) return false;
|
|
11146
11154
|
return value.anchor === void 0 || object(value.anchor) && closed(value.anchor, ["kind", "wireId"]) && value.anchor.kind === "messenger-message" && text(value.anchor.wireId, 1024) && !/[\x00-\x1f\x7f]/.test(value.anchor.wireId);
|
|
11147
11155
|
}
|
|
11148
11156
|
var cleanup = (value) => object(value) && closed(value, ["target"]) && contactTarget(value.target);
|
|
11157
|
+
var resolution = (value) => object(value) && closed(value, ["eventId"]) && typeof value.eventId === "string" && /^status:[A-Za-z0-9_.:-]{1,512}:[1-9][0-9]{0,15}$/.test(value.eventId);
|
|
11149
11158
|
var has = (entry, key) => Object.hasOwn(entry, key);
|
|
11150
|
-
var supported = (entry) => object(entry) && typeof entry.id === "string" && (has(entry, "operation") ? entry.operation === "delete-target" && cleanup(entry.value) : has(entry, "payload") ? notificationInput(entry.payload) : entry.targetVersion === 1);
|
|
11159
|
+
var supported = (entry) => object(entry) && typeof entry.id === "string" && (has(entry, "operation") ? entry.operation === "delete-target" && cleanup(entry.value) || entry.operation === "resolve" && resolution(entry.value) : has(entry, "payload") ? notificationInput(entry.payload) : entry.targetVersion === 1);
|
|
11151
11160
|
var same = (id) => (entry) => supported(entry) && entry.id === id;
|
|
11152
11161
|
function producerConfig(env = process.env) {
|
|
11153
11162
|
const origin = env.OURS_NOTIFICATIONS_ORIGIN, token = env.OURS_NOTIFICATIONS_PRODUCER_TOKEN;
|
|
@@ -11219,6 +11228,26 @@ var NotificationOutbox = class {
|
|
|
11219
11228
|
this.persist([...this.entries, { id, value, targetVersion: 1 }], cursor);
|
|
11220
11229
|
return true;
|
|
11221
11230
|
}
|
|
11231
|
+
/**
|
|
11232
|
+
* A status event, fully projected when its change was committed (no later projection, so a crash replays the
|
|
11233
|
+
* identical payload and the service's event dedupe applies). Returns false only at capacity.
|
|
11234
|
+
*/
|
|
11235
|
+
enqueueEvent(payload) {
|
|
11236
|
+
if (!notificationInput(payload) || !statusTarget(payload.target)) throw new Error("Invalid status notification");
|
|
11237
|
+
if (this.entries.some(same(payload.eventId))) return true;
|
|
11238
|
+
if (this.entries.filter(supported).length >= 2e3) return false;
|
|
11239
|
+
this.persist([...this.entries, { id: payload.eventId, value: { status: true }, payload }]);
|
|
11240
|
+
return true;
|
|
11241
|
+
}
|
|
11242
|
+
/**
|
|
11243
|
+
* End a pending status notification (answered, closed or superseded). Queued after its send, so the send is
|
|
11244
|
+
* delivered first; never dropped by send capacity, and never cancels another queued job.
|
|
11245
|
+
*/
|
|
11246
|
+
enqueueResolve(eventId) {
|
|
11247
|
+
if (!resolution({ eventId })) throw new Error("Invalid status event");
|
|
11248
|
+
const id = `resolve:${eventId}`;
|
|
11249
|
+
if (!this.entries.some(same(id))) this.persist([...this.entries, { id, value: { eventId }, operation: "resolve" }]);
|
|
11250
|
+
}
|
|
11222
11251
|
retireTarget(target, matches) {
|
|
11223
11252
|
if (!contactTarget(target)) throw new Error("Invalid notification target");
|
|
11224
11253
|
const id = `delete-target:${contactIdentity(target.contactId)}`;
|
|
@@ -11266,16 +11295,17 @@ var NotificationOutbox = class {
|
|
|
11266
11295
|
continue;
|
|
11267
11296
|
}
|
|
11268
11297
|
}
|
|
11269
|
-
const value = entry.operation
|
|
11298
|
+
const value = entry.operation ? entry.value : entry.payload ?? await this.project(entry.value, entry.id);
|
|
11270
11299
|
if (!this.entries.some(same(entry.id))) continue;
|
|
11271
11300
|
if (value === void 0) {
|
|
11272
11301
|
this.persist(this.entries.filter((current) => !same(entry.id)(current)));
|
|
11273
11302
|
continue;
|
|
11274
11303
|
}
|
|
11275
|
-
if (entry.operation ? !cleanup(value) : !notificationInput(value)) continue;
|
|
11304
|
+
if (entry.operation === "delete-target" ? !cleanup(value) : entry.operation === "resolve" ? !resolution(value) : !notificationInput(value)) continue;
|
|
11276
11305
|
attempts++;
|
|
11277
11306
|
if (!entry.operation && !entry.payload) this.persist(this.entries.map((e2) => same(entry.id)(e2) ? { ...e2, payload: value } : e2));
|
|
11278
|
-
const
|
|
11307
|
+
const route = entry.operation === "delete-target" ? "/api/v1/delete-target" : entry.operation === "resolve" ? "/api/v1/resolve" : "/api/v1/send";
|
|
11308
|
+
const response = await fetch(this.config.origin + route, {
|
|
11279
11309
|
method: "POST",
|
|
11280
11310
|
redirect: "error",
|
|
11281
11311
|
signal: AbortSignal.timeout(1e4),
|
|
@@ -11283,7 +11313,7 @@ var NotificationOutbox = class {
|
|
|
11283
11313
|
body: JSON.stringify(value)
|
|
11284
11314
|
});
|
|
11285
11315
|
await response.body?.cancel();
|
|
11286
|
-
if (!response.ok) throw new Error("notification service rejected event");
|
|
11316
|
+
if (!response.ok && !(entry.operation === "resolve" && response.status === 404)) throw new Error("notification service rejected event");
|
|
11287
11317
|
this.persist(this.entries.filter((e2) => !same(entry.id)(e2)));
|
|
11288
11318
|
} catch {
|
|
11289
11319
|
this.failed = true;
|
|
@@ -11301,7 +11331,7 @@ var NotificationOutbox = class {
|
|
|
11301
11331
|
|
|
11302
11332
|
// src/notification-producer.ts
|
|
11303
11333
|
init_define_MESSENGER_BUILD_INFO();
|
|
11304
|
-
import { join } from "node:path";
|
|
11334
|
+
import { join as join2 } from "node:path";
|
|
11305
11335
|
|
|
11306
11336
|
// src/push-delivery.ts
|
|
11307
11337
|
init_define_MESSENGER_BUILD_INFO();
|
|
@@ -11476,8 +11506,8 @@ function isCoworkRoomContact(announced) {
|
|
|
11476
11506
|
return v04 || namedRoomLabel(announced) !== null || currentRoomMetadata(announced) !== null || legacyRoomId(announced) !== null;
|
|
11477
11507
|
}
|
|
11478
11508
|
function contactMessagePreview(announcedContact, text2) {
|
|
11479
|
-
const
|
|
11480
|
-
return
|
|
11509
|
+
const line2 = roomLineForContact(announcedContact, text2);
|
|
11510
|
+
return line2 ? roomMessagePreview(line2) : String(text2 ?? "");
|
|
11481
11511
|
}
|
|
11482
11512
|
function systemLine(kind, label, text2, extra = {}) {
|
|
11483
11513
|
return { variant: "system", kind, author: "", role: "", label, text: text2, ...extra };
|
|
@@ -11509,10 +11539,10 @@ function membershipFallback(membership) {
|
|
|
11509
11539
|
const who = isNonEmptyString(membership.alias) ? membership.alias : "A member";
|
|
11510
11540
|
return membership.action === "remove" ? `${who} left the room.` : "The room membership changed.";
|
|
11511
11541
|
}
|
|
11512
|
-
function roomMessagePreview(
|
|
11513
|
-
if (!
|
|
11514
|
-
const lead =
|
|
11515
|
-
const text2 = collapse(
|
|
11542
|
+
function roomMessagePreview(line2) {
|
|
11543
|
+
if (!line2) return "";
|
|
11544
|
+
const lead = line2.variant === "chat" ? line2.author : line2.label;
|
|
11545
|
+
const text2 = collapse(line2.text);
|
|
11516
11546
|
if (!lead) return text2;
|
|
11517
11547
|
return text2 ? `${lead} \xB7 ${text2}` : lead;
|
|
11518
11548
|
}
|
|
@@ -11725,6 +11755,802 @@ var PushDeliveryQueue = class {
|
|
|
11725
11755
|
}
|
|
11726
11756
|
};
|
|
11727
11757
|
|
|
11758
|
+
// src/status-service.ts
|
|
11759
|
+
init_define_MESSENGER_BUILD_INFO();
|
|
11760
|
+
|
|
11761
|
+
// src/statuses.ts
|
|
11762
|
+
init_define_MESSENGER_BUILD_INFO();
|
|
11763
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
11764
|
+
import { closeSync as closeSync2, fsyncSync as fsyncSync2, mkdirSync as mkdirSync2, openSync as openSync2, readdirSync, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
|
|
11765
|
+
import { join, resolve } from "node:path";
|
|
11766
|
+
var STATUS_TITLE_MAX = 120;
|
|
11767
|
+
var STATUS_BODY_MAX_BYTES = 64 * 1024;
|
|
11768
|
+
var STATUS_ATTACHMENTS_MAX = 10;
|
|
11769
|
+
var STATUS_OPTIONS_MIN = 2;
|
|
11770
|
+
var STATUS_OPTIONS_MAX = 12;
|
|
11771
|
+
var STATUS_CLOSE_REASON_MAX = 500;
|
|
11772
|
+
var STATUS_ANSWER_TEXT_MAX = 8e3;
|
|
11773
|
+
var PUSH_TITLE_MAX = 160;
|
|
11774
|
+
var PUSH_BODY_MAX = 200;
|
|
11775
|
+
var STATUS_KINDS = Object.freeze({
|
|
11776
|
+
update: { answerable: false, push: "<Agent>: <title>" },
|
|
11777
|
+
question: { answerable: true, push: "<Agent> asks: <title>" },
|
|
11778
|
+
alert: { answerable: false, push: "<Agent> needs attention: <title>" }
|
|
11779
|
+
});
|
|
11780
|
+
var StatusError = class extends Error {
|
|
11781
|
+
constructor(code, message) {
|
|
11782
|
+
super(message);
|
|
11783
|
+
this.code = code;
|
|
11784
|
+
}
|
|
11785
|
+
};
|
|
11786
|
+
var CID = /^[A-F0-9]{64}$/;
|
|
11787
|
+
var STATUS_ID2 = /^st_[a-z0-9]{8,64}$/;
|
|
11788
|
+
var REQUEST_KEY = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
11789
|
+
var OPTION_ID = /^[A-Za-z0-9_-]{1,64}$/;
|
|
11790
|
+
var SUBMISSION_ID = /^[A-Za-z0-9_-]{8,128}$/;
|
|
11791
|
+
var PUBLISH_FIELDS = ["kind", "title", "body", "attachments", "interaction", "supersedes", "request_key"];
|
|
11792
|
+
var codePoints = (value) => [...value].length;
|
|
11793
|
+
var invalid = (message) => {
|
|
11794
|
+
throw new StatusError("invalid_request", message);
|
|
11795
|
+
};
|
|
11796
|
+
var plain = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
11797
|
+
function closedObject(value, allowed, what) {
|
|
11798
|
+
if (!plain(value)) invalid(`${what} must be an object`);
|
|
11799
|
+
const extra = Object.keys(value).filter((key) => !allowed.includes(key));
|
|
11800
|
+
if (extra.length) invalid(`${what} has unsupported field ${extra[0]}`);
|
|
11801
|
+
return value;
|
|
11802
|
+
}
|
|
11803
|
+
function line(value, what, max) {
|
|
11804
|
+
if (typeof value !== "string" || !value.trim()) invalid(`${what} must be non-empty text`);
|
|
11805
|
+
const text2 = value;
|
|
11806
|
+
if (/[\x00-\x1f\x7f]/.test(text2)) invalid(`${what} must be one line without control characters`);
|
|
11807
|
+
if (codePoints(text2) > max) throw new StatusError("limit_exceeded", `${what} exceeds the ${max}-character limit`);
|
|
11808
|
+
return text2;
|
|
11809
|
+
}
|
|
11810
|
+
function clip(text2, max) {
|
|
11811
|
+
if (text2.length <= max) return text2;
|
|
11812
|
+
let end = max - 1;
|
|
11813
|
+
if (end > 0 && /[\uD800-\uDBFF]/.test(text2[end - 1])) end--;
|
|
11814
|
+
return text2.slice(0, end) + "\u2026";
|
|
11815
|
+
}
|
|
11816
|
+
function canonicalCid(value) {
|
|
11817
|
+
const cid = String(value ?? "").toUpperCase();
|
|
11818
|
+
if (!CID.test(cid)) throw new StatusError("forbidden", "a status author needs an authenticated identity CID");
|
|
11819
|
+
return cid;
|
|
11820
|
+
}
|
|
11821
|
+
function validInteraction(value) {
|
|
11822
|
+
const item = closedObject(value, ["mode", "options", "allowOther", "placeholder"], "interaction");
|
|
11823
|
+
if (item.mode !== "text" && item.mode !== "single" && item.mode !== "multi") invalid("interaction.mode must be text, single or multi");
|
|
11824
|
+
const result = { mode: item.mode };
|
|
11825
|
+
if (item.placeholder !== void 0) result.placeholder = line(item.placeholder, "interaction.placeholder", 200);
|
|
11826
|
+
if (item.mode === "text") {
|
|
11827
|
+
if (item.options !== void 0 || item.allowOther !== void 0) invalid("a text question has no options");
|
|
11828
|
+
return result;
|
|
11829
|
+
}
|
|
11830
|
+
if (!Array.isArray(item.options) || item.options.length < STATUS_OPTIONS_MIN || item.options.length > STATUS_OPTIONS_MAX)
|
|
11831
|
+
invalid(`a choice question needs ${STATUS_OPTIONS_MIN}-${STATUS_OPTIONS_MAX} options`);
|
|
11832
|
+
const ids = /* @__PURE__ */ new Set();
|
|
11833
|
+
result.options = item.options.map((raw, index) => {
|
|
11834
|
+
const option2 = closedObject(raw, ["id", "label", "description", "recommended"], `interaction.options[${index}]`);
|
|
11835
|
+
if (typeof option2.id !== "string" || !OPTION_ID.test(option2.id)) invalid('option id must be 1-64 letters, digits, "_" or "-"');
|
|
11836
|
+
if (ids.has(option2.id)) invalid(`option id ${option2.id} is not unique`);
|
|
11837
|
+
ids.add(option2.id);
|
|
11838
|
+
if (option2.recommended !== void 0 && typeof option2.recommended !== "boolean") invalid("option recommended must be a boolean");
|
|
11839
|
+
return {
|
|
11840
|
+
id: option2.id,
|
|
11841
|
+
label: line(option2.label, "option label", 200),
|
|
11842
|
+
...option2.description === void 0 ? {} : { description: line(option2.description, "option description", 500) },
|
|
11843
|
+
...option2.recommended === void 0 ? {} : { recommended: option2.recommended }
|
|
11844
|
+
};
|
|
11845
|
+
});
|
|
11846
|
+
if (item.allowOther !== void 0) {
|
|
11847
|
+
if (typeof item.allowOther !== "boolean") invalid("interaction.allowOther must be a boolean");
|
|
11848
|
+
result.allowOther = item.allowOther;
|
|
11849
|
+
}
|
|
11850
|
+
return result;
|
|
11851
|
+
}
|
|
11852
|
+
function validAttachments(value) {
|
|
11853
|
+
if (value === void 0) return [];
|
|
11854
|
+
if (!Array.isArray(value)) return invalid("attachments must be a list");
|
|
11855
|
+
if (value.length > STATUS_ATTACHMENTS_MAX) throw new StatusError("limit_exceeded", `a status can have at most ${STATUS_ATTACHMENTS_MAX} attachments`);
|
|
11856
|
+
return value.map((raw, index) => {
|
|
11857
|
+
const item = closedObject(raw, ["id", "name", "media_type", "size", "sha256"], `attachments[${index}]`);
|
|
11858
|
+
if (typeof item.id !== "string" || !/^[A-Za-z0-9_.:-]{1,256}$/.test(item.id)) invalid("attachment id must be a delivered file ID");
|
|
11859
|
+
const name = line(item.name, "attachment name", 240);
|
|
11860
|
+
if (/[\\/]/.test(name) || name === "." || name === "..") invalid("attachment name must not contain slashes");
|
|
11861
|
+
const mediaType = line(item.media_type, "attachment media_type", 255);
|
|
11862
|
+
if (!Number.isSafeInteger(item.size) || item.size < 0) invalid("attachment size must be a non-negative integer");
|
|
11863
|
+
if (typeof item.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(item.sha256)) invalid("attachment sha256 must be 64 lowercase hex characters");
|
|
11864
|
+
return { id: item.id, name, media_type: mediaType, size: item.size, sha256: item.sha256 };
|
|
11865
|
+
});
|
|
11866
|
+
}
|
|
11867
|
+
function validatePublish(raw) {
|
|
11868
|
+
if (!plain(raw)) return invalid("publish arguments must be an object");
|
|
11869
|
+
for (const key of ["author", "author_cid", "authorCid", "task_id", "taskId", "mission", "source"])
|
|
11870
|
+
if (key in raw) invalid(`${key} cannot be set: the author is the authenticated sender and external statuses have no mission`);
|
|
11871
|
+
const input = closedObject(raw, PUBLISH_FIELDS, "publish arguments");
|
|
11872
|
+
if (typeof input.kind !== "string" || !Object.hasOwn(STATUS_KINDS, input.kind))
|
|
11873
|
+
invalid(`kind must be one of ${Object.keys(STATUS_KINDS).join(", ")}`);
|
|
11874
|
+
const kind = input.kind;
|
|
11875
|
+
const title = line(input.title, "title", STATUS_TITLE_MAX);
|
|
11876
|
+
if (typeof input.body !== "string") invalid("body must be Markdown text");
|
|
11877
|
+
if (Buffer.byteLength(input.body, "utf8") > STATUS_BODY_MAX_BYTES)
|
|
11878
|
+
throw new StatusError("limit_exceeded", "body exceeds the 64 KiB Markdown limit");
|
|
11879
|
+
const attachments = validAttachments(input.attachments);
|
|
11880
|
+
const answerable = STATUS_KINDS[kind].answerable;
|
|
11881
|
+
if (answerable && input.interaction === void 0) invalid(`a ${kind} needs an interaction`);
|
|
11882
|
+
if (!answerable && input.interaction !== void 0) invalid(`a ${kind} cannot have an interaction`);
|
|
11883
|
+
if (input.supersedes !== void 0 && (kind !== "question" || typeof input.supersedes !== "string" || !STATUS_ID2.test(input.supersedes)))
|
|
11884
|
+
invalid("only a question can supersede, and supersedes must be a status ID");
|
|
11885
|
+
if (input.request_key !== void 0 && (typeof input.request_key !== "string" || !REQUEST_KEY.test(input.request_key)))
|
|
11886
|
+
invalid('request_key must be 1-128 letters, digits, ".", "_", ":" or "-"');
|
|
11887
|
+
return {
|
|
11888
|
+
kind,
|
|
11889
|
+
title,
|
|
11890
|
+
body: input.body,
|
|
11891
|
+
attachments,
|
|
11892
|
+
...input.interaction === void 0 ? {} : { interaction: validInteraction(input.interaction) },
|
|
11893
|
+
...input.supersedes === void 0 ? {} : { supersedes: input.supersedes },
|
|
11894
|
+
...input.request_key === void 0 ? {} : { request_key: input.request_key }
|
|
11895
|
+
};
|
|
11896
|
+
}
|
|
11897
|
+
function statusPush(status) {
|
|
11898
|
+
const agent = status.author.display_name?.trim() || `${status.author.identity_cid.slice(0, 8)}\u2026`;
|
|
11899
|
+
const template = STATUS_KINDS[status.kind]?.push ?? "<Agent>: <title>";
|
|
11900
|
+
const title = clip(template.replace("<Agent>", agent).replace("<title>", status.title), PUSH_TITLE_MAX);
|
|
11901
|
+
const first = status.body.split("\n").map((text2) => text2.replace(/^\s*(?:#{1,6}\s|>\s?|[-*+]\s|\d+\.\s)*/, "").trim()).find(Boolean);
|
|
11902
|
+
return { title, body: clip(first ?? "Open the feed", PUSH_BODY_MAX) };
|
|
11903
|
+
}
|
|
11904
|
+
var statusEventId = (status) => `status:${status.status_id}:${status.revision}`;
|
|
11905
|
+
var sendEvent = (status) => ({ op: "send", eventId: statusEventId(status), delivery: status.kind === "question" ? "until-resolved" : "inbox", ...statusPush(status) });
|
|
11906
|
+
var resolveEvents = (status) => status.kind === "question" && status.state === "active" && !status.answer ? [{ op: "resolve", eventId: statusEventId(status) }] : [];
|
|
11907
|
+
var withEvents = (status, events) => events.length ? { ...status, notification_events: [...status.notification_events ?? [], ...events] } : status;
|
|
11908
|
+
var content = (r) => JSON.stringify([r.kind, r.title, r.body, r.attachments, r.interaction ?? null, r.supersedes ?? null]);
|
|
11909
|
+
var AlreadyAnsweredError = class extends StatusError {
|
|
11910
|
+
constructor(status) {
|
|
11911
|
+
super("conflict", "already_answered: this question already has an accepted answer");
|
|
11912
|
+
this.status = status;
|
|
11913
|
+
}
|
|
11914
|
+
};
|
|
11915
|
+
function writeDurably(path2, text2) {
|
|
11916
|
+
const temp = `${path2}.${process.pid}.tmp`;
|
|
11917
|
+
const fd = openSync2(temp, "w", 384);
|
|
11918
|
+
try {
|
|
11919
|
+
writeFileSync2(fd, text2);
|
|
11920
|
+
fsyncSync2(fd);
|
|
11921
|
+
} finally {
|
|
11922
|
+
closeSync2(fd);
|
|
11923
|
+
}
|
|
11924
|
+
renameSync2(temp, path2);
|
|
11925
|
+
const dir = openSync2(join(path2, ".."), "r");
|
|
11926
|
+
try {
|
|
11927
|
+
fsyncSync2(dir);
|
|
11928
|
+
} finally {
|
|
11929
|
+
closeSync2(dir);
|
|
11930
|
+
}
|
|
11931
|
+
}
|
|
11932
|
+
var statusesDirFor = (stateDir, ownerCid) => resolve(stateDir, `statuses-${createHash("sha256").update(ownerCid.toUpperCase()).digest("hex").slice(0, 24)}`);
|
|
11933
|
+
var storeObservers = /* @__PURE__ */ new Map();
|
|
11934
|
+
function subscribeStatuses(stateDir, ownerCid, onCommitted, signal) {
|
|
11935
|
+
if (signal.aborted) return () => {
|
|
11936
|
+
};
|
|
11937
|
+
const key = statusesDirFor(stateDir, ownerCid), observers = storeObservers.get(key) ?? /* @__PURE__ */ new Set();
|
|
11938
|
+
storeObservers.set(key, observers);
|
|
11939
|
+
observers.add(onCommitted);
|
|
11940
|
+
const dispose = () => {
|
|
11941
|
+
observers.delete(onCommitted);
|
|
11942
|
+
if (!observers.size) storeObservers.delete(key);
|
|
11943
|
+
signal.removeEventListener("abort", dispose);
|
|
11944
|
+
};
|
|
11945
|
+
signal.addEventListener("abort", dispose, { once: true });
|
|
11946
|
+
return dispose;
|
|
11947
|
+
}
|
|
11948
|
+
var MessengerStatusStore = class {
|
|
11949
|
+
dir;
|
|
11950
|
+
ingestDir;
|
|
11951
|
+
listeners = /* @__PURE__ */ new Set();
|
|
11952
|
+
constructor(stateDir, ownerCid) {
|
|
11953
|
+
this.dir = statusesDirFor(stateDir, ownerCid);
|
|
11954
|
+
this.ingestDir = join(this.dir, ".ingest");
|
|
11955
|
+
mkdirSync2(this.ingestDir, { recursive: true, mode: 448 });
|
|
11956
|
+
}
|
|
11957
|
+
/** Called after every committed change (live resource views, notification flush). */
|
|
11958
|
+
onChange(listener) {
|
|
11959
|
+
this.listeners.add(listener);
|
|
11960
|
+
return () => this.listeners.delete(listener);
|
|
11961
|
+
}
|
|
11962
|
+
changed() {
|
|
11963
|
+
for (const listener of [...this.listeners, ...storeObservers.get(this.dir) ?? []]) {
|
|
11964
|
+
try {
|
|
11965
|
+
listener();
|
|
11966
|
+
} catch {
|
|
11967
|
+
}
|
|
11968
|
+
}
|
|
11969
|
+
}
|
|
11970
|
+
path(id) {
|
|
11971
|
+
return join(this.dir, `${id}.json`);
|
|
11972
|
+
}
|
|
11973
|
+
write(record) {
|
|
11974
|
+
writeDurably(this.path(record.status_id), JSON.stringify(record, null, 2) + "\n");
|
|
11975
|
+
}
|
|
11976
|
+
get(id) {
|
|
11977
|
+
if (!STATUS_ID2.test(id)) return void 0;
|
|
11978
|
+
try {
|
|
11979
|
+
const record = JSON.parse(readFileSync2(this.path(id), "utf8"));
|
|
11980
|
+
if (record?.version !== 1 || record.status_id !== id || record.source !== "messenger") throw new Error(`unsupported status record ${id}`);
|
|
11981
|
+
return record;
|
|
11982
|
+
} catch (error) {
|
|
11983
|
+
if (error.code === "ENOENT") return void 0;
|
|
11984
|
+
throw error;
|
|
11985
|
+
}
|
|
11986
|
+
}
|
|
11987
|
+
require(id) {
|
|
11988
|
+
const record = this.get(id);
|
|
11989
|
+
if (!record) throw new StatusError("not_found", "status not found");
|
|
11990
|
+
return record;
|
|
11991
|
+
}
|
|
11992
|
+
list() {
|
|
11993
|
+
return readdirSync(this.dir).filter((name) => name.endsWith(".json") && STATUS_ID2.test(name.slice(0, -5))).map((name) => this.get(name.slice(0, -5))).filter((record) => !!record);
|
|
11994
|
+
}
|
|
11995
|
+
ingestPath(wireId) {
|
|
11996
|
+
return join(this.ingestDir, `${createHash("sha256").update(wireId).digest("hex")}.json`);
|
|
11997
|
+
}
|
|
11998
|
+
/** The recorded outcome of an already ingested command message, so a re-delivered message is never applied twice. */
|
|
11999
|
+
ingested(wireId) {
|
|
12000
|
+
try {
|
|
12001
|
+
return JSON.parse(readFileSync2(this.ingestPath(wireId), "utf8"));
|
|
12002
|
+
} catch (error) {
|
|
12003
|
+
if (error.code === "ENOENT") return void 0;
|
|
12004
|
+
throw error;
|
|
12005
|
+
}
|
|
12006
|
+
}
|
|
12007
|
+
recordIngest(record) {
|
|
12008
|
+
writeDurably(this.ingestPath(record.wire_id), JSON.stringify(record) + "\n");
|
|
12009
|
+
}
|
|
12010
|
+
/**
|
|
12011
|
+
* Ingest one `ours.status.publish` command, idempotently by its wire ID: the status and the ingest record are both
|
|
12012
|
+
* durable before the result is returned (and so before any command_result is sent).
|
|
12013
|
+
*/
|
|
12014
|
+
ingestPublish(author, args, wireId, now = /* @__PURE__ */ new Date(), refusal) {
|
|
12015
|
+
const done = this.ingested(wireId);
|
|
12016
|
+
if (done) return done.outcome;
|
|
12017
|
+
let outcome;
|
|
12018
|
+
try {
|
|
12019
|
+
if (refusal) throw refusal;
|
|
12020
|
+
outcome = { ok: true, status_id: this.publish(author, args, wireId, now).status.status_id };
|
|
12021
|
+
} catch (error) {
|
|
12022
|
+
if (!(error instanceof StatusError)) throw error;
|
|
12023
|
+
outcome = { ok: false, code: error.code, message: error.message };
|
|
12024
|
+
}
|
|
12025
|
+
this.recordIngest({ version: 1, wire_id: wireId, author_cid: canonicalCid(author.cid), command: "ours.status.publish", outcome });
|
|
12026
|
+
return outcome;
|
|
12027
|
+
}
|
|
12028
|
+
/** Ingest one `ours.status.close` command, idempotently by its wire ID. Only the author can close its status. */
|
|
12029
|
+
ingestClose(author, args, wireId, now = /* @__PURE__ */ new Date()) {
|
|
12030
|
+
const done = this.ingested(wireId);
|
|
12031
|
+
if (done) return done.outcome;
|
|
12032
|
+
let outcome;
|
|
12033
|
+
try {
|
|
12034
|
+
const input = closedObject(args, ["status_id", "reason"], "close arguments");
|
|
12035
|
+
if (typeof input.status_id !== "string") invalid("status_id is required");
|
|
12036
|
+
outcome = { ok: true, status_id: this.close(author.cid, input.status_id, input.reason, now).status_id };
|
|
12037
|
+
} catch (error) {
|
|
12038
|
+
if (!(error instanceof StatusError)) throw error;
|
|
12039
|
+
outcome = { ok: false, code: error.code, message: error.message };
|
|
12040
|
+
}
|
|
12041
|
+
this.recordIngest({ version: 1, wire_id: wireId, author_cid: canonicalCid(author.cid), command: "ours.status.close", outcome });
|
|
12042
|
+
return outcome;
|
|
12043
|
+
}
|
|
12044
|
+
publish(author, raw, requestWireId, now = /* @__PURE__ */ new Date()) {
|
|
12045
|
+
const input = validatePublish(raw);
|
|
12046
|
+
const cid = canonicalCid(author.cid);
|
|
12047
|
+
const at2 = now.toISOString();
|
|
12048
|
+
const id = input.request_key ? `st_m${createHash("sha256").update(`${cid}\0${input.request_key}`).digest("hex").slice(0, 32)}` : `st_w${createHash("sha256").update(`${cid}\0${requestWireId}`).digest("hex").slice(0, 32)}`;
|
|
12049
|
+
const name = author.name?.trim() ? author.name.trim().slice(0, 120) : void 0;
|
|
12050
|
+
const record = {
|
|
12051
|
+
version: 1,
|
|
12052
|
+
status_id: id,
|
|
12053
|
+
source: "messenger",
|
|
12054
|
+
kind: input.kind,
|
|
12055
|
+
author: { identity_cid: cid, ...name ? { display_name: name } : {} },
|
|
12056
|
+
revision: 1,
|
|
12057
|
+
title: input.title,
|
|
12058
|
+
body: input.body,
|
|
12059
|
+
attachments: input.attachments,
|
|
12060
|
+
...input.interaction ? { interaction: input.interaction } : {},
|
|
12061
|
+
state: "active",
|
|
12062
|
+
...input.supersedes ? { supersedes: input.supersedes } : {},
|
|
12063
|
+
...input.request_key ? { request_key: input.request_key } : {},
|
|
12064
|
+
request_wire_id: requestWireId,
|
|
12065
|
+
created_at: at2,
|
|
12066
|
+
updated_at: at2
|
|
12067
|
+
};
|
|
12068
|
+
const existing = this.get(id);
|
|
12069
|
+
if (existing) {
|
|
12070
|
+
if (existing.author.identity_cid !== cid || content(existing) !== content(record))
|
|
12071
|
+
throw new StatusError("idempotency_conflict", "request_key was already used for a different status");
|
|
12072
|
+
const superseded2 = this.closeSuperseded(existing, at2);
|
|
12073
|
+
if (superseded2) this.changed();
|
|
12074
|
+
return { status: existing, replayed: true, ...superseded2 ? { superseded: superseded2 } : {} };
|
|
12075
|
+
}
|
|
12076
|
+
if (input.supersedes) {
|
|
12077
|
+
const older = this.get(input.supersedes);
|
|
12078
|
+
if (!older || older.author.identity_cid !== cid) throw new StatusError("not_found", "the superseded status does not exist for this author");
|
|
12079
|
+
if (older.kind !== "question") invalid("only a question can be superseded");
|
|
12080
|
+
}
|
|
12081
|
+
const published = withEvents(record, [sendEvent(record)]);
|
|
12082
|
+
this.write(published);
|
|
12083
|
+
const superseded = this.closeSuperseded(published, at2);
|
|
12084
|
+
this.changed();
|
|
12085
|
+
return { status: published, replayed: false, ...superseded ? { superseded } : {} };
|
|
12086
|
+
}
|
|
12087
|
+
/** Close the author's older question this one supersedes, if it is still open. Idempotent. */
|
|
12088
|
+
closeSuperseded(status, at2) {
|
|
12089
|
+
if (!status.supersedes) return void 0;
|
|
12090
|
+
const older = this.get(status.supersedes);
|
|
12091
|
+
if (!older || older.author.identity_cid !== status.author.identity_cid || older.kind !== "question" || older.state !== "active") return void 0;
|
|
12092
|
+
const superseded = withEvents({ ...older, state: "closed", closed: { reason: "superseded", at: at2, superseded_by: status.status_id }, updated_at: at2 }, resolveEvents(older));
|
|
12093
|
+
this.write(superseded);
|
|
12094
|
+
return superseded;
|
|
12095
|
+
}
|
|
12096
|
+
/** The author closes its own status; an unanswered open question's notification is resolved. Idempotent. */
|
|
12097
|
+
close(authorCid, statusId, reasonRaw, now = /* @__PURE__ */ new Date()) {
|
|
12098
|
+
const cid = canonicalCid(authorCid);
|
|
12099
|
+
const current = this.get(statusId);
|
|
12100
|
+
if (!current || current.author.identity_cid !== cid) throw new StatusError("not_found", "status not found for this author");
|
|
12101
|
+
const reason = reasonRaw === void 0 ? "closed by its agent" : line(reasonRaw, "reason", STATUS_CLOSE_REASON_MAX);
|
|
12102
|
+
if (current.state === "closed") return current;
|
|
12103
|
+
const at2 = now.toISOString();
|
|
12104
|
+
const closed2 = withEvents({ ...current, state: "closed", closed: { reason, at: at2 }, updated_at: at2 }, resolveEvents(current));
|
|
12105
|
+
this.write(closed2);
|
|
12106
|
+
this.changed();
|
|
12107
|
+
return closed2;
|
|
12108
|
+
}
|
|
12109
|
+
/**
|
|
12110
|
+
* The Owner's one accepted answer to an open question (first answer wins), committed with its pending delivery and
|
|
12111
|
+
* the resolve of its notification. A repeat of the same submission returns the stored answer unchanged.
|
|
12112
|
+
*/
|
|
12113
|
+
answer(statusId, input, now = /* @__PURE__ */ new Date()) {
|
|
12114
|
+
if (!SUBMISSION_ID.test(String(input.submissionId ?? ""))) invalid('submissionId must be 8-128 letters, digits, "_" or "-"');
|
|
12115
|
+
const current = this.require(statusId);
|
|
12116
|
+
if (current.answer) {
|
|
12117
|
+
if (current.answer.submission_id === input.submissionId) return { status: current, replayed: true };
|
|
12118
|
+
throw new AlreadyAnsweredError(current);
|
|
12119
|
+
}
|
|
12120
|
+
if (current.kind !== "question" || !current.interaction) invalid("only a question can be answered");
|
|
12121
|
+
if (current.state !== "active") throw new StatusError("conflict", "this question is closed");
|
|
12122
|
+
if (input.expectedRevision !== current.revision) throw new StatusError("conflict", "stale_state: the question changed; reload it");
|
|
12123
|
+
const interaction = current.interaction;
|
|
12124
|
+
const text2 = input.text === void 0 ? void 0 : String(input.text);
|
|
12125
|
+
if (text2 !== void 0 && (!text2.trim() || codePoints(text2) > STATUS_ANSWER_TEXT_MAX)) invalid(`answer text must be 1-${STATUS_ANSWER_TEXT_MAX} characters`);
|
|
12126
|
+
let selection;
|
|
12127
|
+
if (interaction.mode === "text") {
|
|
12128
|
+
if (input.selection !== void 0) invalid("a text question takes text only");
|
|
12129
|
+
if (text2 === void 0) invalid("answer text is required");
|
|
12130
|
+
} else {
|
|
12131
|
+
selection = input.selection ?? [];
|
|
12132
|
+
if (!Array.isArray(selection) || new Set(selection).size !== selection.length) invalid("selection must be a list of distinct option IDs");
|
|
12133
|
+
const ids = new Set(interaction.options.map((option2) => option2.id));
|
|
12134
|
+
if (selection.some((id) => !ids.has(id))) invalid("selection contains an unknown option");
|
|
12135
|
+
if (interaction.mode === "single" && selection.length + (text2 === void 0 ? 0 : 1) !== 1) invalid("a single-choice question takes exactly one answer");
|
|
12136
|
+
if (interaction.mode === "multi" && selection.length === 0 && text2 === void 0) invalid("choose at least one option");
|
|
12137
|
+
if (text2 !== void 0 && !interaction.allowOther) invalid("this question does not accept other text");
|
|
12138
|
+
}
|
|
12139
|
+
const at2 = now.toISOString();
|
|
12140
|
+
const answered = withEvents({ ...current, updated_at: at2, answer: {
|
|
12141
|
+
submission_id: input.submissionId,
|
|
12142
|
+
...selection?.length ? { selection } : {},
|
|
12143
|
+
...text2 === void 0 ? {} : { text: text2 },
|
|
12144
|
+
answered_at: at2,
|
|
12145
|
+
surface: input.surface === "session" ? "session" : "feed",
|
|
12146
|
+
delivery: { state: "pending", command_id: `ans_${randomBytes(12).toString("hex")}`, at: at2 }
|
|
12147
|
+
} }, resolveEvents(current));
|
|
12148
|
+
this.write(answered);
|
|
12149
|
+
this.changed();
|
|
12150
|
+
return { status: answered, replayed: false };
|
|
12151
|
+
}
|
|
12152
|
+
/** Record the receipt-checked outcome of one delivery attempt, only for the attempt that is still pending. */
|
|
12153
|
+
settleDelivery(statusId, commandId, outcome) {
|
|
12154
|
+
const current = this.require(statusId);
|
|
12155
|
+
const delivery = current.answer?.delivery;
|
|
12156
|
+
if (!delivery || delivery.state !== "pending" || delivery.command_id !== commandId) return current;
|
|
12157
|
+
const settled = { ...current, updated_at: outcome.at, answer: { ...current.answer, delivery: outcome } };
|
|
12158
|
+
this.write(settled);
|
|
12159
|
+
this.changed();
|
|
12160
|
+
return settled;
|
|
12161
|
+
}
|
|
12162
|
+
/** The Owner's manual Try again after `not_delivered`: a new pending attempt. Never automatic. */
|
|
12163
|
+
retryDelivery(statusId, now = /* @__PURE__ */ new Date()) {
|
|
12164
|
+
const current = this.require(statusId);
|
|
12165
|
+
if (current.answer?.delivery.state !== "not_delivered") throw new StatusError("conflict", "only an undelivered answer can be sent again");
|
|
12166
|
+
const at2 = now.toISOString();
|
|
12167
|
+
const retried = {
|
|
12168
|
+
...current,
|
|
12169
|
+
updated_at: at2,
|
|
12170
|
+
answer: { ...current.answer, delivery: { state: "pending", command_id: `ans_${randomBytes(12).toString("hex")}`, at: at2 } }
|
|
12171
|
+
};
|
|
12172
|
+
this.write(retried);
|
|
12173
|
+
this.changed();
|
|
12174
|
+
return retried;
|
|
12175
|
+
}
|
|
12176
|
+
/** The Owner has seen this revision (informational statuses and ended questions; an open question stays unseen). */
|
|
12177
|
+
markSeen(statusId, revision) {
|
|
12178
|
+
const current = this.require(statusId);
|
|
12179
|
+
const awaiting = current.kind === "question" && current.state === "active" && !current.answer;
|
|
12180
|
+
if (awaiting || revision !== current.revision || (current.seen_revision ?? 0) >= revision) return current;
|
|
12181
|
+
const seen = { ...current, seen_revision: revision };
|
|
12182
|
+
this.write(seen);
|
|
12183
|
+
this.changed();
|
|
12184
|
+
return seen;
|
|
12185
|
+
}
|
|
12186
|
+
/** Remove handed-off notification events (after the outbox durably accepted them). */
|
|
12187
|
+
clearEvents(statusId, eventKeys) {
|
|
12188
|
+
const current = this.get(statusId);
|
|
12189
|
+
if (!current?.notification_events?.length) return;
|
|
12190
|
+
const remaining = current.notification_events.filter((event) => !eventKeys.has(`${event.op}:${event.eventId}`));
|
|
12191
|
+
if (remaining.length === current.notification_events.length) return;
|
|
12192
|
+
const next = { ...current };
|
|
12193
|
+
if (remaining.length) next.notification_events = remaining;
|
|
12194
|
+
else delete next.notification_events;
|
|
12195
|
+
this.write(next);
|
|
12196
|
+
}
|
|
12197
|
+
};
|
|
12198
|
+
var statusAwaitsOwner = (status) => status.kind === "question" && status.state === "active" && !status.answer;
|
|
12199
|
+
var statusSeen = (status) => !statusAwaitsOwner(status) && (status.seen_revision ?? 0) >= status.revision;
|
|
12200
|
+
var FEED_PAGE_MAX = 200;
|
|
12201
|
+
function feedScope(query) {
|
|
12202
|
+
const scope = query.scope ?? (query.agent === void 0 ? "global" : "agent");
|
|
12203
|
+
if (scope === "global" && query.agent === void 0) return { kind: "global" };
|
|
12204
|
+
if (scope === "agent" && typeof query.agent === "string") return { kind: "agent", identityCid: canonicalCid(query.agent) };
|
|
12205
|
+
throw new StatusError("invalid_request", "scope must be global, or agent with an agent CID");
|
|
12206
|
+
}
|
|
12207
|
+
function feedItem(status) {
|
|
12208
|
+
const delivery = status.answer?.delivery;
|
|
12209
|
+
return {
|
|
12210
|
+
source: "messenger",
|
|
12211
|
+
status_id: status.status_id,
|
|
12212
|
+
kind: status.kind,
|
|
12213
|
+
title: status.title,
|
|
12214
|
+
author: status.author,
|
|
12215
|
+
revision: status.revision,
|
|
12216
|
+
state: status.state,
|
|
12217
|
+
answered: !!status.answer,
|
|
12218
|
+
...delivery ? { answer_delivery: { state: delivery.state, at: delivery.at, ...delivery.state === "not_delivered" ? { reason: delivery.reason } : {} } } : {},
|
|
12219
|
+
awaits_owner: statusAwaitsOwner(status),
|
|
12220
|
+
seen: statusSeen(status),
|
|
12221
|
+
request_wire_id: status.request_wire_id,
|
|
12222
|
+
created_at: status.created_at,
|
|
12223
|
+
updated_at: status.updated_at
|
|
12224
|
+
};
|
|
12225
|
+
}
|
|
12226
|
+
function publicStatus(status) {
|
|
12227
|
+
const { version: _version, request_key: _key, seen_revision: _seen, notification_events: _events, ...visible } = status;
|
|
12228
|
+
return { ...visible, seen: statusSeen(status), awaits_owner: statusAwaitsOwner(status) };
|
|
12229
|
+
}
|
|
12230
|
+
function listFeed(store, scope, options = {}) {
|
|
12231
|
+
const limit = options.limit ?? 100;
|
|
12232
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > FEED_PAGE_MAX) throw new StatusError("invalid_request", `limit must be 1-${FEED_PAGE_MAX}`);
|
|
12233
|
+
const all = store.list().filter((status) => scope.kind === "global" || status.author.identity_cid === scope.identityCid).map(feedItem).sort((a, b2) => a.created_at.localeCompare(b2.created_at) || a.status_id.localeCompare(b2.status_id));
|
|
12234
|
+
let start2 = 0;
|
|
12235
|
+
if (options.after !== void 0) {
|
|
12236
|
+
start2 = all.findIndex((item) => item.status_id === options.after) + 1;
|
|
12237
|
+
if (!start2) throw new StatusError("invalid_request", "after must be a status ID in this scope");
|
|
12238
|
+
}
|
|
12239
|
+
const page = all.slice(start2, start2 + limit);
|
|
12240
|
+
const unseen = all.filter((item) => !item.seen);
|
|
12241
|
+
return {
|
|
12242
|
+
items: page,
|
|
12243
|
+
next_after: start2 + page.length < all.length ? page.at(-1).status_id : null,
|
|
12244
|
+
total: all.length,
|
|
12245
|
+
unseen: unseen.length,
|
|
12246
|
+
open_questions: all.filter((item) => item.awaits_owner).map((item) => item.status_id),
|
|
12247
|
+
opens_at: unseen[0]?.status_id ?? all.at(-1)?.status_id ?? null,
|
|
12248
|
+
caught_up: unseen.length === 0,
|
|
12249
|
+
scope_version: createHash("sha256").update(JSON.stringify(all)).digest("hex").slice(0, 32)
|
|
12250
|
+
};
|
|
12251
|
+
}
|
|
12252
|
+
|
|
12253
|
+
// src/status-service.ts
|
|
12254
|
+
var ATTACHMENT_KEYS = ["id", "name", "media_type", "size", "sha256"];
|
|
12255
|
+
var PUBLISH_COMMAND = "ours.status.publish";
|
|
12256
|
+
var CLOSE_COMMAND = "ours.status.close";
|
|
12257
|
+
var ANSWER_COMMAND = "ours.status.answer";
|
|
12258
|
+
var OWN_COMMANDS = /* @__PURE__ */ new Set([PUBLISH_COMMAND, CLOSE_COMMAND]);
|
|
12259
|
+
var option = { type: "object", additionalProperties: false, required: ["id", "label"], properties: {
|
|
12260
|
+
id: { type: "string" },
|
|
12261
|
+
label: { type: "string" },
|
|
12262
|
+
description: { type: "string" },
|
|
12263
|
+
recommended: { type: "boolean" }
|
|
12264
|
+
} };
|
|
12265
|
+
var STATUS_COMMAND_DEFINITIONS = Object.freeze([
|
|
12266
|
+
{
|
|
12267
|
+
name: PUBLISH_COMMAND,
|
|
12268
|
+
description: "Publish a status (update, question or alert) to the Owner's feed. The author is you, the sender. The result is {status_id} or {error:{code,message}}. A question needs an interaction; request_key makes a retried publish return the first result.",
|
|
12269
|
+
input_schema: { type: "object", additionalProperties: false, required: ["kind", "title", "body"], properties: {
|
|
12270
|
+
kind: { type: "string", enum: ["update", "question", "alert"] },
|
|
12271
|
+
title: { type: "string" },
|
|
12272
|
+
body: { type: "string" },
|
|
12273
|
+
attachments: { type: "array", maxItems: STATUS_ATTACHMENTS_MAX, items: { type: "object", additionalProperties: false, required: ["id"], properties: {
|
|
12274
|
+
id: { type: "string", description: "The wire_id of a file you already sent to this Owner" },
|
|
12275
|
+
name: { type: "string" },
|
|
12276
|
+
media_type: { type: "string" },
|
|
12277
|
+
size: { type: "integer" },
|
|
12278
|
+
sha256: { type: "string" }
|
|
12279
|
+
} } },
|
|
12280
|
+
interaction: { type: "object", additionalProperties: false, required: ["mode"], properties: {
|
|
12281
|
+
mode: { type: "string", enum: ["text", "single", "multi"] },
|
|
12282
|
+
options: { type: "array", items: option },
|
|
12283
|
+
allowOther: { type: "boolean" },
|
|
12284
|
+
placeholder: { type: "string" }
|
|
12285
|
+
} },
|
|
12286
|
+
supersedes: { type: "string" },
|
|
12287
|
+
request_key: { type: "string" }
|
|
12288
|
+
} }
|
|
12289
|
+
},
|
|
12290
|
+
{
|
|
12291
|
+
name: CLOSE_COMMAND,
|
|
12292
|
+
description: "Close one of your own statuses (a question you no longer need answered). Result {status_id} or {error}.",
|
|
12293
|
+
input_schema: { type: "object", additionalProperties: false, required: ["status_id"], properties: {
|
|
12294
|
+
status_id: { type: "string" },
|
|
12295
|
+
reason: { type: "string" }
|
|
12296
|
+
} }
|
|
12297
|
+
}
|
|
12298
|
+
]);
|
|
12299
|
+
var outcomeJson = (outcome) => outcome.ok ? { status_id: outcome.status_id } : { error: { code: outcome.code, message: outcome.message } };
|
|
12300
|
+
var wireIdOf = (value) => {
|
|
12301
|
+
const id = value && typeof value === "object" ? value.wireId ?? value.wire_id : void 0;
|
|
12302
|
+
return typeof id === "string" && id ? id : void 0;
|
|
12303
|
+
};
|
|
12304
|
+
var unsupportedPeer = (error) => /unsupported_peer/.test(String(error?.message ?? error));
|
|
12305
|
+
function isStatusCommandMessage(message) {
|
|
12306
|
+
if (message?.message_kind !== "command" || typeof message.body !== "string") return false;
|
|
12307
|
+
try {
|
|
12308
|
+
return OWN_COMMANDS.has(JSON.parse(message.body).command ?? "");
|
|
12309
|
+
} catch {
|
|
12310
|
+
return false;
|
|
12311
|
+
}
|
|
12312
|
+
}
|
|
12313
|
+
function answerText(status) {
|
|
12314
|
+
const answer = status.answer;
|
|
12315
|
+
const labels = (answer.selection ?? []).map((id) => status.interaction?.options?.find((option2) => option2.id === id)?.label ?? id);
|
|
12316
|
+
const parts = [...labels, ...answer.text === void 0 ? [] : [answer.text]];
|
|
12317
|
+
return `Answer to your question "${status.title}" (${status.status_id}):
|
|
12318
|
+
${parts.join("\n")}`;
|
|
12319
|
+
}
|
|
12320
|
+
var StatusService = class {
|
|
12321
|
+
constructor(store, client, outbox, warn = () => {
|
|
12322
|
+
}) {
|
|
12323
|
+
this.store = store;
|
|
12324
|
+
this.client = client;
|
|
12325
|
+
this.outbox = outbox;
|
|
12326
|
+
this.warn = warn;
|
|
12327
|
+
store.onChange(() => this.flushNotifications());
|
|
12328
|
+
}
|
|
12329
|
+
ingesting;
|
|
12330
|
+
again = false;
|
|
12331
|
+
delivering = /* @__PURE__ */ new Map();
|
|
12332
|
+
/**
|
|
12333
|
+
* Advertise the status commands, settle attempts a restart interrupted, flush pending push work and ingest.
|
|
12334
|
+
* An attempt left pending by a crash may or may not have reached the agent: it becomes `not_delivered` with that
|
|
12335
|
+
* reason, and only the Owner's Try again sends it again.
|
|
12336
|
+
*/
|
|
12337
|
+
async start(now = /* @__PURE__ */ new Date()) {
|
|
12338
|
+
await this.advertise();
|
|
12339
|
+
for (const status of this.store.list()) {
|
|
12340
|
+
const delivery = status.answer?.delivery;
|
|
12341
|
+
if (delivery?.state === "pending")
|
|
12342
|
+
this.store.settleDelivery(status.status_id, delivery.command_id, {
|
|
12343
|
+
state: "not_delivered",
|
|
12344
|
+
command_id: delivery.command_id,
|
|
12345
|
+
at: now.toISOString(),
|
|
12346
|
+
reason: "the server restarted before the delivery result was known; use Try again if the agent did not receive it"
|
|
12347
|
+
});
|
|
12348
|
+
}
|
|
12349
|
+
this.flushNotifications();
|
|
12350
|
+
await this.ingest();
|
|
12351
|
+
}
|
|
12352
|
+
/** Merge the status commands into the identity's advertised catalog. */
|
|
12353
|
+
async advertise() {
|
|
12354
|
+
const current = await this.client.listSelfCommands();
|
|
12355
|
+
const foreign = current.filter((command) => !OWN_COMMANDS.has(command.name));
|
|
12356
|
+
const refuse = () => {
|
|
12357
|
+
throw new Error("handled by another process");
|
|
12358
|
+
};
|
|
12359
|
+
const commands = [
|
|
12360
|
+
...foreign.map((command) => ({ ...command, handler: refuse })),
|
|
12361
|
+
{ ...STATUS_COMMAND_DEFINITIONS[0], handler: async (args, ctx) => outcomeJson(await this.ingestPublish({ cid: ctx.sender_cid, name: ctx.sender_name }, args, ctx.request_wire_id)) },
|
|
12362
|
+
{ ...STATUS_COMMAND_DEFINITIONS[1], handler: (args, ctx) => outcomeJson(this.store.ingestClose({ cid: ctx.sender_cid }, args, ctx.request_wire_id)) }
|
|
12363
|
+
];
|
|
12364
|
+
await this.client.registerCommands(commands);
|
|
12365
|
+
}
|
|
12366
|
+
/**
|
|
12367
|
+
* A publish whose attachments name files by wire ID. Each must be a file this Messenger RECEIVED from the same
|
|
12368
|
+
* author; its metadata comes from the file history, and any metadata the agent supplied must match it. A status can
|
|
12369
|
+
* therefore never present another contact's file, or the Owner's own, as the author's. An already ingested command
|
|
12370
|
+
* keeps its recorded outcome: a refused publish stays refused, and the agent sends a new command after the file.
|
|
12371
|
+
*/
|
|
12372
|
+
async ingestPublish(author, args, wireId) {
|
|
12373
|
+
if (this.store.ingested(wireId)) return this.store.ingestPublish(author, args, wireId);
|
|
12374
|
+
let resolved = args, refusal;
|
|
12375
|
+
try {
|
|
12376
|
+
resolved = await this.canonicalAttachments(author.cid, args);
|
|
12377
|
+
} catch (error) {
|
|
12378
|
+
if (!(error instanceof StatusError)) throw error;
|
|
12379
|
+
refusal = error;
|
|
12380
|
+
}
|
|
12381
|
+
return this.store.ingestPublish(author, resolved, wireId, /* @__PURE__ */ new Date(), refusal);
|
|
12382
|
+
}
|
|
12383
|
+
async canonicalAttachments(authorCid, args) {
|
|
12384
|
+
if (!args || typeof args !== "object" || Array.isArray(args)) return args;
|
|
12385
|
+
const raw = args.attachments;
|
|
12386
|
+
if (!Array.isArray(raw) || raw.length === 0 || raw.length > STATUS_ATTACHMENTS_MAX) return args;
|
|
12387
|
+
const attachments = [];
|
|
12388
|
+
for (const [index, item] of raw.entries()) {
|
|
12389
|
+
const given = item && typeof item === "object" && !Array.isArray(item) ? item : void 0;
|
|
12390
|
+
if (typeof given?.id !== "string") return args;
|
|
12391
|
+
const unknown = Object.keys(given).find((key) => !ATTACHMENT_KEYS.includes(key));
|
|
12392
|
+
if (unknown !== void 0)
|
|
12393
|
+
throw new StatusError("attachment_invalid", `attachments[${index}].${unknown} is not a known attachment field`);
|
|
12394
|
+
const file = this.client.getFileInfo ? await this.client.getFileInfo({ wire_id: given.id }) : null;
|
|
12395
|
+
if (!file)
|
|
12396
|
+
throw new StatusError("attachment_not_received", `attachments[${index}] is not a file received from you; send the file first, then publish`);
|
|
12397
|
+
if (file.direction !== "in" || canonicalCid(file.from.id) !== canonicalCid(authorCid))
|
|
12398
|
+
throw new StatusError("attachment_invalid", `attachments[${index}] was not sent by you`);
|
|
12399
|
+
const canonical3 = { id: file.wire_id, name: file.filename, media_type: file.mime, size: file.size, sha256: file.sha256 };
|
|
12400
|
+
for (const key of ["name", "media_type", "size", "sha256"])
|
|
12401
|
+
if (given[key] !== void 0 && given[key] !== canonical3[key])
|
|
12402
|
+
throw new StatusError("attachment_invalid", `attachments[${index}].${key} does not match the file you sent`);
|
|
12403
|
+
attachments.push(canonical3);
|
|
12404
|
+
}
|
|
12405
|
+
return { ...args, attachments };
|
|
12406
|
+
}
|
|
12407
|
+
/** Ingest unread status commands; overlapping requests coalesce into one follow-up pass. */
|
|
12408
|
+
ingest() {
|
|
12409
|
+
if (this.ingesting) {
|
|
12410
|
+
this.again = true;
|
|
12411
|
+
return this.ingesting;
|
|
12412
|
+
}
|
|
12413
|
+
return this.ingesting = this.ingestOnce().finally(() => {
|
|
12414
|
+
this.ingesting = void 0;
|
|
12415
|
+
if (this.again) {
|
|
12416
|
+
this.again = false;
|
|
12417
|
+
void this.ingest();
|
|
12418
|
+
}
|
|
12419
|
+
});
|
|
12420
|
+
}
|
|
12421
|
+
async ingestOnce() {
|
|
12422
|
+
const rows = await this.client.listIncomingMessages();
|
|
12423
|
+
const ours = [];
|
|
12424
|
+
for (const row of rows) {
|
|
12425
|
+
if (row.message_kind !== "command") continue;
|
|
12426
|
+
const message = await this.client.getHistoryItem({ wire_id: row.wire_id });
|
|
12427
|
+
if (!message || message.direction !== "in" || !isStatusCommandMessage(message)) continue;
|
|
12428
|
+
const { command, arguments: args } = JSON.parse(message.body);
|
|
12429
|
+
const author = { cid: message.from.id, name: message.from.name };
|
|
12430
|
+
if (command === PUBLISH_COMMAND) await this.ingestPublish(author, args, message.wire_id);
|
|
12431
|
+
else this.store.ingestClose(author, args, message.wire_id);
|
|
12432
|
+
ours.push(message.wire_id);
|
|
12433
|
+
}
|
|
12434
|
+
if (ours.length) await this.client.getMessages({ wire_ids: ours });
|
|
12435
|
+
}
|
|
12436
|
+
/**
|
|
12437
|
+
* Hand committed push work to the durable outbox, then clear it from the status (replay-safe by event ID). Oldest
|
|
12438
|
+
* status first; a status's events stay in order (a resolve never overtakes its send). Work that is refused (outbox
|
|
12439
|
+
* full) or fails (storage) stays on the status and is handed off by the next call — every change, and the server's
|
|
12440
|
+
* existing periodic recovery tick (`recover`), so it progresses without unrelated status traffic or a restart.
|
|
12441
|
+
*/
|
|
12442
|
+
flushNotifications() {
|
|
12443
|
+
if (!this.outbox) return;
|
|
12444
|
+
let statuses;
|
|
12445
|
+
try {
|
|
12446
|
+
statuses = this.store.list().sort((a, b2) => a.created_at.localeCompare(b2.created_at) || a.status_id.localeCompare(b2.status_id));
|
|
12447
|
+
} catch (error) {
|
|
12448
|
+
this.warn(`Status notifications pending: ${error.message}`);
|
|
12449
|
+
return;
|
|
12450
|
+
}
|
|
12451
|
+
let full = false;
|
|
12452
|
+
for (const status of statuses) {
|
|
12453
|
+
const events = status.notification_events ?? [];
|
|
12454
|
+
if (!events.length) continue;
|
|
12455
|
+
const handed = /* @__PURE__ */ new Set();
|
|
12456
|
+
try {
|
|
12457
|
+
for (const event of events) {
|
|
12458
|
+
if (event.op === "send") {
|
|
12459
|
+
const accepted = this.outbox.enqueueEvent({
|
|
12460
|
+
eventId: event.eventId,
|
|
12461
|
+
title: event.title,
|
|
12462
|
+
body: event.body,
|
|
12463
|
+
target: { kind: "status", authorCid: status.author.identity_cid, statusId: status.status_id },
|
|
12464
|
+
delivery: event.delivery
|
|
12465
|
+
});
|
|
12466
|
+
if (!accepted) {
|
|
12467
|
+
full = true;
|
|
12468
|
+
break;
|
|
12469
|
+
}
|
|
12470
|
+
} else this.outbox.enqueueResolve(event.eventId);
|
|
12471
|
+
handed.add(`${event.op}:${event.eventId}`);
|
|
12472
|
+
}
|
|
12473
|
+
this.store.clearEvents(status.status_id, handed);
|
|
12474
|
+
} catch (error) {
|
|
12475
|
+
this.warn(`Status notifications pending for ${status.status_id}: ${error.message}`);
|
|
12476
|
+
}
|
|
12477
|
+
if (full) {
|
|
12478
|
+
this.warn("Notification outbox is full; status pushes stay pending");
|
|
12479
|
+
break;
|
|
12480
|
+
}
|
|
12481
|
+
}
|
|
12482
|
+
this.outbox.prompt();
|
|
12483
|
+
}
|
|
12484
|
+
/** The periodic recovery tick: hand off retained push work, then ingest any status command a prompt missed. */
|
|
12485
|
+
recover() {
|
|
12486
|
+
this.flushNotifications();
|
|
12487
|
+
return this.ingest();
|
|
12488
|
+
}
|
|
12489
|
+
/** The Owner answers (feed or chat): first answer wins; delivery is attempted once, receipt-checked. */
|
|
12490
|
+
async answer(statusId, input) {
|
|
12491
|
+
const result = this.store.answer(statusId, input);
|
|
12492
|
+
if (result.replayed) return result;
|
|
12493
|
+
return { status: await this.deliver(statusId), replayed: false };
|
|
12494
|
+
}
|
|
12495
|
+
/** The Owner's manual Try again after `not_delivered`. */
|
|
12496
|
+
async retry(statusId) {
|
|
12497
|
+
this.store.retryDelivery(statusId);
|
|
12498
|
+
return this.deliver(statusId);
|
|
12499
|
+
}
|
|
12500
|
+
/** One delivery attempt for the pending answer: the typed command, or the readable text when unsupported. */
|
|
12501
|
+
deliver(statusId) {
|
|
12502
|
+
const running = this.delivering.get(statusId);
|
|
12503
|
+
if (running) return running;
|
|
12504
|
+
const attempt = this.deliverOnce(statusId).finally(() => this.delivering.delete(statusId));
|
|
12505
|
+
this.delivering.set(statusId, attempt);
|
|
12506
|
+
return attempt;
|
|
12507
|
+
}
|
|
12508
|
+
async deliverOnce(statusId) {
|
|
12509
|
+
const status = this.store.get(statusId);
|
|
12510
|
+
const delivery = status?.answer?.delivery;
|
|
12511
|
+
if (!status || delivery?.state !== "pending") return status;
|
|
12512
|
+
const { command_id: commandId } = delivery;
|
|
12513
|
+
const at2 = () => (/* @__PURE__ */ new Date()).toISOString();
|
|
12514
|
+
const answer = status.answer;
|
|
12515
|
+
try {
|
|
12516
|
+
const sent = await this.client.sendCommand({ contact: status.author.identity_cid, command: ANSWER_COMMAND, arguments: {
|
|
12517
|
+
status_id: status.status_id,
|
|
12518
|
+
submission_id: answer.submission_id,
|
|
12519
|
+
question: status.title,
|
|
12520
|
+
...answer.selection ? { selection: answer.selection } : {},
|
|
12521
|
+
...answer.text === void 0 ? {} : { text: answer.text }
|
|
12522
|
+
} });
|
|
12523
|
+
const wireId = wireIdOf(sent);
|
|
12524
|
+
return this.store.settleDelivery(statusId, commandId, wireId ? { state: "delivered", command_id: commandId, at: at2(), wire_id: wireId } : { state: "not_delivered", command_id: commandId, at: at2(), reason: "the answer command was not accepted" });
|
|
12525
|
+
} catch (error) {
|
|
12526
|
+
if (!unsupportedPeer(error)) {
|
|
12527
|
+
return this.store.settleDelivery(statusId, commandId, {
|
|
12528
|
+
state: "not_delivered",
|
|
12529
|
+
command_id: commandId,
|
|
12530
|
+
at: at2(),
|
|
12531
|
+
reason: `the answer could not be sent: ${String(error?.message ?? error).slice(0, 300)}`
|
|
12532
|
+
});
|
|
12533
|
+
}
|
|
12534
|
+
}
|
|
12535
|
+
try {
|
|
12536
|
+
const sent = await this.client.sendMessage({
|
|
12537
|
+
contact: status.author.identity_cid,
|
|
12538
|
+
text: answerText(status),
|
|
12539
|
+
reply_to_wire_id: status.request_wire_id
|
|
12540
|
+
});
|
|
12541
|
+
const wireId = wireIdOf(sent);
|
|
12542
|
+
return this.store.settleDelivery(statusId, commandId, wireId ? { state: "delivered_as_text", command_id: commandId, at: at2(), wire_id: wireId } : { state: "not_delivered", command_id: commandId, at: at2(), reason: "the text reply was not accepted" });
|
|
12543
|
+
} catch (error) {
|
|
12544
|
+
return this.store.settleDelivery(statusId, commandId, {
|
|
12545
|
+
state: "not_delivered",
|
|
12546
|
+
command_id: commandId,
|
|
12547
|
+
at: at2(),
|
|
12548
|
+
reason: `the text reply could not be sent: ${String(error?.message ?? error).slice(0, 300)}`
|
|
12549
|
+
});
|
|
12550
|
+
}
|
|
12551
|
+
}
|
|
12552
|
+
};
|
|
12553
|
+
|
|
11728
12554
|
// src/notification-producer.ts
|
|
11729
12555
|
var MessengerNotificationProducer = class {
|
|
11730
12556
|
constructor(stateDir, config, identityCid, client, warn) {
|
|
@@ -11735,9 +12561,10 @@ var MessengerNotificationProducer = class {
|
|
|
11735
12561
|
if (!Array.isArray(view.contacts) || !Array.isArray(view.pending) || [...view.contacts, ...view.pending].some((contact) => typeof contact?.container_id !== "string")) throw Error("Contact inventory unavailable");
|
|
11736
12562
|
return [...view.contacts, ...view.pending].some((contact) => contactIdentity(contact.container_id) === contactIdentity(cid));
|
|
11737
12563
|
};
|
|
11738
|
-
this.outbox = new NotificationOutbox(
|
|
12564
|
+
this.outbox = new NotificationOutbox(join2(stateDir, "notification-outbox.json"), config, async (value, eventId) => {
|
|
11739
12565
|
const record = value;
|
|
11740
12566
|
if (await knownContact(record.sender_id) === false) return;
|
|
12567
|
+
if (record.event === "message_received" && client.getHistoryItem && isStatusCommandMessage(await client.getHistoryItem({ wire_id: record.wire_id }))) return;
|
|
11741
12568
|
const event = await projectPushEvent(client, {
|
|
11742
12569
|
contactId: record.sender_id,
|
|
11743
12570
|
wireId: record.wire_id,
|
|
@@ -11778,7 +12605,7 @@ var MessengerNotificationProducer = class {
|
|
|
11778
12605
|
const record = value;
|
|
11779
12606
|
if (typeof record?.sender_id === "string" && contactIdentity(record.sender_id) === contactIdentity(cid)) return true;
|
|
11780
12607
|
if (!payload) return false;
|
|
11781
|
-
return contactIdentity(payload.target.contactId) === contactIdentity(cid);
|
|
12608
|
+
return payload.target.kind === "contact" && contactIdentity(payload.target.contactId) === contactIdentity(cid);
|
|
11782
12609
|
});
|
|
11783
12610
|
void this.outbox.drain();
|
|
11784
12611
|
}
|
|
@@ -11791,7 +12618,7 @@ var MessengerNotificationProducer = class {
|
|
|
11791
12618
|
import { existsSync as existsSync3 } from "node:fs";
|
|
11792
12619
|
import { readFile, realpath, stat } from "node:fs/promises";
|
|
11793
12620
|
import { createServer } from "node:http";
|
|
11794
|
-
import { dirname as dirname5, extname, isAbsolute as isAbsolute2, relative, resolve as
|
|
12621
|
+
import { dirname as dirname5, extname, isAbsolute as isAbsolute2, relative, resolve as resolve4, sep } from "node:path";
|
|
11795
12622
|
import { fileURLToPath } from "node:url";
|
|
11796
12623
|
import { Worker } from "node:worker_threads";
|
|
11797
12624
|
|
|
@@ -11804,12 +12631,12 @@ import { randomUUID as randomUUID2 } from "node:crypto";
|
|
|
11804
12631
|
|
|
11805
12632
|
// src/workspace-profile.ts
|
|
11806
12633
|
init_define_MESSENGER_BUILD_INFO();
|
|
11807
|
-
import { existsSync as existsSync2, lstatSync, mkdirSync as
|
|
11808
|
-
import { join as
|
|
12634
|
+
import { existsSync as existsSync2, lstatSync, mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "node:fs";
|
|
12635
|
+
import { join as join3, resolve as resolve2 } from "node:path";
|
|
11809
12636
|
import { randomUUID } from "node:crypto";
|
|
11810
12637
|
var profileObservers = /* @__PURE__ */ new Map();
|
|
11811
12638
|
function profileKey(dir, cid) {
|
|
11812
|
-
return
|
|
12639
|
+
return resolve2(path(dir, cid));
|
|
11813
12640
|
}
|
|
11814
12641
|
function subscribeHumanProfile(dir, cid, onCommitted, signal) {
|
|
11815
12642
|
if (signal.aborted) return () => {
|
|
@@ -11843,7 +12670,7 @@ function profileName(value) {
|
|
|
11843
12670
|
}
|
|
11844
12671
|
function path(dir, cid) {
|
|
11845
12672
|
if (!/^[a-f0-9]{64}$/i.test(cid)) throw Error("Invalid identity");
|
|
11846
|
-
return
|
|
12673
|
+
return join3(dir, "human-" + cid.toLowerCase() + ".json");
|
|
11847
12674
|
}
|
|
11848
12675
|
function readHumanProfile(dir, cid) {
|
|
11849
12676
|
if (!/^[a-f0-9]{64}$/i.test(cid)) return;
|
|
@@ -11851,12 +12678,12 @@ function readHumanProfile(dir, cid) {
|
|
|
11851
12678
|
if (!existsSync2(file)) return;
|
|
11852
12679
|
const stat2 = lstatSync(file);
|
|
11853
12680
|
if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.nlink !== 1 || stat2.uid !== process.getuid?.() || (stat2.mode & 63) !== 0) throw Error("Private profile path required");
|
|
11854
|
-
const row = JSON.parse(
|
|
12681
|
+
const row = JSON.parse(readFileSync3(file, "utf8"));
|
|
11855
12682
|
return workspaceProfile(row);
|
|
11856
12683
|
}
|
|
11857
12684
|
function writeHumanProfile(dir, cid, value) {
|
|
11858
12685
|
const row = workspaceProfile(value);
|
|
11859
|
-
|
|
12686
|
+
mkdirSync3(dir, { recursive: true, mode: 448 });
|
|
11860
12687
|
const directory = lstatSync(dir);
|
|
11861
12688
|
if (!directory.isDirectory() || directory.isSymbolicLink() || directory.uid !== process.getuid?.() || (directory.mode & 63) !== 0) throw Error("Private profile directory required");
|
|
11862
12689
|
const file = path(dir, cid);
|
|
@@ -11865,15 +12692,15 @@ function writeHumanProfile(dir, cid, value) {
|
|
|
11865
12692
|
if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.nlink !== 1 || stat2.uid !== process.getuid?.() || (stat2.mode & 63) !== 0) throw Error("Private profile path required");
|
|
11866
12693
|
}
|
|
11867
12694
|
const temporary = file + "." + randomUUID();
|
|
11868
|
-
|
|
11869
|
-
|
|
12695
|
+
writeFileSync3(temporary, JSON.stringify(row) + "\n", { mode: 384, flag: "wx" });
|
|
12696
|
+
renameSync3(temporary, file);
|
|
11870
12697
|
publishHumanProfile(dir, cid);
|
|
11871
12698
|
return row;
|
|
11872
12699
|
}
|
|
11873
12700
|
|
|
11874
12701
|
// src/watch.ts
|
|
11875
12702
|
init_define_MESSENGER_BUILD_INFO();
|
|
11876
|
-
import { createHash } from "node:crypto";
|
|
12703
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
11877
12704
|
|
|
11878
12705
|
// src/events.ts
|
|
11879
12706
|
init_define_MESSENGER_BUILD_INFO();
|
|
@@ -11937,8 +12764,8 @@ var MessengerEventBus = class {
|
|
|
11937
12764
|
}
|
|
11938
12765
|
if (sub.closed) return Promise.resolve(null);
|
|
11939
12766
|
if (sub.waiting) throw new Error("only one pending next() is allowed per event subscriber");
|
|
11940
|
-
return new Promise((
|
|
11941
|
-
sub.waiting =
|
|
12767
|
+
return new Promise((resolve5) => {
|
|
12768
|
+
sub.waiting = resolve5;
|
|
11942
12769
|
});
|
|
11943
12770
|
},
|
|
11944
12771
|
close: () => this.#close(sub)
|
|
@@ -11948,9 +12775,9 @@ var MessengerEventBus = class {
|
|
|
11948
12775
|
for (const sub of this.#subscribers) {
|
|
11949
12776
|
if (sub.closed) continue;
|
|
11950
12777
|
if (sub.waiting) {
|
|
11951
|
-
const
|
|
12778
|
+
const resolve5 = sub.waiting;
|
|
11952
12779
|
sub.waiting = null;
|
|
11953
|
-
|
|
12780
|
+
resolve5(event);
|
|
11954
12781
|
continue;
|
|
11955
12782
|
}
|
|
11956
12783
|
if (sub.overflowed) continue;
|
|
@@ -11970,9 +12797,9 @@ var MessengerEventBus = class {
|
|
|
11970
12797
|
sub.closed = true;
|
|
11971
12798
|
sub.queue.length = 0;
|
|
11972
12799
|
this.#subscribers.delete(sub);
|
|
11973
|
-
const
|
|
12800
|
+
const resolve5 = sub.waiting;
|
|
11974
12801
|
sub.waiting = null;
|
|
11975
|
-
|
|
12802
|
+
resolve5?.(null);
|
|
11976
12803
|
}
|
|
11977
12804
|
};
|
|
11978
12805
|
function toSse(event, identity) {
|
|
@@ -11988,7 +12815,7 @@ function toSse(event, identity) {
|
|
|
11988
12815
|
|
|
11989
12816
|
// src/watch.ts
|
|
11990
12817
|
function pageDigest(events) {
|
|
11991
|
-
return
|
|
12818
|
+
return createHash2("sha256").update(JSON.stringify(events)).digest("base64url");
|
|
11992
12819
|
}
|
|
11993
12820
|
function applyNotificationPage(page, push, delivery, events, stats, log2) {
|
|
11994
12821
|
if (!Number.isSafeInteger(page.cursor) || page.cursor < 0 || !Array.isArray(page.events)) {
|
|
@@ -12034,12 +12861,12 @@ function applyNotificationPage(page, push, delivery, events, stats, log2) {
|
|
|
12034
12861
|
}
|
|
12035
12862
|
function abortableWait(ms, signal) {
|
|
12036
12863
|
if (signal.aborted) return Promise.resolve();
|
|
12037
|
-
return new Promise((
|
|
12864
|
+
return new Promise((resolve5) => {
|
|
12038
12865
|
const timer = setTimeout(done, ms);
|
|
12039
12866
|
function done() {
|
|
12040
12867
|
clearTimeout(timer);
|
|
12041
12868
|
signal.removeEventListener("abort", done);
|
|
12042
|
-
|
|
12869
|
+
resolve5();
|
|
12043
12870
|
}
|
|
12044
12871
|
signal.addEventListener("abort", done, { once: true });
|
|
12045
12872
|
});
|
|
@@ -12098,8 +12925,8 @@ function startResourceObserver(client, identity, callbacks) {
|
|
|
12098
12925
|
let readyResolve;
|
|
12099
12926
|
let readyReject;
|
|
12100
12927
|
let readySettled = false;
|
|
12101
|
-
const ready = new Promise((
|
|
12102
|
-
readyResolve =
|
|
12928
|
+
const ready = new Promise((resolve5, reject) => {
|
|
12929
|
+
readyResolve = resolve5;
|
|
12103
12930
|
readyReject = reject;
|
|
12104
12931
|
});
|
|
12105
12932
|
void ready.catch(() => {
|
|
@@ -12171,7 +12998,7 @@ init_define_MESSENGER_BUILD_INFO();
|
|
|
12171
12998
|
|
|
12172
12999
|
// src/typed-commands.ts
|
|
12173
13000
|
init_define_MESSENGER_BUILD_INFO();
|
|
12174
|
-
import { createHash as
|
|
13001
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
12175
13002
|
var MAX_COMMANDS = 64;
|
|
12176
13003
|
var MAX_COMMAND_NAME_LENGTH = 128;
|
|
12177
13004
|
var MAX_COMMAND_DESCRIPTION_LENGTH = 2048;
|
|
@@ -12231,7 +13058,7 @@ function projectCatalog(recipientCid, commands) {
|
|
|
12231
13058
|
input_schema: command.input_schema
|
|
12232
13059
|
};
|
|
12233
13060
|
});
|
|
12234
|
-
const fingerprint2 =
|
|
13061
|
+
const fingerprint2 = createHash3("sha256").update(canonical({
|
|
12235
13062
|
recipient_cid: recipientCid,
|
|
12236
13063
|
commands: projected
|
|
12237
13064
|
})).digest("base64url");
|
|
@@ -12375,23 +13202,23 @@ data: ${bytes.toString("utf8")}
|
|
|
12375
13202
|
yield { event: "resource-chunk", data: { ...binding, type: "commit", totalBytes: bytes.length } };
|
|
12376
13203
|
}
|
|
12377
13204
|
function canonicalResourceDescriptor(value) {
|
|
12378
|
-
const
|
|
13205
|
+
const invalid2 = () => {
|
|
12379
13206
|
throw new Error("invalid resource descriptor");
|
|
12380
13207
|
};
|
|
12381
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return
|
|
13208
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return invalid2();
|
|
12382
13209
|
const row = value;
|
|
12383
|
-
if (Object.keys(row).some((key) => !["viewId", "resource", "entityId", "window", "addressing"].includes(key)) || typeof row.viewId !== "string" || !/^[A-Za-z0-9_-]{1,128}$/.test(row.viewId) || !["contacts", "identity", "messages", "files", "commands", "activity"].includes(String(row.resource))) return
|
|
13210
|
+
if (Object.keys(row).some((key) => !["viewId", "resource", "entityId", "window", "addressing"].includes(key)) || typeof row.viewId !== "string" || !/^[A-Za-z0-9_-]{1,128}$/.test(row.viewId) || !["contacts", "identity", "messages", "files", "commands", "activity", "statuses"].includes(String(row.resource))) return invalid2();
|
|
12384
13211
|
const resource = row.resource;
|
|
12385
13212
|
const scoped = ["messages", "files", "commands"].includes(resource);
|
|
12386
|
-
if (scoped ? typeof row.entityId !== "string" || !row.entityId : row.entityId !== void 0) return
|
|
12387
|
-
if (row.addressing !== void 0 && (row.addressing !== "cid" || !["messages", "files"].includes(resource) || !/^[a-f0-9]{64}$/i.test(String(row.entityId)))) return
|
|
12388
|
-
if (resource !== "messages" && row.window !== void 0) return
|
|
13213
|
+
if (scoped ? typeof row.entityId !== "string" || !row.entityId : row.entityId !== void 0) return invalid2();
|
|
13214
|
+
if (row.addressing !== void 0 && (row.addressing !== "cid" || !["messages", "files"].includes(resource) || !/^[a-f0-9]{64}$/i.test(String(row.entityId)))) return invalid2();
|
|
13215
|
+
if (resource !== "messages" && row.window !== void 0) return invalid2();
|
|
12389
13216
|
let window2;
|
|
12390
13217
|
if (resource === "messages") {
|
|
12391
13218
|
const raw = row.window ?? { limit: 50, retainedPages: 1 };
|
|
12392
|
-
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return
|
|
13219
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return invalid2();
|
|
12393
13220
|
const w3 = raw;
|
|
12394
|
-
if (Object.keys(w3).some((key) => !["limit", "retainedPages", "oldestSequence"].includes(key)) || !Number.isInteger(w3.limit) || w3.limit < 1 || w3.limit > 200 || !Number.isSafeInteger(w3.retainedPages) || w3.retainedPages < 1 || w3.oldestSequence !== void 0 && (!Number.isSafeInteger(w3.oldestSequence) || w3.oldestSequence < 1)) return
|
|
13221
|
+
if (Object.keys(w3).some((key) => !["limit", "retainedPages", "oldestSequence"].includes(key)) || !Number.isInteger(w3.limit) || w3.limit < 1 || w3.limit > 200 || !Number.isSafeInteger(w3.retainedPages) || w3.retainedPages < 1 || w3.oldestSequence !== void 0 && (!Number.isSafeInteger(w3.oldestSequence) || w3.oldestSequence < 1)) return invalid2();
|
|
12395
13222
|
window2 = {
|
|
12396
13223
|
limit: w3.limit,
|
|
12397
13224
|
retainedPages: w3.retainedPages,
|
|
@@ -12496,8 +13323,8 @@ var ResourceOutput = class {
|
|
|
12496
13323
|
return this.#fail(new Error("resource pending limit exceeded"));
|
|
12497
13324
|
}
|
|
12498
13325
|
admitted();
|
|
12499
|
-
return new Promise((
|
|
12500
|
-
const item = { envelope, bytes, resolve:
|
|
13326
|
+
return new Promise((resolve5, reject) => {
|
|
13327
|
+
const item = { envelope, bytes, resolve: resolve5, reject };
|
|
12501
13328
|
if (!this.#active) {
|
|
12502
13329
|
this.#active = item;
|
|
12503
13330
|
void this.#pump();
|
|
@@ -12548,11 +13375,11 @@ data: ${JSON.stringify(frame.data)}
|
|
|
12548
13375
|
}
|
|
12549
13376
|
#drain() {
|
|
12550
13377
|
if (this.#closed) return Promise.resolve();
|
|
12551
|
-
return new Promise((
|
|
13378
|
+
return new Promise((resolve5) => {
|
|
12552
13379
|
const release = () => {
|
|
12553
13380
|
this.response.removeListener("drain", release);
|
|
12554
13381
|
this.#releaseDrain = void 0;
|
|
12555
|
-
|
|
13382
|
+
resolve5();
|
|
12556
13383
|
};
|
|
12557
13384
|
this.#releaseDrain = release;
|
|
12558
13385
|
this.response.once("drain", release);
|
|
@@ -12636,8 +13463,8 @@ var ResourceConnections = class {
|
|
|
12636
13463
|
open(response) {
|
|
12637
13464
|
const id = randomUUID2(), controller = new AbortController();
|
|
12638
13465
|
let resolveClosed;
|
|
12639
|
-
const closed2 = new Promise((
|
|
12640
|
-
resolveClosed =
|
|
13466
|
+
const closed2 = new Promise((resolve5) => {
|
|
13467
|
+
resolveClosed = resolve5;
|
|
12641
13468
|
});
|
|
12642
13469
|
let connection;
|
|
12643
13470
|
const close = () => {
|
|
@@ -12697,6 +13524,11 @@ data: ${JSON.stringify({
|
|
|
12697
13524
|
connection.localRevision++;
|
|
12698
13525
|
for (const view of connection.views.values()) if (view.descriptor.resource === "identity") this.#schedule(connection, view);
|
|
12699
13526
|
}, controller.signal);
|
|
13527
|
+
subscribeStatuses(this.deps.stateDir, this.deps.identityCid, () => {
|
|
13528
|
+
if (!connection || controller.signal.aborted) return;
|
|
13529
|
+
connection.localRevision++;
|
|
13530
|
+
for (const view of connection.views.values()) if (view.descriptor.resource === "statuses") this.#schedule(connection, view);
|
|
13531
|
+
}, controller.signal);
|
|
12700
13532
|
response.write(`event: resource-connection
|
|
12701
13533
|
data: ${JSON.stringify({
|
|
12702
13534
|
protocolVersion: 1,
|
|
@@ -12731,8 +13563,8 @@ data: ${JSON.stringify({
|
|
|
12731
13563
|
if (!connection.epochs.has(viewId) && connection.epochs.size >= 256) throw new ResourceBindingError(503, "resource epoch capacity exceeded");
|
|
12732
13564
|
if (current) this.#retire(current);
|
|
12733
13565
|
let resolveInitial, rejectInitial;
|
|
12734
|
-
const initial = new Promise((
|
|
12735
|
-
resolveInitial =
|
|
13566
|
+
const initial = new Promise((resolve5, reject) => {
|
|
13567
|
+
resolveInitial = resolve5;
|
|
12736
13568
|
rejectInitial = reject;
|
|
12737
13569
|
});
|
|
12738
13570
|
void initial.catch(() => {
|
|
@@ -12838,7 +13670,7 @@ data: ${JSON.stringify({
|
|
|
12838
13670
|
#coverage(connection, source) {
|
|
12839
13671
|
const now = Date.now();
|
|
12840
13672
|
if (now - (connection.coverageAt ?? -Infinity) < 15e3 || !connection.observer.healthy) return Promise.resolve();
|
|
12841
|
-
const eligible = [...connection.views.values()].filter((view) => this.#current(connection, view) && !view.failed && !view.running && !view.dirty && view.payload !== void 0 && view.covered && view.covered.producerGeneration === source.producerGeneration && view.covered.position === source.position && (view.descriptor.resource !== "identity" || view.localRevision === connection.localRevision) && now - (view.qualifiedAt ?? 0) >= 15e3);
|
|
13673
|
+
const eligible = [...connection.views.values()].filter((view) => this.#current(connection, view) && !view.failed && !view.running && !view.dirty && view.payload !== void 0 && view.covered && view.covered.producerGeneration === source.producerGeneration && view.covered.position === source.position && (view.descriptor.resource !== "identity" && view.descriptor.resource !== "statuses" || view.localRevision === connection.localRevision) && now - (view.qualifiedAt ?? 0) >= 15e3);
|
|
12842
13674
|
if (!eligible.length) return Promise.resolve();
|
|
12843
13675
|
const views = eligible.map((view) => ({
|
|
12844
13676
|
protocolVersion: 1,
|
|
@@ -12936,9 +13768,9 @@ function mediaResponsePolicy(mime2) {
|
|
|
12936
13768
|
|
|
12937
13769
|
// src/command-invocations.ts
|
|
12938
13770
|
init_define_MESSENGER_BUILD_INFO();
|
|
12939
|
-
import { createHash as
|
|
12940
|
-
import { chmodSync, mkdirSync as
|
|
12941
|
-
import { dirname as dirname2, join as
|
|
13771
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
13772
|
+
import { chmodSync, mkdirSync as mkdirSync4, readFileSync as readFileSync4, renameSync as renameSync4, writeFileSync as writeFileSync4 } from "node:fs";
|
|
13773
|
+
import { dirname as dirname2, join as join4 } from "node:path";
|
|
12942
13774
|
var MAX_INVOCATIONS = 4096;
|
|
12943
13775
|
var InvocationConflictError = class extends Error {
|
|
12944
13776
|
};
|
|
@@ -12950,7 +13782,7 @@ function canonical2(value) {
|
|
|
12950
13782
|
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical2(value[key])}`).join(",")}}`;
|
|
12951
13783
|
}
|
|
12952
13784
|
function invocationFingerprint(input) {
|
|
12953
|
-
return
|
|
13785
|
+
return createHash4("sha256").update(canonical2(input)).digest("base64url");
|
|
12954
13786
|
}
|
|
12955
13787
|
function validRecord(value) {
|
|
12956
13788
|
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
@@ -12965,10 +13797,10 @@ var CommandInvocationStore = class _CommandInvocationStore {
|
|
|
12965
13797
|
}
|
|
12966
13798
|
static open(stateDir, identityCid, capacity = MAX_INVOCATIONS) {
|
|
12967
13799
|
if (!Number.isInteger(capacity) || capacity < 1) throw new Error("invocation capacity must be a positive integer");
|
|
12968
|
-
const file =
|
|
13800
|
+
const file = join4(stateDir, `typed-commands-${createHash4("sha256").update(identityCid).digest("hex").slice(0, 24)}.json`);
|
|
12969
13801
|
let state = { version: 1, records: {} };
|
|
12970
13802
|
try {
|
|
12971
|
-
const parsed = JSON.parse(
|
|
13803
|
+
const parsed = JSON.parse(readFileSync4(file, "utf8"));
|
|
12972
13804
|
if (!parsed || typeof parsed !== "object" || parsed.version !== 1 || !parsed.records || typeof parsed.records !== "object" || !Object.values(parsed.records).every(validRecord)) {
|
|
12973
13805
|
throw new Error("invalid typed command invocation state");
|
|
12974
13806
|
}
|
|
@@ -13016,11 +13848,11 @@ var CommandInvocationStore = class _CommandInvocationStore {
|
|
|
13016
13848
|
return record;
|
|
13017
13849
|
}
|
|
13018
13850
|
save() {
|
|
13019
|
-
|
|
13851
|
+
mkdirSync4(dirname2(this.file), { recursive: true, mode: 448 });
|
|
13020
13852
|
const temp = `${this.file}.${process.pid}.tmp`;
|
|
13021
|
-
|
|
13853
|
+
writeFileSync4(temp, JSON.stringify(this.state), { mode: 384 });
|
|
13022
13854
|
chmodSync(temp, 384);
|
|
13023
|
-
|
|
13855
|
+
renameSync4(temp, this.file);
|
|
13024
13856
|
}
|
|
13025
13857
|
};
|
|
13026
13858
|
function statusFor(delivery, wireId) {
|
|
@@ -13230,13 +14062,13 @@ var Preprocessor = class {
|
|
|
13230
14062
|
return this.droppedBufferSize + this.pos;
|
|
13231
14063
|
}
|
|
13232
14064
|
getError(code, cpOffset) {
|
|
13233
|
-
const { line, col, offset } = this;
|
|
14065
|
+
const { line: line2, col, offset } = this;
|
|
13234
14066
|
const startCol = col + cpOffset;
|
|
13235
14067
|
const startOffset = offset + cpOffset;
|
|
13236
14068
|
return {
|
|
13237
14069
|
code,
|
|
13238
|
-
startLine:
|
|
13239
|
-
endLine:
|
|
14070
|
+
startLine: line2,
|
|
14071
|
+
endLine: line2,
|
|
13240
14072
|
startCol,
|
|
13241
14073
|
endCol: startCol,
|
|
13242
14074
|
startOffset,
|
|
@@ -18381,12 +19213,12 @@ var Parser = class {
|
|
|
18381
19213
|
/** @protected */
|
|
18382
19214
|
_insertTemplate(token) {
|
|
18383
19215
|
const tmpl = this.treeAdapter.createElement(token.tagName, NS.HTML, token.attrs);
|
|
18384
|
-
const
|
|
18385
|
-
this.treeAdapter.setTemplateContent(tmpl,
|
|
19216
|
+
const content2 = this.treeAdapter.createDocumentFragment();
|
|
19217
|
+
this.treeAdapter.setTemplateContent(tmpl, content2);
|
|
18386
19218
|
this._attachElementToTree(tmpl, token.location);
|
|
18387
19219
|
this.openElements.push(tmpl, token.tagID);
|
|
18388
19220
|
if (this.options.sourceCodeLocationInfo)
|
|
18389
|
-
this.treeAdapter.setNodeSourceCodeLocation(
|
|
19221
|
+
this.treeAdapter.setNodeSourceCodeLocation(content2, null);
|
|
18390
19222
|
}
|
|
18391
19223
|
/** @protected */
|
|
18392
19224
|
_insertFakeRootElement() {
|
|
@@ -21265,10 +22097,10 @@ function serializeAttributes(node, { treeAdapter }) {
|
|
|
21265
22097
|
}
|
|
21266
22098
|
function serializeTextNode(node, options) {
|
|
21267
22099
|
const { treeAdapter } = options;
|
|
21268
|
-
const
|
|
22100
|
+
const content2 = treeAdapter.getTextNodeContent(node);
|
|
21269
22101
|
const parent = treeAdapter.getParentNode(node);
|
|
21270
22102
|
const parentTn = parent && treeAdapter.isElementNode(parent) && treeAdapter.getTagName(parent);
|
|
21271
|
-
return parentTn && treeAdapter.getNamespaceURI(parent) === NS.HTML && hasUnescapedText(parentTn, options.scriptingEnabled) ?
|
|
22103
|
+
return parentTn && treeAdapter.getNamespaceURI(parent) === NS.HTML && hasUnescapedText(parentTn, options.scriptingEnabled) ? content2 : escapeText(content2);
|
|
21272
22104
|
}
|
|
21273
22105
|
function serializeCommentNode(node, { treeAdapter }) {
|
|
21274
22106
|
return `<!--${treeAdapter.getCommentNodeContent(node)}-->`;
|
|
@@ -21445,6 +22277,15 @@ var HttpError = class extends Error {
|
|
|
21445
22277
|
}
|
|
21446
22278
|
};
|
|
21447
22279
|
var bad = (m2) => new HttpError(400, m2);
|
|
22280
|
+
function statusService(deps) {
|
|
22281
|
+
if (!deps.statuses) throw new HttpError(404, "Agent statuses are unavailable (typed commands are disabled)");
|
|
22282
|
+
return deps.statuses;
|
|
22283
|
+
}
|
|
22284
|
+
function statusHttpError(error) {
|
|
22285
|
+
if (!(error instanceof StatusError)) return error;
|
|
22286
|
+
const status = error.code === "not_found" ? 404 : error.code === "forbidden" ? 403 : error.code === "conflict" || error.code === "idempotency_conflict" ? 409 : error.code === "limit_exceeded" ? 413 : 400;
|
|
22287
|
+
return new HttpError(status, error.message);
|
|
22288
|
+
}
|
|
21448
22289
|
function str(body, key) {
|
|
21449
22290
|
const v2 = body[key];
|
|
21450
22291
|
if (typeof v2 !== "string" || v2 === "") throw bad(`${key} must be a non-empty string`);
|
|
@@ -21787,8 +22628,8 @@ async function serveEvents(req, res, deps) {
|
|
|
21787
22628
|
};
|
|
21788
22629
|
const waitForDrain = () => {
|
|
21789
22630
|
if (drainWait) return drainWait;
|
|
21790
|
-
drainWait = new Promise((
|
|
21791
|
-
releaseDrain =
|
|
22631
|
+
drainWait = new Promise((resolve5) => {
|
|
22632
|
+
releaseDrain = resolve5;
|
|
21792
22633
|
});
|
|
21793
22634
|
res.once("drain", onDrain);
|
|
21794
22635
|
return drainWait;
|
|
@@ -21878,6 +22719,8 @@ async function projectResourceView(deps, input, signal, source) {
|
|
|
21878
22719
|
return projectCommandResource(client, deps, { contact: descriptor.entityId });
|
|
21879
22720
|
case "activity":
|
|
21880
22721
|
return projectActivity(client, signal, source);
|
|
22722
|
+
case "statuses":
|
|
22723
|
+
return listFeed(statusService(deps).store, { kind: "global" }, { limit: FEED_PAGE_MAX });
|
|
21881
22724
|
case "messages": {
|
|
21882
22725
|
const pin = descriptor.addressing === "cid" ? canonicalPeer(descriptor.entityId) : void 0;
|
|
21883
22726
|
const peer = pin ? { cid: pin.cid, announcedName: "" } : await resolveContact(client, descriptor.entityId);
|
|
@@ -21971,6 +22814,75 @@ var ROUTES = {
|
|
|
21971
22814
|
return { wire_id: wireId, delivery: "tracked" };
|
|
21972
22815
|
},
|
|
21973
22816
|
"GET /api/contacts/:contact/commands": async ({ client, deps, params }) => projectCommandResource(client, deps, params),
|
|
22817
|
+
// ---- external agents' statuses (canonical here; Fleet agents' statuses stay in Fleet) -------------------------
|
|
22818
|
+
"GET /api/statuses": async ({ deps, query }) => {
|
|
22819
|
+
const extra = [...query.keys()].filter((key) => !["scope", "agent", "after", "limit"].includes(key) || query.getAll(key).length !== 1);
|
|
22820
|
+
if (extra.length) throw bad(`unexpected query ${extra[0]}`);
|
|
22821
|
+
try {
|
|
22822
|
+
const after = query.get("after") ?? void 0, limit = query.get("limit");
|
|
22823
|
+
return listFeed(
|
|
22824
|
+
statusService(deps).store,
|
|
22825
|
+
feedScope({ scope: query.get("scope") ?? void 0, agent: query.get("agent") ?? void 0 }),
|
|
22826
|
+
{ ...after === void 0 ? {} : { after }, ...limit === null ? {} : { limit: Number(limit) } }
|
|
22827
|
+
);
|
|
22828
|
+
} catch (error) {
|
|
22829
|
+
throw statusHttpError(error);
|
|
22830
|
+
}
|
|
22831
|
+
},
|
|
22832
|
+
"GET /api/statuses/:statusId": async ({ deps, params }) => {
|
|
22833
|
+
const status = statusService(deps).store.get(params.statusId);
|
|
22834
|
+
if (!status) throw new HttpError(404, "status not found");
|
|
22835
|
+
return { status: publicStatus(status) };
|
|
22836
|
+
},
|
|
22837
|
+
/** The chat ("session") card: the status a `ours.status.publish` message created, read from the store, never the raw JSON. */
|
|
22838
|
+
"GET /api/statuses/by-wire/:wireId": async ({ deps, params }) => {
|
|
22839
|
+
const service = statusService(deps);
|
|
22840
|
+
const ingested = service.store.ingested(params.wireId);
|
|
22841
|
+
if (!ingested) throw new HttpError(404, "no status for this message");
|
|
22842
|
+
if (!ingested.outcome.ok) return { error: { code: ingested.outcome.code, message: ingested.outcome.message } };
|
|
22843
|
+
const status = service.store.get(ingested.outcome.status_id);
|
|
22844
|
+
if (!status) throw new HttpError(404, "status not found");
|
|
22845
|
+
return { status: publicStatus(status) };
|
|
22846
|
+
},
|
|
22847
|
+
"POST /api/statuses/:statusId/answer": async ({ deps, params, body }) => {
|
|
22848
|
+
const allowed = ["expectedRevision", "submissionId", "selection", "text", "surface"];
|
|
22849
|
+
const extra = Object.keys(body).filter((key) => !allowed.includes(key));
|
|
22850
|
+
if (extra.length) throw bad(`unexpected answer field ${extra[0]}`);
|
|
22851
|
+
if (body.surface !== void 0 && body.surface !== "feed" && body.surface !== "session") throw bad("surface must be feed or session");
|
|
22852
|
+
if (body.selection !== void 0 && (!Array.isArray(body.selection) || body.selection.some((id) => typeof id !== "string"))) throw bad("selection must be a list of option IDs");
|
|
22853
|
+
if (body.text !== void 0 && typeof body.text !== "string") throw bad("text must be a string");
|
|
22854
|
+
try {
|
|
22855
|
+
const { status } = await statusService(deps).answer(params.statusId, {
|
|
22856
|
+
expectedRevision: body.expectedRevision,
|
|
22857
|
+
submissionId: body.submissionId,
|
|
22858
|
+
...body.selection === void 0 ? {} : { selection: body.selection },
|
|
22859
|
+
...body.text === void 0 ? {} : { text: body.text },
|
|
22860
|
+
...body.surface === void 0 ? {} : { surface: body.surface }
|
|
22861
|
+
});
|
|
22862
|
+
return { status: publicStatus(status) };
|
|
22863
|
+
} catch (error) {
|
|
22864
|
+
throw statusHttpError(error);
|
|
22865
|
+
}
|
|
22866
|
+
},
|
|
22867
|
+
/** The Owner's manual Try again after `not_delivered`. */
|
|
22868
|
+
"POST /api/statuses/:statusId/answer/deliver": async ({ deps, params }) => {
|
|
22869
|
+
try {
|
|
22870
|
+
return { status: publicStatus(await statusService(deps).retry(params.statusId)) };
|
|
22871
|
+
} catch (error) {
|
|
22872
|
+
throw statusHttpError(error);
|
|
22873
|
+
}
|
|
22874
|
+
},
|
|
22875
|
+
/** The Owner displayed this revision as the current feed card or its chat card came on screen. */
|
|
22876
|
+
"POST /api/statuses/:statusId/seen": async ({ deps, params, body }) => {
|
|
22877
|
+
if (Object.keys(body).some((key) => key !== "revision") || !Number.isSafeInteger(body.revision)) throw bad("expected { revision }");
|
|
22878
|
+
try {
|
|
22879
|
+
const store = statusService(deps).store;
|
|
22880
|
+
if (!store.get(params.statusId)) throw new HttpError(404, "status not found");
|
|
22881
|
+
return { status: publicStatus(store.markSeen(params.statusId, body.revision)) };
|
|
22882
|
+
} catch (error) {
|
|
22883
|
+
throw statusHttpError(error);
|
|
22884
|
+
}
|
|
22885
|
+
},
|
|
21974
22886
|
"POST /api/commands/send": async ({ client, deps, body }) => {
|
|
21975
22887
|
if (deps.config.typedCommands === false) throw new HttpError(404, "Typed commands are disabled");
|
|
21976
22888
|
const peer = await resolveContact(client, str(body, "contact"));
|
|
@@ -22214,7 +23126,7 @@ var ROUTES = {
|
|
|
22214
23126
|
const contactDeadline = Date.now() + 1e4;
|
|
22215
23127
|
while (!(await client.listContacts()).contacts.some((contact) => contact.container_id.toUpperCase() === serverCid)) {
|
|
22216
23128
|
if (Date.now() >= contactDeadline) throw bad("Enrollment contact is not ready; obtain a fresh setup payload before retrying");
|
|
22217
|
-
await new Promise((
|
|
23129
|
+
await new Promise((resolve5) => setTimeout(resolve5, 100));
|
|
22218
23130
|
}
|
|
22219
23131
|
const argumentsValue = { type: "ours.app.bind-workspace.v1", accountId: String(challenge.accountId), workspaceId: String(challenge.workspaceId), nonce: String(challenge.nonce), hostWorkspaceId: String(body.hostWorkspaceId) };
|
|
22220
23132
|
const outcome = await client.sendCommand({ contact: serverCid, command: "bind-workspace", arguments: argumentsValue });
|
|
@@ -22457,7 +23369,7 @@ async function serveApi(req, res, deps) {
|
|
|
22457
23369
|
const [connectionId, viewId, epoch, baselineId] = resourceHeaders.map((values) => values[0]);
|
|
22458
23370
|
const baseline = await resourceService(deps).bound(connectionId, viewId, Number(epoch), baselineId);
|
|
22459
23371
|
const descriptor = baseline.descriptor;
|
|
22460
|
-
const route = descriptor.addressing === "cid" ? descriptor.resource === "files" ? "GET /api/peers/:cid/files" : "GET /api/peers/:cid/page" : descriptor.resource === "contacts" ? "GET /api/contacts" : descriptor.resource === "activity" ? "GET /api/activity" : descriptor.resource === "identity" ? "GET /api/identity" : descriptor.resource === "commands" ? "GET /api/contacts/:contact/commands" : descriptor.resource === "files" ? "GET /api/conversations/:contact/files" : "GET /api/conversations/:contact/page";
|
|
23372
|
+
const route = descriptor.addressing === "cid" ? descriptor.resource === "files" ? "GET /api/peers/:cid/files" : "GET /api/peers/:cid/page" : descriptor.resource === "contacts" ? "GET /api/contacts" : descriptor.resource === "activity" ? "GET /api/activity" : descriptor.resource === "statuses" ? "GET /api/statuses" : descriptor.resource === "identity" ? "GET /api/identity" : descriptor.resource === "commands" ? "GET /api/contacts/:contact/commands" : descriptor.resource === "files" ? "GET /api/conversations/:contact/files" : "GET /api/conversations/:contact/page";
|
|
22461
23373
|
const allowedQuery = descriptor.resource === "messages" && [...url.searchParams.keys()].every((key) => key === "limit") && (!url.searchParams.has("limit") || url.searchParams.getAll("limit").length === 1 && Number(url.searchParams.get("limit")) === descriptor.window.limit);
|
|
22462
23374
|
if (hit.key !== route || descriptor.entityId !== void 0 && descriptor.entityId !== (hit.params.cid ?? hit.params.contact) || url.searchParams.size > 0 && !allowedQuery) throw new ResourceBindingError(409, "resource read descriptor mismatch");
|
|
22463
23375
|
res.setHeader("X-Resource-Connection", connectionId);
|
|
@@ -22503,12 +23415,12 @@ function isOursError(error) {
|
|
|
22503
23415
|
|
|
22504
23416
|
// src/daemon.ts
|
|
22505
23417
|
init_define_MESSENGER_BUILD_INFO();
|
|
22506
|
-
import { randomBytes as
|
|
23418
|
+
import { randomBytes as randomBytes3 } from "node:crypto";
|
|
22507
23419
|
|
|
22508
23420
|
// node_modules/@ours.network/sdk/dist/index.js
|
|
22509
23421
|
init_define_MESSENGER_BUILD_INFO();
|
|
22510
23422
|
|
|
22511
|
-
// node_modules/@ours.network/sdk/dist/chunk-
|
|
23423
|
+
// node_modules/@ours.network/sdk/dist/chunk-JGK6W4GI.js
|
|
22512
23424
|
init_define_MESSENGER_BUILD_INFO();
|
|
22513
23425
|
|
|
22514
23426
|
// node_modules/@ours.network/sdk/dist/chunk-GPUVPRIY.js
|
|
@@ -22616,9 +23528,9 @@ var L = 100 * 1024 * 1024;
|
|
|
22616
23528
|
var K = { brokerUrl: "wss://broker1.ours.network", port: 3050, stateDir: E(T(), ".ours"), gcIntervalMs: 36e5, historyMaxBytes: L, apiVisibility: "owner", apiAuthMode: "legacy" };
|
|
22617
23529
|
var $2 = "daemon-token";
|
|
22618
23530
|
|
|
22619
|
-
// node_modules/@ours.network/sdk/dist/chunk-
|
|
23531
|
+
// node_modules/@ours.network/sdk/dist/chunk-JGK6W4GI.js
|
|
22620
23532
|
import { homedir as Te } from "node:os";
|
|
22621
|
-
import { isAbsolute as Oe, join as Se, resolve as
|
|
23533
|
+
import { isAbsolute as Oe, join as Se, resolve as pe } from "node:path";
|
|
22622
23534
|
import { randomBytes as W } from "node:crypto";
|
|
22623
23535
|
import { readFileSync as xe } from "node:fs";
|
|
22624
23536
|
import { homedir as Ne } from "node:os";
|
|
@@ -22643,7 +23555,7 @@ function w2(e2) {
|
|
|
22643
23555
|
if (t.username || t.password || t.hash) throw new Error("Daemon endpoint cannot contain credentials or fragment");
|
|
22644
23556
|
return t.origin + t.pathname.replace(/\/+$/, "") + t.search;
|
|
22645
23557
|
}
|
|
22646
|
-
function
|
|
23558
|
+
function u2(e2, t) {
|
|
22647
23559
|
if (!t.startsWith("/") || t.startsWith("//") || t.includes("#")) throw new Error("Invalid daemon route");
|
|
22648
23560
|
let n = new URL(e2), r = new URL(t, "http://daemon.invalid");
|
|
22649
23561
|
if (n.pathname = n.pathname.replace(/\/+$/, "") + r.pathname, r.search) {
|
|
@@ -22729,7 +23641,7 @@ var F = class {
|
|
|
22729
23641
|
this.leaseToken = t.leaseToken, this.clientPid = t.clientPid ?? process.pid, this.explicitApiToken = t.apiToken, this.credentialPath = t.credentialPath;
|
|
22730
23642
|
let n = t.fetch ?? globalThis.fetch;
|
|
22731
23643
|
this.fetchImpl = (r, i) => {
|
|
22732
|
-
let o = String(r) ===
|
|
23644
|
+
let o = String(r) === u2(this.base, "/api/v1/releaseLease"), s = [i?.signal, o ? t.requestSignal ? AbortSignal.timeout(5e3) : void 0 : t.requestSignal].filter((a) => a != null);
|
|
22733
23645
|
return n(r, { ...i, ...s.length ? { signal: AbortSignal.any(s) } : {} });
|
|
22734
23646
|
};
|
|
22735
23647
|
}
|
|
@@ -22740,7 +23652,7 @@ var F = class {
|
|
|
22740
23652
|
return { "x-ours-session-mode": this.sessionMode, "x-ours-lease-token": this.leaseToken, "x-ours-client-pid": String(this.clientPid), ...n ? { "x-ours-api-token": n } : {}, ...t };
|
|
22741
23653
|
}
|
|
22742
23654
|
async post(t, n, r = false) {
|
|
22743
|
-
let i = await this.fetchImpl(
|
|
23655
|
+
let i = await this.fetchImpl(u2(this.base, `/api/v1/${t}`), { redirect: "error", method: "POST", headers: this.headers({ "content-type": "application/json" }), body: JSON.stringify(n ?? {}), ...r ? { signal: AbortSignal.timeout(5e3) } : {} }), o;
|
|
22744
23656
|
try {
|
|
22745
23657
|
r ? o = await C(i) : o = await i.json();
|
|
22746
23658
|
} catch {
|
|
@@ -22759,7 +23671,7 @@ var F = class {
|
|
|
22759
23671
|
return o;
|
|
22760
23672
|
}
|
|
22761
23673
|
async get(t, n) {
|
|
22762
|
-
let r = await this.fetchImpl(
|
|
23674
|
+
let r = await this.fetchImpl(u2(this.base, t), { redirect: "error", headers: n ? this.headers() : {} }), i;
|
|
22763
23675
|
try {
|
|
22764
23676
|
i = await r.json();
|
|
22765
23677
|
} catch {
|
|
@@ -22770,7 +23682,7 @@ var F = class {
|
|
|
22770
23682
|
return i;
|
|
22771
23683
|
}
|
|
22772
23684
|
async resourcePosition(t, n) {
|
|
22773
|
-
let r = await this.fetchImpl(
|
|
23685
|
+
let r = await this.fetchImpl(u2(this.base, `/identities/${encodeURIComponent(t)}/resource-events?position=1`), { redirect: "error", headers: this.headers(), signal: n.signal });
|
|
22774
23686
|
if (!r.ok) throw new U(r.status);
|
|
22775
23687
|
let i = await C(r);
|
|
22776
23688
|
return le(i), i;
|
|
@@ -22790,7 +23702,7 @@ var F = class {
|
|
|
22790
23702
|
a(1e4);
|
|
22791
23703
|
let y2 = new URLSearchParams();
|
|
22792
23704
|
n.after !== void 0 && (y2.set("after", String(n.after)), y2.set("expectedGeneration", n.expectedGeneration));
|
|
22793
|
-
let h = await this.fetchImpl(
|
|
23705
|
+
let h = await this.fetchImpl(u2(this.base, `/identities/${encodeURIComponent(t)}/resource-events?${y2}`), { redirect: "error", headers: this.headers({ accept: "text/event-stream" }), signal: i });
|
|
22794
23706
|
if (i.aborted) throw h.body?.cancel(), i.reason;
|
|
22795
23707
|
if (!h.ok) throw new U(h.status);
|
|
22796
23708
|
if (!h.body || !h.headers.get("content-type")?.startsWith("text/event-stream")) throw new Error("Invalid resource stream response");
|
|
@@ -22806,11 +23718,11 @@ var F = class {
|
|
|
22806
23718
|
if (!N) break;
|
|
22807
23719
|
let j = v2.slice(0, N.index);
|
|
22808
23720
|
if (v2 = v2.slice(N.index + N[0].length), b2 -= Buffer.byteLength(j) + Buffer.byteLength(N[0]), Buffer.byteLength(j) > 512 * 1024) throw new Error("Resource frame exceeds limit");
|
|
22809
|
-
let oe = j.split(/\r?\n/).filter((
|
|
23721
|
+
let oe = j.split(/\r?\n/).filter((P) => P.startsWith("data:")).map((P) => P.slice(5).trimStart()).join(`
|
|
22810
23722
|
`);
|
|
22811
23723
|
if (!oe) continue;
|
|
22812
23724
|
let R2 = JSON.parse(oe);
|
|
22813
|
-
if (c(), j.split(/\r?\n/).some((
|
|
23725
|
+
if (c(), j.split(/\r?\n/).some((P) => P === "event: auth_required")) throw new U(401);
|
|
22814
23726
|
le(R2);
|
|
22815
23727
|
let K2 = R2.kind;
|
|
22816
23728
|
if (!["ready", "committed", "coverage", "resync"].includes(K2)) throw new Error("Invalid resource frame kind");
|
|
@@ -22826,6 +23738,18 @@ var F = class {
|
|
|
22826
23738
|
clearTimeout(o), r.abort(), i.removeEventListener("abort", g), await m2(), l?.releaseLock();
|
|
22827
23739
|
}
|
|
22828
23740
|
}
|
|
23741
|
+
ensureSessionIdentity(t) {
|
|
23742
|
+
return this.post("ensureSessionIdentity", t);
|
|
23743
|
+
}
|
|
23744
|
+
renameIdentity(t) {
|
|
23745
|
+
return this.post("renameIdentity", t);
|
|
23746
|
+
}
|
|
23747
|
+
promoteIdentity() {
|
|
23748
|
+
return this.post("promoteIdentity", {});
|
|
23749
|
+
}
|
|
23750
|
+
listLocalSessions() {
|
|
23751
|
+
return this.post("listLocalSessions", {});
|
|
23752
|
+
}
|
|
22829
23753
|
createIdentity(t) {
|
|
22830
23754
|
return this.post("createIdentity", t);
|
|
22831
23755
|
}
|
|
@@ -23006,7 +23930,7 @@ var F = class {
|
|
|
23006
23930
|
return this.get("/history-storage", true);
|
|
23007
23931
|
}
|
|
23008
23932
|
async readNotificationPage(t, n = {}) {
|
|
23009
|
-
let r = "/identities/" + encodeURIComponent(t) + "/notifications", i = n.kinds?.length ? "&kinds=" + encodeURIComponent(n.kinds.join(",")) : "", o = n.requestTimeoutMs === void 0 ? n.signal : AbortSignal.any([...n.signal ? [n.signal] : [], AbortSignal.timeout(n.requestTimeoutMs)]), s = await this.fetchImpl(
|
|
23933
|
+
let r = "/identities/" + encodeURIComponent(t) + "/notifications", i = n.kinds?.length ? "&kinds=" + encodeURIComponent(n.kinds.join(",")) : "", o = n.requestTimeoutMs === void 0 ? n.signal : AbortSignal.any([...n.signal ? [n.signal] : [], AbortSignal.timeout(n.requestTimeoutMs)]), s = await this.fetchImpl(u2(this.base, r + "?since=" + encodeURIComponent(String(n.since ?? "tip")) + i), { redirect: "error", headers: this.headers(), signal: o }), a;
|
|
23010
23934
|
try {
|
|
23011
23935
|
a = await s.json();
|
|
23012
23936
|
} catch {
|
|
@@ -23023,7 +23947,7 @@ var F = class {
|
|
|
23023
23947
|
for (; !n.signal?.aborted; ) {
|
|
23024
23948
|
let s;
|
|
23025
23949
|
try {
|
|
23026
|
-
let a = await this.fetchImpl(
|
|
23950
|
+
let a = await this.fetchImpl(u2(this.base, `${i}?since=${r}${o}`), { redirect: "error", headers: this.headers(), signal: n.requestTimeoutMs === void 0 ? n.signal : AbortSignal.any([...n.signal ? [n.signal] : [], AbortSignal.timeout(n.requestTimeoutMs)]) });
|
|
23027
23951
|
try {
|
|
23028
23952
|
s = await a.json();
|
|
23029
23953
|
} catch {
|
|
@@ -23039,7 +23963,7 @@ var F = class {
|
|
|
23039
23963
|
}
|
|
23040
23964
|
}
|
|
23041
23965
|
async fetchFile(t) {
|
|
23042
|
-
let n = await this.fetchImpl(
|
|
23966
|
+
let n = await this.fetchImpl(u2(this.base, `/files/${encodeURIComponent(t)}`), { redirect: "error", headers: this.headers() });
|
|
23043
23967
|
if (!n.ok) {
|
|
23044
23968
|
let r = `HTTP ${n.status}`;
|
|
23045
23969
|
try {
|
|
@@ -23052,7 +23976,7 @@ var F = class {
|
|
|
23052
23976
|
return new Uint8Array(await n.arrayBuffer());
|
|
23053
23977
|
}
|
|
23054
23978
|
async openFile(t) {
|
|
23055
|
-
let n = await this.fetchImpl(
|
|
23979
|
+
let n = await this.fetchImpl(u2(this.base, `/files/${encodeURIComponent(t)}`), { redirect: "error", headers: this.headers() });
|
|
23056
23980
|
if (!n.ok) {
|
|
23057
23981
|
let r = `HTTP ${n.status}`;
|
|
23058
23982
|
try {
|
|
@@ -23068,7 +23992,7 @@ var F = class {
|
|
|
23068
23992
|
async uploadFile(t, n) {
|
|
23069
23993
|
let r = t instanceof Uint8Array ? t.byteLength : n.size;
|
|
23070
23994
|
if (r === void 0) throw new Error("uploadFile: `size` is required when the body is a stream (the route needs Content-Length)");
|
|
23071
|
-
let i = await this.fetchImpl(
|
|
23995
|
+
let i = await this.fetchImpl(u2(this.base, "/files/upload"), { redirect: "error", method: "POST", headers: { ...this.headers(), "x-ours-filename": encodeURIComponent(n.filename), "Content-Type": n.mime || "application/octet-stream", "Content-Length": String(r) }, body: t, ...t instanceof Uint8Array ? {} : { duplex: "half" } });
|
|
23072
23996
|
if (!i.ok) {
|
|
23073
23997
|
let o = `HTTP ${i.status}`;
|
|
23074
23998
|
try {
|
|
@@ -23101,7 +24025,7 @@ var x = class extends Error {
|
|
|
23101
24025
|
function Ae(e2 = process.env) {
|
|
23102
24026
|
if (e2.OURS_CONFIG !== void 0) {
|
|
23103
24027
|
if (!e2.OURS_CONFIG.trim()) throw new x("OURS_CONFIG must name a client profile");
|
|
23104
|
-
return
|
|
24028
|
+
return pe(e2.OURS_CONFIG);
|
|
23105
24029
|
}
|
|
23106
24030
|
return Se(e2.HOME || Te(), ".ours-client", "profile.json");
|
|
23107
24031
|
}
|
|
@@ -23125,9 +24049,9 @@ function Re(e2) {
|
|
|
23125
24049
|
} catch {
|
|
23126
24050
|
return t("endpoint must equal serverUrl/daemon");
|
|
23127
24051
|
}
|
|
23128
|
-
return typeof n.expectedInstanceId != "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(n.expectedInstanceId) ? t("expectedInstanceId must be a lowercase UUID") : typeof n.credentialPath != "string" || !Oe(n.credentialPath) ||
|
|
24052
|
+
return typeof n.expectedInstanceId != "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(n.expectedInstanceId) ? t("expectedInstanceId must be a lowercase UUID") : typeof n.credentialPath != "string" || !Oe(n.credentialPath) || pe(n.credentialPath) !== n.credentialPath ? t("credentialPath must be an absolute normalized path") : Object.freeze({ serverUrl: r, endpoint: i, expectedInstanceId: n.expectedInstanceId, credentialPath: n.credentialPath });
|
|
23129
24053
|
}
|
|
23130
|
-
function
|
|
24054
|
+
function ue(e2 = process.env) {
|
|
23131
24055
|
let t = Ae(e2), n;
|
|
23132
24056
|
try {
|
|
23133
24057
|
n = JSON.parse(m(t).toString("utf8"));
|
|
@@ -23138,14 +24062,14 @@ function pe(e2 = process.env) {
|
|
|
23138
24062
|
if (["OURS_PORT", "OURS_STATE_DIR", "OURS_API_TOKEN", "OURS_DAEMON_ID", "OURS_DAEMON_URL", "OURS_DAEMON_CREDENTIAL_PATH"].some((o) => e2[o]?.trim())) throw new x("remove legacy OURS_PORT/STATE_DIR/API_TOKEN/DAEMON_ID/DAEMON_URL/DAEMON_CREDENTIAL_PATH environment selectors");
|
|
23139
24063
|
return Object.freeze({ ...r, configPath: t });
|
|
23140
24064
|
}
|
|
23141
|
-
var
|
|
24065
|
+
var p = class extends Error {
|
|
23142
24066
|
constructor(n, r) {
|
|
23143
24067
|
super(r);
|
|
23144
24068
|
this.code = n;
|
|
23145
24069
|
this.name = "DaemonSelectionError";
|
|
23146
24070
|
}
|
|
23147
24071
|
};
|
|
23148
|
-
var Y = class extends
|
|
24072
|
+
var Y = class extends p {
|
|
23149
24073
|
constructor(n, r, i = {}) {
|
|
23150
24074
|
super("DAEMON_UNAVAILABLE", `no ours daemon is running at ${D(n)} for state directory ${JSON.stringify(r)}. Install the daemon with \`npm install --global @ours.network/daemon\`, then start the shared daemon with \`ours-daemon start\` or install/start its per-user service through \`ours-daemon install-service\`. SDK applications attach to the shared daemon and do not start an embedded daemon.`);
|
|
23151
24075
|
this.endpoint = n;
|
|
@@ -23155,20 +24079,20 @@ var Y = class extends u2 {
|
|
|
23155
24079
|
};
|
|
23156
24080
|
var me = K.port;
|
|
23157
24081
|
var X = $2;
|
|
23158
|
-
var
|
|
23159
|
-
var
|
|
24082
|
+
var Pe = ".ours";
|
|
24083
|
+
var ke = ["explicit", "environment", "config-file"];
|
|
23160
24084
|
function De(e2 = {}) {
|
|
23161
24085
|
let t = e2.env ?? process.env;
|
|
23162
|
-
if (t.OURS_TLS_CERT !== void 0 || t.OURS_TLS_KEY !== void 0) throw new
|
|
23163
|
-
if (e2.endpoint !== void 0 && new URL(e2.endpoint).protocol !== "http:" && new URL(e2.endpoint).protocol !== "https:") throw new
|
|
24086
|
+
if (t.OURS_TLS_CERT !== void 0 || t.OURS_TLS_KEY !== void 0) throw new p("INCOHERENT_SELECTION", "Daemon TLS is not supported in V1; remove OURS_TLS_CERT/OURS_TLS_KEY and explicitly configure HTTP");
|
|
24087
|
+
if (e2.endpoint !== void 0 && new URL(e2.endpoint).protocol !== "http:" && new URL(e2.endpoint).protocol !== "https:") throw new p("INCOHERENT_SELECTION", "Client requires an HTTP or HTTPS daemon endpoint");
|
|
23164
24088
|
let n = e2.readTextFile ?? ((y2) => xe(y2, "utf8")), r = e2.homeDir ?? Ne(), i = M2(t, "OURS_INSTANCE");
|
|
23165
|
-
if (i !== void 0) throw new
|
|
24089
|
+
if (i !== void 0) throw new p("INCOHERENT_SELECTION", `OURS_INSTANCE=${JSON.stringify(i)} is set, but named daemon instances are not implemented. Select the daemon with an explicit endpoint/port option or with OURS_PORT, and unset OURS_INSTANCE.`);
|
|
23166
24090
|
if (e2.stateDir !== void 0 && e2.expectStateDir !== void 0) {
|
|
23167
24091
|
let y2 = H(e2.stateDir), h = H(e2.expectStateDir);
|
|
23168
|
-
if (y2 !== h) throw new
|
|
24092
|
+
if (y2 !== h) throw new p("INCOHERENT_SELECTION", `stateDir ${JSON.stringify(y2)} and expectStateDir ${JSON.stringify(h)} name different directories. The state directory decides which token is read; the expected one decides which daemon that token may be sent to. Reconcile them, or pass only one.`);
|
|
23169
24093
|
}
|
|
23170
|
-
let o = $e(e2.configPath, M2(t, "OURS_CONFIG")), s = o ? Ue(o.value, n) : {}, a = fe(e2.port, Fe(M2(t, "OURS_PORT")), s.port, me), c = fe(e2.stateDir ?? e2.expectStateDir, M2(t, "OURS_STATE_DIR"), s.stateDir, J(r,
|
|
23171
|
-
Ce({ endpointSelected: e2.endpoint !== void 0 || a.source !== "default", endpointSource: f.source, stateDirIntentional:
|
|
24094
|
+
let o = $e(e2.configPath, M2(t, "OURS_CONFIG")), s = o ? Ue(o.value, n) : {}, a = fe(e2.port, Fe(M2(t, "OURS_PORT")), s.port, me), c = fe(e2.stateDir ?? e2.expectStateDir, M2(t, "OURS_STATE_DIR"), s.stateDir, J(r, Pe)), l = { value: H(c.value), source: c.source }, f = e2.endpoint !== void 0 ? { value: w2(e2.endpoint), source: "explicit" } : { value: `http://127.0.0.1:${a.value}`, source: a.source }, m2 = M2(t, "OURS_API_TOKEN");
|
|
24095
|
+
Ce({ endpointSelected: e2.endpoint !== void 0 || a.source !== "default", endpointSource: f.source, stateDirIntentional: ke.includes(l.source), stateDirSource: l.source, hasExplicitToken: e2.token !== void 0 && e2.token !== "", hasEnvToken: m2 !== void 0, requireExplicitSelection: e2.requireExplicitSelection === true, portSource: a.source });
|
|
23172
24096
|
let g = Le(e2.token, m2, s, l, e2.readTextFile);
|
|
23173
24097
|
return { baseUrl: f, port: a, stateDir: l, expectStateDir: e2.expectStateDir !== void 0 ? H(e2.expectStateDir) : l.value, ...g ? { token: g } : {}, ...o ? { configPath: o } : {} };
|
|
23174
24098
|
}
|
|
@@ -23182,7 +24106,7 @@ function Ce(e2) {
|
|
|
23182
24106
|
if (e2.hasExplicitToken && !e2.stateDirIntentional) throw $3("an explicit token was given, but the state directory is the built-in default, so there would be nothing to assert the daemon against before the token is sent. Pass expectStateDir (or stateDir) naming the state directory that token belongs to.");
|
|
23183
24107
|
}
|
|
23184
24108
|
function $3(e2) {
|
|
23185
|
-
return new
|
|
24109
|
+
return new p("INCOHERENT_SELECTION", e2);
|
|
23186
24110
|
}
|
|
23187
24111
|
function Le(e2, t, n, r, i) {
|
|
23188
24112
|
if (e2 !== void 0 && e2 !== "") return { value: e2, source: "explicit" };
|
|
@@ -23204,33 +24128,33 @@ function Ue(e2, t) {
|
|
|
23204
24128
|
try {
|
|
23205
24129
|
n = t(e2);
|
|
23206
24130
|
} catch {
|
|
23207
|
-
throw new
|
|
24131
|
+
throw new p("CONFIG_UNREADABLE", `the daemon config file ${JSON.stringify(e2)} could not be read.`);
|
|
23208
24132
|
}
|
|
23209
24133
|
let r;
|
|
23210
24134
|
try {
|
|
23211
24135
|
r = JSON.parse(n);
|
|
23212
24136
|
} catch {
|
|
23213
|
-
throw new
|
|
24137
|
+
throw new p("CONFIG_INVALID", `the daemon config file ${JSON.stringify(e2)} is not valid JSON.`);
|
|
23214
24138
|
}
|
|
23215
|
-
if (r === null || typeof r != "object" || Array.isArray(r)) throw new
|
|
24139
|
+
if (r === null || typeof r != "object" || Array.isArray(r)) throw new p("CONFIG_INVALID", `the daemon config file ${JSON.stringify(e2)} is not a JSON object.`);
|
|
23216
24140
|
let i = r, o = {}, s = i.port;
|
|
23217
24141
|
if (s !== void 0) {
|
|
23218
|
-
if (typeof s != "number" || !Number.isInteger(s) || s < 1 || s > 65535) throw new
|
|
24142
|
+
if (typeof s != "number" || !Number.isInteger(s) || s < 1 || s > 65535) throw new p("CONFIG_INVALID", `the daemon config file ${JSON.stringify(e2)} declares an invalid port; expected an integer 1-65535.`);
|
|
23219
24143
|
o.port = s;
|
|
23220
24144
|
}
|
|
23221
24145
|
let a = i.stateDir;
|
|
23222
24146
|
if (a !== void 0) {
|
|
23223
|
-
if (typeof a != "string" || a.trim() === "") throw new
|
|
24147
|
+
if (typeof a != "string" || a.trim() === "") throw new p("CONFIG_INVALID", `the daemon config file ${JSON.stringify(e2)} declares an invalid stateDir; expected a non-empty string.`);
|
|
23224
24148
|
o.stateDir = a;
|
|
23225
24149
|
}
|
|
23226
24150
|
let c = i.apiToken;
|
|
23227
24151
|
if (c !== void 0) {
|
|
23228
|
-
if (typeof c != "string" || c.trim() === "") throw new
|
|
24152
|
+
if (typeof c != "string" || c.trim() === "") throw new p("CONFIG_INVALID", `the daemon config file ${JSON.stringify(e2)} declares an invalid apiToken; expected a non-empty string.`);
|
|
23229
24153
|
o.apiToken = c;
|
|
23230
24154
|
}
|
|
23231
24155
|
let l = i.apiVisibility;
|
|
23232
24156
|
if (l !== void 0) {
|
|
23233
|
-
if (l !== "owner" && l !== "shared" && l !== "open") throw new
|
|
24157
|
+
if (l !== "owner" && l !== "shared" && l !== "open") throw new p("CONFIG_INVALID", `the daemon config file ${JSON.stringify(e2)} declares an unknown apiVisibility ${JSON.stringify(l)}; expected "owner", "shared" or "open".`);
|
|
23234
24158
|
o.apiVisibility = l;
|
|
23235
24159
|
}
|
|
23236
24160
|
return o;
|
|
@@ -23244,7 +24168,7 @@ function M2(e2, t) {
|
|
|
23244
24168
|
function Fe(e2) {
|
|
23245
24169
|
if (e2 === void 0) return;
|
|
23246
24170
|
let t = Number.parseInt(e2, 10);
|
|
23247
|
-
if (!Number.isInteger(t) || t < 1 || t > 65535) throw new
|
|
24171
|
+
if (!Number.isInteger(t) || t < 1 || t > 65535) throw new p("INCOHERENT_SELECTION", `OURS_PORT=${JSON.stringify(e2)} is not a TCP port between 1 and 65535.`);
|
|
23248
24172
|
return t;
|
|
23249
24173
|
}
|
|
23250
24174
|
function fe(e2, t, n, r) {
|
|
@@ -23257,21 +24181,21 @@ function $e(e2, t) {
|
|
|
23257
24181
|
async function Me(e2, t = {}) {
|
|
23258
24182
|
let n = t.fetch ?? globalThis.fetch, r = new AbortController(), i = setTimeout(() => r.abort(), t.timeoutMs ?? 5e3), o;
|
|
23259
24183
|
try {
|
|
23260
|
-
let a = await n(
|
|
23261
|
-
if (!a.ok) throw new
|
|
24184
|
+
let a = await n(u2(e2.baseUrl.value, "/state-dir"), { signal: r.signal, redirect: "error" });
|
|
24185
|
+
if (!a.ok) throw new p("INCOHERENT_SELECTION", `${D(u2(e2.baseUrl.value, "/state-dir"))} answered HTTP ${a.status}, so the daemon at that address could not be identified. Refusing to send a credential to it.`);
|
|
23262
24186
|
o = await a.json();
|
|
23263
24187
|
} catch (a) {
|
|
23264
|
-
throw a instanceof
|
|
24188
|
+
throw a instanceof p ? a : new Y(e2.baseUrl.value, e2.expectStateDir, { cause: a });
|
|
23265
24189
|
} finally {
|
|
23266
24190
|
clearTimeout(i);
|
|
23267
24191
|
}
|
|
23268
24192
|
let s = typeof o.stateDir == "string" ? H(o.stateDir) : null;
|
|
23269
|
-
if (s === null) throw new
|
|
23270
|
-
if (s !== e2.expectStateDir) throw new
|
|
24193
|
+
if (s === null) throw new p("INCOHERENT_SELECTION", `${D(u2(e2.baseUrl.value, "/state-dir"))} did not report a state directory, so this is not an ours daemon or not one this client understands. Refusing to send a credential to it.`);
|
|
24194
|
+
if (s !== e2.expectStateDir) throw new p("INCOHERENT_SELECTION", `the daemon at ${D(e2.baseUrl.value)} owns state directory ${JSON.stringify(s)}, but this selection expects ${JSON.stringify(e2.expectStateDir)}. The token belongs to the expected directory, so it is NOT being sent. Point the endpoint and the state directory at the same daemon.`);
|
|
23271
24195
|
}
|
|
23272
24196
|
async function Q(e2 = {}) {
|
|
23273
24197
|
if (e2.endpoint === void 0 && e2.port === void 0 && e2.stateDir === void 0 && e2.expectStateDir === void 0) {
|
|
23274
|
-
let g =
|
|
24198
|
+
let g = ue({ ...e2.env ?? process.env, ...e2.configPath === void 0 ? {} : { OURS_CONFIG: e2.configPath } });
|
|
23275
24199
|
return Q({ ...e2, endpoint: g.endpoint, expectedInstanceId: g.expectedInstanceId, credentialPath: g.credentialPath, sessionMode: "external", leaseToken: e2.leaseToken ?? W(32).toString("hex"), env: {} });
|
|
23276
24200
|
}
|
|
23277
24201
|
if ("serverCertificate" in e2 && e2.serverCertificate !== void 0) throw new Error("Custom serverCertificate is not supported; HTTPS uses Node certificate trust, including NODE_EXTRA_CA_CERTS");
|
|
@@ -23296,7 +24220,7 @@ async function Q(e2 = {}) {
|
|
|
23296
24220
|
if (i === "external") T2.includes("external-sessions-v1") || T2.push("external-sessions-v1");
|
|
23297
24221
|
else if (T2.includes("external-sessions-v1")) throw new Error("External capabilities require explicit sessionMode: external; refusing local-mode fallback");
|
|
23298
24222
|
{
|
|
23299
|
-
let b2 = await globalThis.fetch(
|
|
24223
|
+
let b2 = await globalThis.fetch(u2(h, "/selection"), { signal: s ? AbortSignal.any([s, AbortSignal.timeout(5e3)]) : AbortSignal.timeout(5e3), redirect: "error" }), _ = await C(b2);
|
|
23300
24224
|
if (!b2.ok || !_ || Object.keys(_).length !== 3 || Object.keys(_).some((O2) => !["schema", "instanceId", "capabilities"].includes(O2)) || _.schema !== 1 || _.instanceId !== a) throw new Error("Daemon instance selection metadata is absent, incompatible or mismatched");
|
|
23301
24225
|
let A2 = _.capabilities;
|
|
23302
24226
|
if (!Array.isArray(A2) || A2.some((O2) => typeof O2 != "string") || T2.some((O2) => !A2.includes(O2))) throw new Error("Daemon does not support the required capabilities; refusing local-mode fallback");
|
|
@@ -23312,9 +24236,9 @@ async function Q(e2 = {}) {
|
|
|
23312
24236
|
|
|
23313
24237
|
// src/owner-session.ts
|
|
23314
24238
|
init_define_MESSENGER_BUILD_INFO();
|
|
23315
|
-
import { randomBytes } from "node:crypto";
|
|
24239
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
23316
24240
|
import * as fs from "node:fs";
|
|
23317
|
-
import { isAbsolute, join as
|
|
24241
|
+
import { isAbsolute, join as join5, resolve as resolve3, dirname as dirname3 } from "node:path";
|
|
23318
24242
|
import { spawnSync } from "node:child_process";
|
|
23319
24243
|
function stateExists(path2) {
|
|
23320
24244
|
try {
|
|
@@ -23330,18 +24254,18 @@ var OwnerSession = class _OwnerSession {
|
|
|
23330
24254
|
constructor(stateDir, selection) {
|
|
23331
24255
|
this.stateDir = stateDir;
|
|
23332
24256
|
this.selection = selection;
|
|
23333
|
-
this.path =
|
|
24257
|
+
this.path = join5(stateDir, "owner-session.json");
|
|
23334
24258
|
}
|
|
23335
24259
|
record;
|
|
23336
24260
|
path;
|
|
23337
24261
|
lockFd;
|
|
23338
24262
|
static async open(stateDir, selection, attach) {
|
|
23339
|
-
const saved = stateDir && stateExists(
|
|
24263
|
+
const saved = stateDir && stateExists(join5(stateDir, "owner-session.json"));
|
|
23340
24264
|
if (!selection || process.platform !== "linux") {
|
|
23341
24265
|
if (saved) throw new ConfigurationError("Saved messenger ownership requires its qualified V1 activation and original selection");
|
|
23342
24266
|
return void 0;
|
|
23343
24267
|
}
|
|
23344
|
-
if (!stateDir || !isAbsolute(stateDir) ||
|
|
24268
|
+
if (!stateDir || !isAbsolute(stateDir) || resolve3(stateDir) !== stateDir) {
|
|
23345
24269
|
throw new ConfigurationError("Messenger ownership requires an absolute private state directory");
|
|
23346
24270
|
}
|
|
23347
24271
|
const capability = spawnSync("flock", ["--version"], { stdio: "ignore", timeout: 5e3 });
|
|
@@ -23368,7 +24292,7 @@ var OwnerSession = class _OwnerSession {
|
|
|
23368
24292
|
}
|
|
23369
24293
|
session.record = {
|
|
23370
24294
|
version: 1,
|
|
23371
|
-
ownerInstanceId: "messenger-" +
|
|
24295
|
+
ownerInstanceId: "messenger-" + randomBytes2(24).toString("hex"),
|
|
23372
24296
|
selection: { ...selection },
|
|
23373
24297
|
phase: "active"
|
|
23374
24298
|
};
|
|
@@ -23443,7 +24367,7 @@ var OwnerSession = class _OwnerSession {
|
|
|
23443
24367
|
}
|
|
23444
24368
|
fs.mkdirSync(this.stateDir, { recursive: true, mode: 448 });
|
|
23445
24369
|
this.privateStat(this.stateDir, true);
|
|
23446
|
-
const path2 =
|
|
24370
|
+
const path2 = join5(this.stateDir, "owner-session.lock");
|
|
23447
24371
|
this.lockFd = fs.openSync(path2, fs.constants.O_CREAT | fs.constants.O_RDWR | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK, 384);
|
|
23448
24372
|
const st2 = this.privateStat(path2);
|
|
23449
24373
|
const opened = fs.fstatSync(this.lockFd);
|
|
@@ -23481,7 +24405,7 @@ var OwnerSession = class _OwnerSession {
|
|
|
23481
24405
|
}
|
|
23482
24406
|
write() {
|
|
23483
24407
|
if (stateExists(this.path)) this.privateStat(this.path);
|
|
23484
|
-
const temporary = this.path + "." +
|
|
24408
|
+
const temporary = this.path + "." + randomBytes2(12).toString("hex") + ".tmp";
|
|
23485
24409
|
let fd;
|
|
23486
24410
|
try {
|
|
23487
24411
|
fd = fs.openSync(temporary, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY | fs.constants.O_NOFOLLOW, 384);
|
|
@@ -23540,7 +24464,7 @@ async function startRuntime(cfg, buildInfo, attach = Q) {
|
|
|
23540
24464
|
throw new ConfigurationError("OURS_DAEMON_URL, OURS_DAEMON_ID and OURS_DAEMON_CREDENTIAL_PATH must be set together");
|
|
23541
24465
|
}
|
|
23542
24466
|
const owner = await OwnerSession.open(cfg.stateDir, selected ? { endpoint, expectedInstanceId, credentialPath, identity: cfg.identity } : void 0, attach);
|
|
23543
|
-
const leaseToken = owner?.ownerInstanceId ?? `messenger-${
|
|
24467
|
+
const leaseToken = owner?.ownerInstanceId ?? `messenger-${randomBytes3(24).toString("hex")}`;
|
|
23544
24468
|
let client;
|
|
23545
24469
|
let info;
|
|
23546
24470
|
try {
|
|
@@ -23608,9 +24532,9 @@ async function bindIdentity(runtime, cfg) {
|
|
|
23608
24532
|
// src/push.ts
|
|
23609
24533
|
init_define_MESSENGER_BUILD_INFO();
|
|
23610
24534
|
var import_web_push = __toESM(require_src2(), 1);
|
|
23611
|
-
import { createHash as
|
|
23612
|
-
import { chmodSync as chmodSync2, lstatSync as lstatSync4, mkdirSync as
|
|
23613
|
-
import { dirname as dirname4, join as
|
|
24535
|
+
import { createHash as createHash5, randomUUID as randomUUID3, timingSafeEqual } from "node:crypto";
|
|
24536
|
+
import { chmodSync as chmodSync2, lstatSync as lstatSync4, mkdirSync as mkdirSync7, readFileSync as readFileSync6, renameSync as renameSync6, writeFileSync as writeFileSync7 } from "node:fs";
|
|
24537
|
+
import { dirname as dirname4, join as join6 } from "node:path";
|
|
23614
24538
|
var MAX_BINDINGS = 32;
|
|
23615
24539
|
var MAX_ENDPOINT_LENGTH = 2048;
|
|
23616
24540
|
var MAX_LABEL_LENGTH = 160;
|
|
@@ -23635,7 +24559,7 @@ function nonEmpty3(value, max = Number.MAX_SAFE_INTEGER) {
|
|
|
23635
24559
|
return typeof value === "string" && value.length > 0 && value.length <= max;
|
|
23636
24560
|
}
|
|
23637
24561
|
function fingerprint(publicKey) {
|
|
23638
|
-
return
|
|
24562
|
+
return createHash5("sha256").update(publicKey).digest("base64url");
|
|
23639
24563
|
}
|
|
23640
24564
|
function base64urlBytes(value, length, field) {
|
|
23641
24565
|
if (!nonEmpty3(value, 256) || !/^[A-Za-z0-9_-]+$/.test(value)) {
|
|
@@ -23806,15 +24730,15 @@ var PushStore = class _PushStore {
|
|
|
23806
24730
|
const env = typeof identityCidOrEnv === "string" ? envOrDependencies : identityCidOrEnv;
|
|
23807
24731
|
const deps = typeof identityCidOrEnv === "string" ? dependencies : envOrDependencies;
|
|
23808
24732
|
if (!nonEmpty3(identityCid, 512)) throw new Error("push identity CID must be a non-empty bounded string");
|
|
23809
|
-
const file =
|
|
23810
|
-
|
|
24733
|
+
const file = join6(stateDir, "push.json");
|
|
24734
|
+
mkdirSync7(dirname4(file), { recursive: true, mode: 448 });
|
|
23811
24735
|
let parsed;
|
|
23812
24736
|
try {
|
|
23813
24737
|
const stat2 = lstatSync4(file);
|
|
23814
24738
|
if (!stat2.isFile() || stat2.isSymbolicLink()) throw preservedStateError(file, "not a safe regular file");
|
|
23815
24739
|
let value;
|
|
23816
24740
|
try {
|
|
23817
|
-
value = JSON.parse(
|
|
24741
|
+
value = JSON.parse(readFileSync6(file, "utf8"));
|
|
23818
24742
|
} catch (error) {
|
|
23819
24743
|
throw preservedStateError(file, `corrupt or unreadable (${error instanceof Error ? error.message : String(error)})`);
|
|
23820
24744
|
}
|
|
@@ -23913,9 +24837,9 @@ var PushStore = class _PushStore {
|
|
|
23913
24837
|
}
|
|
23914
24838
|
persist() {
|
|
23915
24839
|
const tmp = `${this.file}.tmp`;
|
|
23916
|
-
|
|
24840
|
+
writeFileSync7(tmp, JSON.stringify(this.state, null, 2), { mode: 384 });
|
|
23917
24841
|
chmodSync2(tmp, 384);
|
|
23918
|
-
|
|
24842
|
+
renameSync6(tmp, this.file);
|
|
23919
24843
|
chmodSync2(this.file, 384);
|
|
23920
24844
|
}
|
|
23921
24845
|
get publicKey() {
|
|
@@ -24444,7 +25368,7 @@ function attachPresenceServer(server, registry, options) {
|
|
|
24444
25368
|
clearInterval(pinger);
|
|
24445
25369
|
server.removeListener("upgrade", upgrade);
|
|
24446
25370
|
for (const socket of wss.clients) socket.terminate();
|
|
24447
|
-
await new Promise((
|
|
25371
|
+
await new Promise((resolve5) => wss.close(() => resolve5()));
|
|
24448
25372
|
}
|
|
24449
25373
|
};
|
|
24450
25374
|
}
|
|
@@ -24491,7 +25415,7 @@ async function redirectStaleEntryAsset(req, res, appDir, pathname, basePath = "/
|
|
|
24491
25415
|
const staleEntry = /^\/assets\/index-[A-Za-z0-9_-]+\.(js|css)$/.exec(pathname);
|
|
24492
25416
|
if (!staleEntry) return false;
|
|
24493
25417
|
try {
|
|
24494
|
-
const index = (await readContainedFile(appDir,
|
|
25418
|
+
const index = (await readContainedFile(appDir, resolve4(appDir, "index.html"))).toString("utf8");
|
|
24495
25419
|
const extension2 = staleEntry[1];
|
|
24496
25420
|
const currentEntry = new RegExp(
|
|
24497
25421
|
`(?:src|href)=["'](\\.?\\/assets\\/index-[A-Za-z0-9_-]+\\.${extension2})["']`
|
|
@@ -24534,8 +25458,8 @@ async function serveApp(req, res, appDir, basePath = "/") {
|
|
|
24534
25458
|
let assetRoot = appDir;
|
|
24535
25459
|
let cacheControl = "no-cache";
|
|
24536
25460
|
if (pathname.startsWith("/assets/")) {
|
|
24537
|
-
assetRoot =
|
|
24538
|
-
const candidate =
|
|
25461
|
+
assetRoot = resolve4(appDir, "assets");
|
|
25462
|
+
const candidate = resolve4(appDir, `.${decodedPathname}`);
|
|
24539
25463
|
if (candidate !== assetRoot && !candidate.startsWith(`${assetRoot}${sep}`)) {
|
|
24540
25464
|
appNotFound(res);
|
|
24541
25465
|
return;
|
|
@@ -24543,25 +25467,25 @@ async function serveApp(req, res, appDir, basePath = "/") {
|
|
|
24543
25467
|
asset = candidate;
|
|
24544
25468
|
cacheControl = "public, max-age=31536000, immutable";
|
|
24545
25469
|
} else if (pathname.startsWith("/icons/")) {
|
|
24546
|
-
assetRoot =
|
|
24547
|
-
const candidate =
|
|
25470
|
+
assetRoot = resolve4(appDir, "icons");
|
|
25471
|
+
const candidate = resolve4(appDir, `.${decodedPathname}`);
|
|
24548
25472
|
if (candidate === assetRoot || !candidate.startsWith(`${assetRoot}${sep}`)) {
|
|
24549
25473
|
appNotFound(res);
|
|
24550
25474
|
return;
|
|
24551
25475
|
}
|
|
24552
25476
|
asset = candidate;
|
|
24553
25477
|
} else if (pathname === "/manifest.webmanifest" || pathname === "/version.json" || pathname === "/sw.js" || pathname === "/icon.svg" || pathname === "/maskable-icon.svg") {
|
|
24554
|
-
asset =
|
|
25478
|
+
asset = resolve4(appDir, pathname.slice(1));
|
|
24555
25479
|
} else if (/\.[a-z0-9]+$/i.test(pathname)) {
|
|
24556
25480
|
appNotFound(res);
|
|
24557
25481
|
return;
|
|
24558
25482
|
} else {
|
|
24559
|
-
asset =
|
|
25483
|
+
asset = resolve4(appDir, "index.html");
|
|
24560
25484
|
}
|
|
24561
25485
|
try {
|
|
24562
25486
|
let body = await readContainedFile(assetRoot, asset);
|
|
24563
25487
|
const base = normalizeBasePath(basePath);
|
|
24564
|
-
if (asset ===
|
|
25488
|
+
if (asset === resolve4(appDir, "index.html")) body = Buffer.from(prefixDocument(body.toString("utf8"), base));
|
|
24565
25489
|
if (pathname === "/manifest.webmanifest" && base !== "/") {
|
|
24566
25490
|
const manifest = JSON.parse(body.toString("utf8"));
|
|
24567
25491
|
for (const key of ["id", "start_url", "scope"]) if (typeof manifest[key] === "string") manifest[key] = base + manifest[key].replace(/^\//, "");
|
|
@@ -24572,7 +25496,7 @@ async function serveApp(req, res, appDir, basePath = "/") {
|
|
|
24572
25496
|
res.writeHead(200, appHeaders(type, cacheControl, body.length));
|
|
24573
25497
|
res.end(req.method === "HEAD" ? void 0 : body);
|
|
24574
25498
|
} catch (error) {
|
|
24575
|
-
if (asset !==
|
|
25499
|
+
if (asset !== resolve4(appDir, "index.html")) {
|
|
24576
25500
|
if (await redirectStaleEntryAsset(req, res, appDir, decodedPathname, basePath)) return;
|
|
24577
25501
|
appNotFound(res);
|
|
24578
25502
|
return;
|
|
@@ -24726,6 +25650,8 @@ async function start(cfg, buildInfo, dependencies = DEFAULT_START_DEPENDENCIES)
|
|
|
24726
25650
|
let watcher;
|
|
24727
25651
|
let delivery;
|
|
24728
25652
|
let notificationOutbox;
|
|
25653
|
+
let statusTimer;
|
|
25654
|
+
let notificationDeliveryWithStatuses;
|
|
24729
25655
|
let events;
|
|
24730
25656
|
let http;
|
|
24731
25657
|
let startupProbe;
|
|
@@ -24742,6 +25668,7 @@ async function start(cfg, buildInfo, dependencies = DEFAULT_START_DEPENDENCIES)
|
|
|
24742
25668
|
startupProbe = void 0;
|
|
24743
25669
|
await watcher?.stop().catch((error) => reportFailure(log.warn, "watcher stop", error));
|
|
24744
25670
|
watcher = void 0;
|
|
25671
|
+
clearInterval(statusTimer);
|
|
24745
25672
|
await notificationOutbox?.close();
|
|
24746
25673
|
await delivery?.stop().catch((error) => reportFailure(log.warn, "push delivery stop", error));
|
|
24747
25674
|
delivery = void 0;
|
|
@@ -24778,8 +25705,25 @@ async function start(cfg, buildInfo, dependencies = DEFAULT_START_DEPENDENCIES)
|
|
|
24778
25705
|
const notificationConfig = producerConfig();
|
|
24779
25706
|
if (notificationConfig) notificationOutbox = new MessengerNotificationProducer(cfg.stateDir, notificationConfig, bound.cid, runtime.client, log.warn);
|
|
24780
25707
|
const notificationDelivery = notificationOutbox ?? delivery;
|
|
25708
|
+
let statuses;
|
|
25709
|
+
if (cfg.typedCommands !== false) {
|
|
25710
|
+
statuses = new StatusService(new MessengerStatusStore(cfg.stateDir, bound.cid), runtime.client, notificationOutbox?.outbox, log.warn);
|
|
25711
|
+
await statuses.start().catch((error) => reportFailure(log.warn, "status service start", error));
|
|
25712
|
+
const ingest = () => {
|
|
25713
|
+
void statuses.ingest().catch((error) => reportFailure(log.warn, "status ingest", error));
|
|
25714
|
+
};
|
|
25715
|
+
statusTimer = setInterval(() => {
|
|
25716
|
+
void statuses.recover().catch((error) => reportFailure(log.warn, "status recovery", error));
|
|
25717
|
+
}, 3e4);
|
|
25718
|
+
statusTimer.unref();
|
|
25719
|
+
const base = notificationDelivery;
|
|
25720
|
+
notificationDeliveryWithStatuses = { admit: (record, ...rest) => {
|
|
25721
|
+
if (record.event === "message_received") ingest();
|
|
25722
|
+
return base.admit(record, ...rest);
|
|
25723
|
+
} };
|
|
25724
|
+
}
|
|
24781
25725
|
watcher = startWatcher(runtime.client, cfg.identity, push, log, events, {
|
|
24782
|
-
delivery: notificationDelivery,
|
|
25726
|
+
delivery: notificationDeliveryWithStatuses ?? notificationDelivery,
|
|
24783
25727
|
readPage: runtime.readNotificationPage
|
|
24784
25728
|
});
|
|
24785
25729
|
const readyDeps = {
|
|
@@ -24795,15 +25739,16 @@ async function start(cfg, buildInfo, dependencies = DEFAULT_START_DEPENDENCIES)
|
|
|
24795
25739
|
}),
|
|
24796
25740
|
events,
|
|
24797
25741
|
identityCid: bound.cid,
|
|
24798
|
-
retireContactNotifications: notificationOutbox ? (cid) => notificationOutbox.retireContact(cid) : void 0
|
|
25742
|
+
retireContactNotifications: notificationOutbox ? (cid) => notificationOutbox.retireContact(cid) : void 0,
|
|
25743
|
+
...statuses ? { statuses } : {}
|
|
24799
25744
|
};
|
|
24800
25745
|
const moduleDir = dirname5(fileURLToPath(import.meta.url));
|
|
24801
25746
|
const appCandidates = [
|
|
24802
|
-
|
|
24803
|
-
|
|
24804
|
-
|
|
25747
|
+
resolve4(moduleDir, "../web"),
|
|
25748
|
+
resolve4(moduleDir, "../dist/web"),
|
|
25749
|
+
resolve4(moduleDir, "web")
|
|
24805
25750
|
];
|
|
24806
|
-
const appDir = process.env.OURS_MESSENGER_WEB_DIR ?? appCandidates.find((candidate) => existsSync3(
|
|
25751
|
+
const appDir = process.env.OURS_MESSENGER_WEB_DIR ?? appCandidates.find((candidate) => existsSync3(resolve4(candidate, "index.html")) && existsSync3(resolve4(candidate, "assets"))) ?? resolve4(moduleDir, "__messenger_web_not_built__");
|
|
24807
25752
|
http = createServer((req, res) => {
|
|
24808
25753
|
const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
|
|
24809
25754
|
let serving;
|