@ghostlytools/sdk 1.13.2 → 1.13.4

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.
@@ -93,8 +93,13 @@ export declare const FILE_LIMITS: {
93
93
  readonly maxUnfinishedIncoming: 256;
94
94
  /** Files one contact sends at once; accepted ones beyond wait their turn. */
95
95
  readonly maxActiveIncoming: 3;
96
- /** An offer nobody answered ends after this long. */
96
+ /**
97
+ * An offer nobody answered ends after this long. So does a file taken here and arriving (`active`, not paused) of which
98
+ * no byte came for this long while a session was open (`ChatFiles.sweep`).
99
+ */
97
100
  readonly offerTtlMs: number;
101
+ /** While a session is open, its files are swept (`ChatFiles.sweep`) this often. */
102
+ readonly sweepEveryMs: number;
98
103
  /**
99
104
  * No answer while something is outstanding: the sender offers again, which puts both sides back in step. Nothing
100
105
  * arriving for a file under way: the receiver says again where it stands.
@@ -171,6 +176,11 @@ export interface FileTransferRecord {
171
176
  * and its part there was deleted.
172
177
  */
173
178
  agreed?: boolean;
179
+ /**
180
+ * In: how long it went with no byte and no change of state while a session was open, as of when it was last kept
181
+ * (`ChatFiles.idleFor`). Time with no session does not count. Absent (an older record): none so far.
182
+ */
183
+ idleMs?: number;
174
184
  }
175
185
  export declare const transferEnded: (record: FileTransferRecord) => boolean;
176
186
  /**
@@ -346,6 +356,8 @@ export declare class ChatFiles {
346
356
  * every trial of a larger one (a fifth of the rate on a wavering path). Confirmed chunk by chunk, it is what each sends with.
347
357
  */
348
358
  private refill;
359
+ /** Sweeps while a session is open (`FILE_LIMITS.sweepEveryMs`). */
360
+ private sweeper?;
349
361
  constructor(host: ChatFilesHost);
350
362
  /** The floor of this chat's window: all of `minWindowBytes`, or its share of an uplink it shares (`FileUplink`). */
351
363
  private floor;
@@ -373,6 +385,15 @@ export declare class ChatFiles {
373
385
  sent(id: string): number;
374
386
  private moved;
375
387
  private changed;
388
+ /** An incoming file's idle count starts again: from now while a session is open, from the next one otherwise. */
389
+ private stirred;
390
+ /**
391
+ * How long an incoming file went with no byte and no change of state while a session was open: what its record kept,
392
+ * and this session's stretch. Time with no session (closed, the app gone, either side away) does not count.
393
+ */
394
+ private idleFor;
395
+ /** The idle time so far goes into the record, kept with it from now on; the stretch counted here starts again. */
396
+ private foldIdle;
376
397
  /**
377
398
  * Keeps `unended` to the entries of this chat not ended. Each change of a record's state is reported (`changed`),
378
399
  * so that is where a file that ended leaves it, and one taken or sent again comes back.
@@ -384,10 +405,14 @@ export declare class ChatFiles {
384
405
  attach(): void;
385
406
  /** The session went: nothing moves until the next one. What was received is made durable. */
386
407
  detach(): void;
387
- /**
388
- * Offers ended by their time to live. The host calls it now and then; `attach` does too. A file taken here and waiting
389
- * its turn ends too once nothing of it arrived in that time: its sender never sent it. Offered again, it is taken
390
- * again (`retakeAgreed`).
408
+ /** The app stops: no more sweeps. */
409
+ stop(): void;
410
+ /**
411
+ * Offers ended by their time to live. The host calls it now and then; `attach` does too, and it runs every
412
+ * `FILE_LIMITS.sweepEveryMs` while a session is open. A file taken here and waiting its turn ends too once nothing of
413
+ * it arrived in that time: its sender never sent it. Offered again, it is taken again (`retakeAgreed`). So does one
414
+ * arriving (`active`) that had no byte and no change of state for that long while a session was open (`idleFor`):
415
+ * paused there or here, or with no session, it waits as long as it takes (WISP 501 § Consent).
391
416
  */
392
417
  sweep(): void;
393
418
  private sayRoom;
@@ -149,7 +149,8 @@ export declare function openDidDhtPayload(did: string, payload: Uint8Array): Dec
149
149
  /**
150
150
  * Resolves a did:dht through Pkarr relays: one GET to each, all at once, and the newest packet that
151
151
  * checks out wins (the highest sequence number; on a tie, the relay listed first), so a relay holding
152
- * an older version cannot bring back a removed key or undo a deactivation. Each answer is bounded to
152
+ * an older version cannot bring back a removed key or undo a deactivation. It waits for every relay
153
+ * that answers within the fetch's timeout, not only the first. Each answer is bounded to
153
154
  * a BEP44 item, its signature checked against the DID's key and its records parsed strictly; a relay
154
155
  * that has nothing, fails or serves a packet that does not check out does not count. A deactivated DID
155
156
  * resolves (`metadata.deactivated`); everything else that goes wrong throws a `DidDhtError`.
@@ -25,6 +25,12 @@ export declare const GROUP_LIMITS: {
25
25
  /** Own messages kept for catch-up: count and total ciphertext bytes. */
26
26
  readonly outlog: 32;
27
27
  readonly outlogBytes: number;
28
+ /**
29
+ * Own messages past that log that members may not have taken (`GroupState.owed`): count and total ciphertext bytes.
30
+ * With the log, the 256 a member takes in one answer.
31
+ */
32
+ readonly owed: 224;
33
+ readonly owedBytes: number;
28
34
  /** Frames waiting for an epoch (or its secret) that has not arrived yet. */
29
35
  readonly waiting: 64;
30
36
  readonly waitingBytes: number;
@@ -302,6 +308,12 @@ export interface GroupState {
302
308
  seqEpoch: number;
303
309
  /** My own frames, newest last, for members who missed them. */
304
310
  sent: GroupMessageFrame[];
311
+ /**
312
+ * My own frames that fell out of `sent` though members may not have taken them (said past the pace they apply,
313
+ * `AuthorPace`), oldest first, until a sync of each other member of their epoch shows it holds them. At most
314
+ * `GROUP_LIMITS.owed` and `owedBytes`. Absent in states from before they were kept.
315
+ */
316
+ owed?: GroupMessageFrame[];
305
317
  /**
306
318
  * Other members' frames, in the order they arrived, for members who missed them. Absent in states from before revision
307
319
  * 0.9. With an app that keeps each frame with its message (`GroupSession`'s `onRows`), only the ones from before it
@@ -505,6 +517,14 @@ export declare class GroupSession {
505
517
  private namesTaken;
506
518
  /** Messages, and apart from them edits, taken per author (`AuthorPace`). In memory only. */
507
519
  private messagePace;
520
+ /**
521
+ * My own frames as members pace them (`OWN_BURST`), and those of mine in `sent` it did not take: one of them that falls
522
+ * out of `sent` goes to `owed`. Then, per frame of `owed`, the members whose sync showed they hold it. In memory only:
523
+ * after a start, each owed frame waits for a sync of every member.
524
+ */
525
+ private ownPace;
526
+ private overPace;
527
+ private owedHeld;
508
528
  private editPace;
509
529
  private queue;
510
530
  /** Metadata frames that name a commit or an epoch I do not have yet, one signed by the admin and one by anyone else (`waitMeta`): tried again when the chain moves. */
@@ -542,6 +562,12 @@ export declare class GroupSession {
542
562
  * word, so it never counts as seen. In memory only: the syncs come again when the edges do.
543
563
  */
544
564
  private heard;
565
+ /**
566
+ * Per author and epoch, the highest number of its own signed frames I did not take at its pace (`AuthorPace`): what
567
+ * `lacking` names, so the author is asked for it again (it keeps it, `GroupState.owed`). Every member refuses the
568
+ * same frames of a burst, all past the last one it took, so nothing else shows they are missing. In memory only.
569
+ */
570
+ private refused;
545
571
  /**
546
572
  * Per member: until when what comes over its edge may be its answer to my sync (`syncFrame`), a catch-up and not a
547
573
  * message written just now. Each frame of the answer keeps it open: it goes a slice at a time. In memory only.
@@ -644,6 +670,8 @@ export declare class GroupSession {
644
670
  * What a sync names in `miss` for one sender now: per epoch, the newest `GROUP_LIMITS.miss` numbers that never arrived.
645
671
  * And, for an epoch of which none arrived, the newest numbers another member said it has (`heard`): a member back
646
672
  * after someone joined, whose author wrote 32 since (all its own answer holds), had nothing below them to ask for.
673
+ * And, first, the oldest of those past the highest seen up to the highest of its frames I refused at its pace
674
+ * (`refused`): its answer brings them oldest first, so what is named changes as they come.
647
675
  */
648
676
  missOf(sender: string): Record<string, number[]>;
649
677
  /**
@@ -780,8 +808,11 @@ export declare class GroupSession {
780
808
  private nextSeq;
781
809
  /** A text sealed and signed as my frame `n` of `epoch`, with its boxes; `o`: where it was first said (`resealBehind`). */
782
810
  private seal;
783
- /** Into my bounded log, for members who missed it. */
811
+ /** Into my bounded log, for members who missed it; one said past the pace members apply goes on to `owed` when it falls out. */
784
812
  private logOwn;
813
+ private owe;
814
+ /** Drops from `owed` each frame every other member of its epoch has shown, in a sync, that it holds. */
815
+ private owedTaken;
785
816
  /**
786
817
  * My message `id` was deleted for everyone: its frame, and each copy said again, keep their place in my log (`nextSeq`,
787
818
  * `couldRead`, the removal's copies) and lose what they said. The log is in the saved state beside the epochs' secrets,
@@ -1026,7 +1057,7 @@ export declare class GroupSession {
1026
1057
  * opens).
1027
1058
  */
1028
1059
  private handOut;
1029
- /** My own messages a member's sync says it lacks, from my bounded log, for the epochs it was a member of. */
1060
+ /** My own messages a member's sync says it lacks, from my bounded log (and `owed`), for the epochs it was a member of. */
1030
1061
  private handOwn;
1031
1062
  private ownLacked;
1032
1063
  /** A frame of a message deleted for everyone (`hooks.removed`, or one of mine `forget` emptied): handed to nobody, its removal is what they get. */
@@ -26,8 +26,9 @@ export declare function sanitizeResponseHeaders(headers: HeaderList, target: Loc
26
26
  /**
27
27
  * The contact's headers a viewer does not pass on: each makes the browser send something to a place it names, outside
28
28
  * `connect-src` (violation and network-error reports, and the endpoints they go to; `Link` preloads, prefetches and
29
- * early connections). With Hide my IP from contacts on, that place would learn this device's address. The same list
30
- * as the CLI's `OPENED_SERVICE_DROPPED_HEADERS` and Desktop's `DROPPED_HEADERS`.
29
+ * early connections; `Speculation-Rules` prefetches and prerenders). With Hide my IP from contacts on, that place would
30
+ * learn this device's address. The same list as the CLI's `OPENED_SERVICE_DROPPED_HEADERS` and Desktop's
31
+ * `DROPPED_HEADERS`.
31
32
  */
32
33
  export declare const VIEWER_DROPPED_HEADERS: string[];
33
34
  /** The directives of a contact's policy that send reports to a URL it names, dropped from it (`OPENED_SERVICE_DROPPED_DIRECTIVES`). */
@@ -160,6 +160,11 @@ export interface SharedIdentity {
160
160
  account?: string;
161
161
  /** queued: the person chose to share, the contact is not connected yet. */
162
162
  status: "queued" | "pending" | "accepted" | "rejected" | "withdrawal-pending" | "withdrawn";
163
+ /**
164
+ * Shared again while the contact may still hold an earlier presentation of it (one not withdrawn): a stop before the
165
+ * new share went still tells the contact.
166
+ */
167
+ held?: true;
163
168
  /** Seconds. When the status last changed. */
164
169
  at: number;
165
170
  error?: string;
@@ -270,6 +275,11 @@ export declare class IdentityExchange {
270
275
  private requested;
271
276
  /** The nonces of the presentations in their provider's check now. */
272
277
  private checking;
278
+ /**
279
+ * The nonces of the challenges sent on this connection. A presentation is signed for its session, so a challenge
280
+ * from a closed link that is not in its check now can no longer be answered.
281
+ */
282
+ private issued;
273
283
  /** When the contact's presentations were checked with their provider (seconds), for `IDENTITY_MAX_CHECKS_PER_HOUR`. */
274
284
  private checks;
275
285
  /** When this side sent its recent frames (ms), for `IDENTITY_SEND_LIMIT`. Kept across connections, as the contact's count is. */
@@ -22,17 +22,20 @@ import type { HeaderList } from "./frames.js";
22
22
  * the same script, so it is the same worker; the page's revoke of the blob's URL drops the guard's own a minute later.
23
23
  * A `data:` worker, and a blob made in another window, in a worker or already revoked, run as they were. Once per
24
24
  * window, whichever guard runs first (`ghostlyWorkerGuard`, `CLIPBOARD_GUARD_SCRIPT` does the same).
25
+ * - takes out each `<script type="speculationrules">` as it is put in the page, a shadow tree the page makes included:
26
+ * Chromium would prefetch or prerender the pages it lists on a server the contact names, which no policy covers
27
+ * (`'unsafe-inline'` lets inline rules in); the `Speculation-Rules` header is not passed on (`VIEWER_DROPPED_HEADERS`).
25
28
  * It uses nothing the page can change after it ran (the page's own code runs later, in the same realm).
26
29
  *
27
30
  * What a script put in the page cannot do, so where the viewer does not run it per document this is not a guarantee:
28
31
  * a frame's window read by its index (`window[0]`, never through the frame element) while the frame's page is still
29
- * on its way, and a `srcdoc` frame inside a shadow tree written in the HTML the page itself sends, run before the
30
- * guard is there.
32
+ * on its way, and a `srcdoc` frame or speculation rules inside a shadow tree written in the HTML the page itself sends,
33
+ * run before the guard is there.
31
34
  * No backslash, `${` or backtick in it: Desktop's copy (`SERVICE_GUARD`, apps/desktop/src/viewer.rs) is the same text.
32
35
  */
33
- export declare const VIEWER_GUARD_SCRIPT = "(function noWebRtc(w) {\n \"use strict\";\n try {\n const apply = Reflect.apply;\n const own = \"<script>(\" + noWebRtc + \")(window)<\" + \"/script>\";\n for (const name of Object.getOwnPropertyNames(w)) {\n if (/^(webkit)?RTC/.test(name)) { try { delete w[name]; } catch (e) {} }\n }\n if (w.trustedTypes && !w.trustedTypes.defaultPolicy) {\n try {\n w.trustedTypes.createPolicy(\"default\", {\n createHTML: (input) => input,\n createScript: (input, type, sink) => (sink === \"Location href\" ? null : input),\n createScriptURL: (input) => input,\n });\n } catch (e) {}\n }\n const open = w.open;\n const opener = function (url, target) {\n apply(open, this, [url === undefined ? \"\" : url, target === undefined ? \"_blank\" : target, \"noopener\"]);\n return null;\n };\n w.open = opener;\n const describe = Object.getOwnPropertyDescriptor;\n const define = Object.defineProperty;\n const shut = (inner) => {\n try { if (inner && inner !== w && (\"RTCPeerConnection\" in inner || \"webkitRTCPeerConnection\" in inner)) noWebRtc(inner); } catch (e) {}\n };\n const count = describe(w, \"length\").get;\n const view = describe(w.Document.prototype, \"defaultView\").get;\n const slice = String.prototype.slice;\n const sweep = () => {\n try { for (let i = apply(count, w, []); i-- > 0;) shut(w[i]); } catch (e) {}\n };\n const listen = w.EventTarget.prototype.addEventListener;\n const home = w.document;\n const reopen = w.Document.prototype.open;\n w.Document.prototype.open = function () {\n if (arguments.length > 2) return apply(opener, w, [arguments[0], arguments[1]]);\n const got = apply(reopen, this, arguments);\n if (this === home) { try { apply(listen, home, [\"load\", sweep, true]); } catch (e) {} }\n return got;\n };\n const text = String;\n const lower = String.prototype.toLowerCase;\n const index = String.prototype.indexOf;\n const Refused = w.TypeError;\n const shadowed = (html) => apply(index, apply(lower, html, []), [\"shadowrootmode\"]) >= 0;\n const refuse = () => { throw new Refused(\"A declarative shadow root is not allowed here\"); };\n for (const [owner, name] of [[w.Element.prototype, \"setHTMLUnsafe\"], [w.ShadowRoot && w.ShadowRoot.prototype, \"setHTMLUnsafe\"], [w.Document, \"parseHTMLUnsafe\"]]) {\n const real = owner && owner[name];\n if (typeof real !== \"function\") continue;\n owner[name] = function (html) {\n const checked = text(html);\n if (shadowed(checked)) refuse();\n return apply(real, this, arguments.length > 1 ? [checked, arguments[1]] : [checked]);\n };\n }\n let tail = \"\";\n for (const name of [\"write\", \"writeln\"]) {\n const real = w.Document.prototype[name];\n if (typeof real !== \"function\") continue;\n w.Document.prototype[name] = function () {\n let checked = \"\";\n for (let i = 0; i < arguments.length; i++) checked += text(arguments[i]);\n if (shadowed(tail + checked)) refuse();\n tail = apply(slice, tail + checked, [-16]);\n return apply(real, this, [checked]);\n };\n }\n for (const kind of [\"HTMLIFrameElement\", \"HTMLFrameElement\", \"HTMLObjectElement\", \"HTMLEmbedElement\"]) {\n const proto = w[kind] && w[kind].prototype;\n for (const name of [\"contentWindow\", \"contentDocument\", \"getSVGDocument\"]) {\n const found = proto && describe(proto, name);\n const key = found && found.get ? \"get\" : \"value\";\n if (!found || typeof found[key] !== \"function\") continue;\n const read = found[key];\n found[key] = function () {\n const got = apply(read, this, arguments);\n try { shut(name === \"contentWindow\" ? got : apply(view, got, [])); } catch (e) {}\n return got;\n };\n try { define(proto, name, found); } catch (e) {}\n }\n }\n const { getAttribute, setAttribute, removeAttribute, attachShadow } = w.Element.prototype;\n const size = describe(w.NodeList.prototype, \"length\").get;\n const first = (frame) => {\n const doc = apply(getAttribute, frame, [\"srcdoc\"]);\n if (doc === null || apply(slice, doc, [0, own.length]) === own) return;\n try { apply(setAttribute, frame, [\"srcdoc\", own + doc]); } catch (e) { apply(removeAttribute, frame, [\"srcdoc\"]); }\n };\n const Observer = w.MutationObserver;\n const observe = Observer.prototype.observe;\n const watch = (root, all) => {\n const scan = () => {\n try {\n const frames = apply(all, root, [\"iframe[srcdoc]\"]);\n for (let i = apply(size, frames, []); i-- > 0;) first(frames[i]);\n } catch (e) {}\n sweep();\n };\n apply(observe, new Observer(scan), [root, { subtree: true, childList: true, attributes: true, attributeFilter: [\"srcdoc\"] }]);\n scan();\n return root;\n };\n const inShadow = w.DocumentFragment.prototype.querySelectorAll;\n if (attachShadow) {\n w.Element.prototype.attachShadow = function () {\n const root = apply(attachShadow, this, arguments);\n try { watch(root, inShadow); } catch (e) {}\n return root;\n };\n }\n if (w.trustedTypes && w.URL && w.Blob && !describe(w, \"ghostlyWorkerGuard\")) {\n try {\n define(w, \"ghostlyWorkerGuard\", { value: true });\n const construct = Reflect.construct;\n const json = JSON.stringify;\n const later = w.setTimeout;\n const Blob = w.Blob;\n const sized = describe(Blob.prototype, \"size\").get;\n const make = w.URL.createObjectURL;\n const revoke = w.URL.revokeObjectURL;\n const policy = \"if (self.trustedTypes && !self.trustedTypes.defaultPolicy) { try { self.trustedTypes.createPolicy('default', { createHTML: (s) => s, createScript: (s) => s, createScriptURL: (s) => s }); } catch (e) {} }\";\n const script = (code) => apply(make, null, [new Blob([code], { type: \"text/javascript\" })]);\n const known = { __proto__: null };\n let first = null;\n w.URL.createObjectURL = function createObjectURL(object) {\n const made = apply(make, this, arguments);\n try { apply(sized, object, []); known[made] = { blob: object, inner: null, classic: null, module: null }; } catch (e) {}\n return made;\n };\n w.URL.revokeObjectURL = function revokeObjectURL(url) {\n try {\n const key = text(url);\n const entry = known[key];\n if (entry) {\n delete known[key];\n const ours = [entry.inner, entry.classic, entry.module];\n apply(later, w, [() => { for (let i = 0; i < 3; i++) { if (ours[i] !== null) apply(revoke, null, [ours[i]]); } }, 60000]);\n }\n } catch (e) {}\n return apply(revoke, this, arguments);\n };\n const start = (url, options) => {\n const entry = known[text(url)];\n if (!entry) return url;\n const kind = options && typeof options === \"object\" && options.type === \"module\" ? \"module\" : \"classic\";\n if (entry[kind] === null) {\n if (entry.inner === null) entry.inner = apply(make, null, [entry.blob]);\n if (kind === \"module\" && first === null) first = script(policy);\n entry[kind] = script(kind === \"module\" ? \"import \" + json(first) + \"; import \" + json(entry.inner) + \";\" : policy + \" importScripts(\" + json(entry.inner) + \");\");\n }\n return entry[kind];\n };\n for (const name of [\"Worker\", \"SharedWorker\"]) {\n const Real = w[name];\n if (typeof Real !== \"function\") continue;\n const started = function (url) {\n if (new.target === undefined) return apply(Real, this, arguments);\n const args = [];\n for (let i = 0; i < arguments.length; i++) args[i] = arguments[i];\n if (args.length > 0) { try { args[0] = start(url, args[1]); } catch (e) {} }\n return construct(Real, args, new.target);\n };\n define(started, \"name\", { value: name });\n started.prototype = Real.prototype;\n define(Real.prototype, \"constructor\", { value: started, writable: true, enumerable: false, configurable: true });\n w[name] = started;\n }\n } catch (e) {}\n }\n apply(listen, home, [\"load\", sweep, true]);\n watch(home, w.Document.prototype.querySelectorAll);\n } catch (e) {}\n})(window)";
36
+ export declare const VIEWER_GUARD_SCRIPT = "(function noWebRtc(w) {\n \"use strict\";\n try {\n const apply = Reflect.apply;\n const own = \"<script>(\" + noWebRtc + \")(window)<\" + \"/script>\";\n for (const name of Object.getOwnPropertyNames(w)) {\n if (/^(webkit)?RTC/.test(name)) { try { delete w[name]; } catch (e) {} }\n }\n if (w.trustedTypes && !w.trustedTypes.defaultPolicy) {\n try {\n w.trustedTypes.createPolicy(\"default\", {\n createHTML: (input) => input,\n createScript: (input, type, sink) => (sink === \"Location href\" ? null : input),\n createScriptURL: (input) => input,\n });\n } catch (e) {}\n }\n const open = w.open;\n const opener = function (url, target) {\n apply(open, this, [url === undefined ? \"\" : url, target === undefined ? \"_blank\" : target, \"noopener\"]);\n return null;\n };\n w.open = opener;\n const describe = Object.getOwnPropertyDescriptor;\n const define = Object.defineProperty;\n const shut = (inner) => {\n try { if (inner && inner !== w && (\"RTCPeerConnection\" in inner || \"webkitRTCPeerConnection\" in inner)) noWebRtc(inner); } catch (e) {}\n };\n const count = describe(w, \"length\").get;\n const view = describe(w.Document.prototype, \"defaultView\").get;\n const slice = String.prototype.slice;\n const sweep = () => {\n try { for (let i = apply(count, w, []); i-- > 0;) shut(w[i]); } catch (e) {}\n };\n const listen = w.EventTarget.prototype.addEventListener;\n const home = w.document;\n const reopen = w.Document.prototype.open;\n w.Document.prototype.open = function () {\n if (arguments.length > 2) return apply(opener, w, [arguments[0], arguments[1]]);\n const got = apply(reopen, this, arguments);\n if (this === home) { try { apply(listen, home, [\"load\", sweep, true]); } catch (e) {} }\n return got;\n };\n const text = String;\n const lower = String.prototype.toLowerCase;\n const index = String.prototype.indexOf;\n const Refused = w.TypeError;\n const shadowed = (html) => apply(index, apply(lower, html, []), [\"shadowrootmode\"]) >= 0;\n const refuse = () => { throw new Refused(\"A declarative shadow root is not allowed here\"); };\n for (const [owner, name] of [[w.Element.prototype, \"setHTMLUnsafe\"], [w.ShadowRoot && w.ShadowRoot.prototype, \"setHTMLUnsafe\"], [w.Document, \"parseHTMLUnsafe\"]]) {\n const real = owner && owner[name];\n if (typeof real !== \"function\") continue;\n owner[name] = function (html) {\n const checked = text(html);\n if (shadowed(checked)) refuse();\n return apply(real, this, arguments.length > 1 ? [checked, arguments[1]] : [checked]);\n };\n }\n let tail = \"\";\n for (const name of [\"write\", \"writeln\"]) {\n const real = w.Document.prototype[name];\n if (typeof real !== \"function\") continue;\n w.Document.prototype[name] = function () {\n let checked = \"\";\n for (let i = 0; i < arguments.length; i++) checked += text(arguments[i]);\n if (shadowed(tail + checked)) refuse();\n tail = apply(slice, tail + checked, [-16]);\n return apply(real, this, [checked]);\n };\n }\n for (const kind of [\"HTMLIFrameElement\", \"HTMLFrameElement\", \"HTMLObjectElement\", \"HTMLEmbedElement\"]) {\n const proto = w[kind] && w[kind].prototype;\n for (const name of [\"contentWindow\", \"contentDocument\", \"getSVGDocument\"]) {\n const found = proto && describe(proto, name);\n const key = found && found.get ? \"get\" : \"value\";\n if (!found || typeof found[key] !== \"function\") continue;\n const read = found[key];\n found[key] = function () {\n const got = apply(read, this, arguments);\n try { shut(name === \"contentWindow\" ? got : apply(view, got, [])); } catch (e) {}\n return got;\n };\n try { define(proto, name, found); } catch (e) {}\n }\n }\n const { getAttribute, setAttribute, removeAttribute, attachShadow } = w.Element.prototype;\n const size = describe(w.NodeList.prototype, \"length\").get;\n const first = (frame) => {\n const doc = apply(getAttribute, frame, [\"srcdoc\"]);\n if (doc === null || apply(slice, doc, [0, own.length]) === own) return;\n try { apply(setAttribute, frame, [\"srcdoc\", own + doc]); } catch (e) { apply(removeAttribute, frame, [\"srcdoc\"]); }\n };\n const trim = String.prototype.trim;\n const drop = w.Element.prototype.remove;\n const unruled = (script) => {\n const type = apply(getAttribute, script, [\"type\"]);\n if (type !== null && apply(lower, apply(trim, type, []), []) === \"speculationrules\") apply(drop, script, []);\n };\n const Observer = w.MutationObserver;\n const observe = Observer.prototype.observe;\n const watch = (root, all) => {\n const scan = () => {\n try {\n const frames = apply(all, root, [\"iframe[srcdoc]\"]);\n for (let i = apply(size, frames, []); i-- > 0;) first(frames[i]);\n } catch (e) {}\n try {\n const scripts = apply(all, root, [\"script\"]);\n for (let i = apply(size, scripts, []); i-- > 0;) unruled(scripts[i]);\n } catch (e) {}\n sweep();\n };\n apply(observe, new Observer(scan), [root, { subtree: true, childList: true, attributes: true, attributeFilter: [\"srcdoc\"] }]);\n scan();\n return root;\n };\n const inShadow = w.DocumentFragment.prototype.querySelectorAll;\n if (attachShadow) {\n w.Element.prototype.attachShadow = function () {\n const root = apply(attachShadow, this, arguments);\n try { watch(root, inShadow); } catch (e) {}\n return root;\n };\n }\n if (w.trustedTypes && w.URL && w.Blob && !describe(w, \"ghostlyWorkerGuard\")) {\n try {\n define(w, \"ghostlyWorkerGuard\", { value: true });\n const construct = Reflect.construct;\n const json = JSON.stringify;\n const later = w.setTimeout;\n const Blob = w.Blob;\n const sized = describe(Blob.prototype, \"size\").get;\n const make = w.URL.createObjectURL;\n const revoke = w.URL.revokeObjectURL;\n const policy = \"if (self.trustedTypes && !self.trustedTypes.defaultPolicy) { try { self.trustedTypes.createPolicy('default', { createHTML: (s) => s, createScript: (s) => s, createScriptURL: (s) => s }); } catch (e) {} }\";\n const script = (code) => apply(make, null, [new Blob([code], { type: \"text/javascript\" })]);\n const known = { __proto__: null };\n let first = null;\n w.URL.createObjectURL = function createObjectURL(object) {\n const made = apply(make, this, arguments);\n try { apply(sized, object, []); known[made] = { blob: object, inner: null, classic: null, module: null }; } catch (e) {}\n return made;\n };\n w.URL.revokeObjectURL = function revokeObjectURL(url) {\n try {\n const key = text(url);\n const entry = known[key];\n if (entry) {\n delete known[key];\n const ours = [entry.inner, entry.classic, entry.module];\n apply(later, w, [() => { for (let i = 0; i < 3; i++) { if (ours[i] !== null) apply(revoke, null, [ours[i]]); } }, 60000]);\n }\n } catch (e) {}\n return apply(revoke, this, arguments);\n };\n const start = (url, options) => {\n const entry = known[text(url)];\n if (!entry) return url;\n const kind = options && typeof options === \"object\" && options.type === \"module\" ? \"module\" : \"classic\";\n if (entry[kind] === null) {\n if (entry.inner === null) entry.inner = apply(make, null, [entry.blob]);\n if (kind === \"module\" && first === null) first = script(policy);\n entry[kind] = script(kind === \"module\" ? \"import \" + json(first) + \"; import \" + json(entry.inner) + \";\" : policy + \" importScripts(\" + json(entry.inner) + \");\");\n }\n return entry[kind];\n };\n for (const name of [\"Worker\", \"SharedWorker\"]) {\n const Real = w[name];\n if (typeof Real !== \"function\") continue;\n const started = function (url) {\n if (new.target === undefined) return apply(Real, this, arguments);\n const args = [];\n for (let i = 0; i < arguments.length; i++) args[i] = arguments[i];\n if (args.length > 0) { try { args[0] = start(url, args[1]); } catch (e) {} }\n return construct(Real, args, new.target);\n };\n define(started, \"name\", { value: name });\n started.prototype = Real.prototype;\n define(Real.prototype, \"constructor\", { value: started, writable: true, enumerable: false, configurable: true });\n w[name] = started;\n }\n } catch (e) {}\n }\n apply(listen, home, [\"load\", sweep, true]);\n watch(home, w.Document.prototype.querySelectorAll);\n } catch (e) {}\n})(window)";
34
37
  /** `VIEWER_GUARD_SCRIPT`'s hash, as a CSP source: a contact's own policy that would refuse it is given it (`allowingViewerGuard`). */
35
- export declare const VIEWER_GUARD_HASH = "'sha256-DweV0mr/eyHFWESxtsRrzk0i6VjF4GSCokjozAiXkbQ='";
38
+ export declare const VIEWER_GUARD_HASH = "'sha256-G1zc09L4CUQu4pukd7RlHvzFZthzzsUsbF0WwoT+KBo='";
36
39
  /**
37
40
  * With the guard, where it is put in the page and not run by the viewer in every frame: frames only from the app's own
38
41
  * origin (a `data:` or `blob:` frame would run before the guard could), and Trusted Types, which hands each
@@ -1,4 +1,4 @@
1
- import { $ as DEFAULT_RELAYS, C as IdentityCheckUnavailable, E as boundVerifiedIdentity, wt as normalizeRelayUrl } from "./bitcoinAddress-BIW3tpJG.js";
1
+ import { $ as DEFAULT_RELAYS, C as IdentityCheckUnavailable, E as boundVerifiedIdentity, wt as normalizeRelayUrl } from "./bitcoinAddress-CDYL3yPz.js";
2
2
  // ../browser/src/proofs/pkarrRelays.ts
3
3
  /**
4
4
  * The profile's Pkarr relays (Network settings), which a did:dht proof is read from, as every other Pkarr read: a
@@ -122,4 +122,4 @@ function boundedIdentityFetch(options = { online: () => true }) {
122
122
  }
123
123
  export { verifyIdentity as i, boundedIdentityFetch as n, descriptorProblems as r, availableSigners as t };
124
124
 
125
- //# sourceMappingURL=verify-DGJJAFTs.js.map
125
+ //# sourceMappingURL=verify-CmN2lXY3.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"verify-DGJJAFTs.js","names":[],"sources":["../../browser/src/proofs/pkarrRelays.ts","../../browser/src/proofs/verify.ts"],"sourcesContent":["import { DEFAULT_RELAYS, normalizeRelayUrl } from \"@ghostly/core\";\n\n/**\n * The profile's Pkarr relays (Network settings), which a did:dht proof is read from, as every other Pkarr read: a\n * person who replaced the list is never read from the defaults. The UI and the engine each set where to read it. Here,\n * not in the provider, so setting it does not load the providers.\n */\nlet source: () => readonly string[] | undefined = () => undefined;\nexport function setPkarrRelaySource(read: () => readonly string[] | undefined): void { source = read; }\nexport function pkarrRelays(): string[] {\n const relays = source();\n return relays?.length ? [...relays] : [...DEFAULT_RELAYS];\n}\n\n/** Whether `url` is under one of the profile's Pkarr relays (`<relay>/…`). */\nexport function isOwnPkarrRelayUrl(url: URL): boolean {\n if (url.username || url.password) return false;\n return pkarrRelays().map(normalizeRelayUrl).some(relay => relay !== null && url.href.startsWith(`${relay}/`));\n}\n","import { boundVerifiedIdentity, IdentityCheckUnavailable, IDENTITY_MAX_EVIDENCE, IDENTITY_MAX_VALIDITY, type IdentityStatement, type VerifiedIdentity } from \"@ghostly/core\";\nimport type { IdentityFetch, IdentityProofProvider, IdentitySigner, VerifyContext } from \"./contract\";\nimport { isOwnPkarrRelayUrl } from \"./pkarrRelays\";\n\nconst DAY = 86_400;\n\n/**\n * The checks every proof goes through, whatever its provider: known provider, validity within the\n * provider's limit, bounded evidence, strict parsing, the provider's own check, and the category rule\n * (a self-custodied proof proves exactly the subject it names; an attested one says who attests it).\n * The engine verifies a contact's proof, and the person's own proof before saving it, only through this.\n */\nexport async function verifyIdentity(providers: readonly IdentityProofProvider[], statement: IdentityStatement, evidence: unknown, ctx: VerifyContext): Promise<VerifiedIdentity> {\n const { binding } = statement;\n const provider = providers.find(p => p.id === binding.provider);\n if (!provider) throw new Error(\"This app cannot verify this kind of identity\");\n if (binding.expiresAt - binding.issuedAt > Math.min(provider.validity.maxDays * DAY, IDENTITY_MAX_VALIDITY)) throw new Error(\"The proof lasts longer than this kind of identity allows\");\n if (JSON.stringify(evidence ?? null).length > IDENTITY_MAX_EVIDENCE) throw new Error(\"Evidence too large\");\n const parsed = provider.parseEvidence(evidence);\n const verified = boundVerifiedIdentity(await provider.verify(statement, parsed, ctx));\n if (provider.category === \"self-custodied\" && verified.subject !== binding.subject) throw new Error(\"The evidence is for another identity\");\n if (provider.category === \"provider-attested\" && !verified.attester) throw new Error(\"The evidence does not say who attests it\");\n return verified;\n}\n\n/** Problems with a provider's descriptor, empty when it is well-formed. The registry and the contract suite use it. */\nexport function descriptorProblems(p: IdentityProofProvider): string[] {\n const problems: string[] = [];\n if (!/^[a-z][a-z0-9-]{0,31}$/.test(p.id)) problems.push(\"id must match ^[a-z][a-z0-9-]{0,31}$\");\n if (!p.label?.trim()) problems.push(\"label is empty\");\n if (!p.description?.trim()) problems.push(\"description is empty\");\n if (!p.privacy?.trim()) problems.push(\"privacy is empty: say what verify contacts\");\n if (p.category !== \"self-custodied\" && p.category !== \"provider-attested\") problems.push(\"category is unknown\");\n if (!p.platforms.length) problems.push(\"no platforms\");\n const { defaultDays, maxDays } = p.validity;\n if (!(Number.isInteger(defaultDays) && Number.isInteger(maxDays) && defaultDays >= 1 && defaultDays <= maxDays && maxDays * DAY <= IDENTITY_MAX_VALIDITY)) problems.push(\"validity must be whole days, 1 ≤ default ≤ max ≤ 400\");\n if (p.recheck && !(Number.isInteger(p.recheck.afterSeconds) && p.recheck.afterSeconds >= 60)) problems.push(\"recheck.afterSeconds must be at least 60\");\n if (p.recheck?.perHour !== undefined && !(Number.isInteger(p.recheck.perHour) && p.recheck.perHour >= 1)) problems.push(\"recheck.perHour must be a whole number, at least 1\");\n if (!p.signers.length) problems.push(\"no signers\");\n const ids = p.signers.map(s => s.id);\n if (new Set(ids).size !== ids.length) problems.push(\"signer ids are not unique\");\n for (const s of p.signers as readonly IdentitySigner<unknown>[]) {\n if (![\"in-app\", \"external-tool\", \"redirect\", \"publish\"].includes(s.kind)) problems.push(`signer ${s.id} has an unknown kind`);\n if (s.kind === \"in-app\" && typeof s.run !== \"function\") problems.push(`signer ${s.id} has no run()`);\n if (s.kind === \"external-tool\" && (typeof s.instructions !== \"function\" || typeof s.parse !== \"function\")) problems.push(`signer ${s.id} needs instructions() and parse()`);\n if (s.kind === \"redirect\" && typeof s.start !== \"function\") problems.push(`signer ${s.id} has no start()`);\n if (s.kind === \"publish\" && (typeof s.instructions !== \"function\" || typeof s.evidence !== \"function\")) problems.push(`signer ${s.id} needs instructions() and evidence()`);\n }\n return problems;\n}\n\n/** Signers of a provider that run on this platform and are available in this window. */\nexport function availableSigners<E>(p: IdentityProofProvider<E>, platform: IdentityProofProvider[\"platforms\"][number]): IdentitySigner<E>[] {\n return p.signers.filter(s => (s.platforms ?? p.platforms).includes(platform) && (s.available?.() ?? true));\n}\n\n/**\n * The engine's `ctx.fetch`: HTTPS GET only, no credentials or referrer, a time-out, a size cap,\n * redirects refused unless asked for.\n * `online` false refuses everything (the person turned the network off).\n * A did:dht read of the profile's own Pkarr relays (`ownPkarrRelay`) may be http://, through `relayFetcher`: those are\n * the relays the person chose, as the chats read them, not an address a contact named.\n */\nexport function boundedIdentityFetch(options: { online: () => boolean; timeoutMs?: number; fetcher?: typeof fetch; relayFetcher?: typeof fetch } = { online: () => true }): IdentityFetch {\n return async (url, { headers, maxBytes = 64 * 1024, signal, redirect = \"error\", ownPkarrRelay } = {}) => {\n if (!options.online()) throw new IdentityCheckUnavailable(\"Offline: this identity cannot be checked now\");\n const target = new URL(url);\n const ownRelay = ownPkarrRelay === true && isOwnPkarrRelayUrl(target);\n if (!ownRelay && (target.protocol !== \"https:\" || target.username || target.password)) throw new Error(\"Identity checks use HTTPS only\");\n const timeout = AbortSignal.timeout(options.timeoutMs ?? 10_000);\n const fetcher = (ownRelay ? options.relayFetcher : undefined) ?? options.fetcher ?? fetch;\n const response = await fetcher(target.href, {\n headers, signal: signal ? AbortSignal.any([signal, timeout]) : timeout,\n credentials: \"omit\", referrerPolicy: \"no-referrer\", cache: \"no-store\", redirect,\n });\n if (Number(response.headers.get(\"content-length\")) > maxBytes) throw new Error(\"Identity check response too large\");\n const reader = response.body?.getReader();\n const parts: Uint8Array[] = [];\n let length = 0;\n if (reader) {\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n length += value.length;\n if (length > maxBytes) throw new Error(\"Identity check response too large\");\n parts.push(value);\n }\n } finally { await reader.cancel().catch(() => {}); }\n }\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const part of parts) { bytes.set(part, offset); offset += part.length; }\n return { status: response.status, contentType: response.headers.get(\"content-type\") ?? \"\", text: new TextDecoder().decode(bytes), bytes };\n };\n}\n"],"mappings":";;;;;;;AAOA,IAAI,eAAoD,KAAA;AAExD,SAAgB,cAAwB;CACtC,MAAM,SAAS,OAAO;CACtB,OAAO,QAAQ,SAAS,CAAC,GAAG,MAAM,IAAI,CAAC,GAAG,cAAc;AAC1D;;AAGA,SAAgB,mBAAmB,KAAmB;CACpD,IAAI,IAAI,YAAY,IAAI,UAAU,OAAO;CACzC,OAAO,YAAY,CAAC,CAAC,IAAI,iBAAiB,CAAC,CAAC,MAAK,UAAS,UAAU,QAAQ,IAAI,KAAK,WAAW,GAAG,MAAM,EAAE,CAAC;AAC9G;;ACdA,IAAM,MAAM;;;;;;;AAQZ,eAAsB,eAAe,WAA6C,WAA8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G,UAAU,KAAK;EAAQ;EAC5E,OAAO;GAAE,QAAQ,SAAS;GAAQ,aAAa,SAAS,QAAQ,IAAI,cAAc,KAAK;GAAI,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK;GAAG;EAAM;CAC1I;AACF"}
1
+ {"version":3,"file":"verify-CmN2lXY3.js","names":[],"sources":["../../browser/src/proofs/pkarrRelays.ts","../../browser/src/proofs/verify.ts"],"sourcesContent":["import { DEFAULT_RELAYS, normalizeRelayUrl } from \"@ghostly/core\";\n\n/**\n * The profile's Pkarr relays (Network settings), which a did:dht proof is read from, as every other Pkarr read: a\n * person who replaced the list is never read from the defaults. The UI and the engine each set where to read it. Here,\n * not in the provider, so setting it does not load the providers.\n */\nlet source: () => readonly string[] | undefined = () => undefined;\nexport function setPkarrRelaySource(read: () => readonly string[] | undefined): void { source = read; }\nexport function pkarrRelays(): string[] {\n const relays = source();\n return relays?.length ? [...relays] : [...DEFAULT_RELAYS];\n}\n\n/** Whether `url` is under one of the profile's Pkarr relays (`<relay>/…`). */\nexport function isOwnPkarrRelayUrl(url: URL): boolean {\n if (url.username || url.password) return false;\n return pkarrRelays().map(normalizeRelayUrl).some(relay => relay !== null && url.href.startsWith(`${relay}/`));\n}\n","import { boundVerifiedIdentity, IdentityCheckUnavailable, IDENTITY_MAX_EVIDENCE, IDENTITY_MAX_VALIDITY, type IdentityStatement, type VerifiedIdentity } from \"@ghostly/core\";\nimport type { IdentityFetch, IdentityProofProvider, IdentitySigner, VerifyContext } from \"./contract\";\nimport { isOwnPkarrRelayUrl } from \"./pkarrRelays\";\n\nconst DAY = 86_400;\n\n/**\n * The checks every proof goes through, whatever its provider: known provider, validity within the\n * provider's limit, bounded evidence, strict parsing, the provider's own check, and the category rule\n * (a self-custodied proof proves exactly the subject it names; an attested one says who attests it).\n * The engine verifies a contact's proof, and the person's own proof before saving it, only through this.\n */\nexport async function verifyIdentity(providers: readonly IdentityProofProvider[], statement: IdentityStatement, evidence: unknown, ctx: VerifyContext): Promise<VerifiedIdentity> {\n const { binding } = statement;\n const provider = providers.find(p => p.id === binding.provider);\n if (!provider) throw new Error(\"This app cannot verify this kind of identity\");\n if (binding.expiresAt - binding.issuedAt > Math.min(provider.validity.maxDays * DAY, IDENTITY_MAX_VALIDITY)) throw new Error(\"The proof lasts longer than this kind of identity allows\");\n if (JSON.stringify(evidence ?? null).length > IDENTITY_MAX_EVIDENCE) throw new Error(\"Evidence too large\");\n const parsed = provider.parseEvidence(evidence);\n const verified = boundVerifiedIdentity(await provider.verify(statement, parsed, ctx));\n if (provider.category === \"self-custodied\" && verified.subject !== binding.subject) throw new Error(\"The evidence is for another identity\");\n if (provider.category === \"provider-attested\" && !verified.attester) throw new Error(\"The evidence does not say who attests it\");\n return verified;\n}\n\n/** Problems with a provider's descriptor, empty when it is well-formed. The registry and the contract suite use it. */\nexport function descriptorProblems(p: IdentityProofProvider): string[] {\n const problems: string[] = [];\n if (!/^[a-z][a-z0-9-]{0,31}$/.test(p.id)) problems.push(\"id must match ^[a-z][a-z0-9-]{0,31}$\");\n if (!p.label?.trim()) problems.push(\"label is empty\");\n if (!p.description?.trim()) problems.push(\"description is empty\");\n if (!p.privacy?.trim()) problems.push(\"privacy is empty: say what verify contacts\");\n if (p.category !== \"self-custodied\" && p.category !== \"provider-attested\") problems.push(\"category is unknown\");\n if (!p.platforms.length) problems.push(\"no platforms\");\n const { defaultDays, maxDays } = p.validity;\n if (!(Number.isInteger(defaultDays) && Number.isInteger(maxDays) && defaultDays >= 1 && defaultDays <= maxDays && maxDays * DAY <= IDENTITY_MAX_VALIDITY)) problems.push(\"validity must be whole days, 1 ≤ default ≤ max ≤ 400\");\n if (p.recheck && !(Number.isInteger(p.recheck.afterSeconds) && p.recheck.afterSeconds >= 60)) problems.push(\"recheck.afterSeconds must be at least 60\");\n if (p.recheck?.perHour !== undefined && !(Number.isInteger(p.recheck.perHour) && p.recheck.perHour >= 1)) problems.push(\"recheck.perHour must be a whole number, at least 1\");\n if (!p.signers.length) problems.push(\"no signers\");\n const ids = p.signers.map(s => s.id);\n if (new Set(ids).size !== ids.length) problems.push(\"signer ids are not unique\");\n for (const s of p.signers as readonly IdentitySigner<unknown>[]) {\n if (![\"in-app\", \"external-tool\", \"redirect\", \"publish\"].includes(s.kind)) problems.push(`signer ${s.id} has an unknown kind`);\n if (s.kind === \"in-app\" && typeof s.run !== \"function\") problems.push(`signer ${s.id} has no run()`);\n if (s.kind === \"external-tool\" && (typeof s.instructions !== \"function\" || typeof s.parse !== \"function\")) problems.push(`signer ${s.id} needs instructions() and parse()`);\n if (s.kind === \"redirect\" && typeof s.start !== \"function\") problems.push(`signer ${s.id} has no start()`);\n if (s.kind === \"publish\" && (typeof s.instructions !== \"function\" || typeof s.evidence !== \"function\")) problems.push(`signer ${s.id} needs instructions() and evidence()`);\n }\n return problems;\n}\n\n/** Signers of a provider that run on this platform and are available in this window. */\nexport function availableSigners<E>(p: IdentityProofProvider<E>, platform: IdentityProofProvider[\"platforms\"][number]): IdentitySigner<E>[] {\n return p.signers.filter(s => (s.platforms ?? p.platforms).includes(platform) && (s.available?.() ?? true));\n}\n\n/**\n * The engine's `ctx.fetch`: HTTPS GET only, no credentials or referrer, a time-out, a size cap,\n * redirects refused unless asked for.\n * `online` false refuses everything (the person turned the network off).\n * A did:dht read of the profile's own Pkarr relays (`ownPkarrRelay`) may be http://, through `relayFetcher`: those are\n * the relays the person chose, as the chats read them, not an address a contact named.\n */\nexport function boundedIdentityFetch(options: { online: () => boolean; timeoutMs?: number; fetcher?: typeof fetch; relayFetcher?: typeof fetch } = { online: () => true }): IdentityFetch {\n return async (url, { headers, maxBytes = 64 * 1024, signal, redirect = \"error\", ownPkarrRelay } = {}) => {\n if (!options.online()) throw new IdentityCheckUnavailable(\"Offline: this identity cannot be checked now\");\n const target = new URL(url);\n const ownRelay = ownPkarrRelay === true && isOwnPkarrRelayUrl(target);\n if (!ownRelay && (target.protocol !== \"https:\" || target.username || target.password)) throw new Error(\"Identity checks use HTTPS only\");\n const timeout = AbortSignal.timeout(options.timeoutMs ?? 10_000);\n const fetcher = (ownRelay ? options.relayFetcher : undefined) ?? options.fetcher ?? fetch;\n const response = await fetcher(target.href, {\n headers, signal: signal ? AbortSignal.any([signal, timeout]) : timeout,\n credentials: \"omit\", referrerPolicy: \"no-referrer\", cache: \"no-store\", redirect,\n });\n if (Number(response.headers.get(\"content-length\")) > maxBytes) throw new Error(\"Identity check response too large\");\n const reader = response.body?.getReader();\n const parts: Uint8Array[] = [];\n let length = 0;\n if (reader) {\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n length += value.length;\n if (length > maxBytes) throw new Error(\"Identity check response too large\");\n parts.push(value);\n }\n } finally { await reader.cancel().catch(() => {}); }\n }\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const part of parts) { bytes.set(part, offset); offset += part.length; }\n return { status: response.status, contentType: response.headers.get(\"content-type\") ?? \"\", text: new TextDecoder().decode(bytes), bytes };\n };\n}\n"],"mappings":";;;;;;;AAOA,IAAI,eAAoD,KAAA;AAExD,SAAgB,cAAwB;CACtC,MAAM,SAAS,OAAO;CACtB,OAAO,QAAQ,SAAS,CAAC,GAAG,MAAM,IAAI,CAAC,GAAG,cAAc;AAC1D;;AAGA,SAAgB,mBAAmB,KAAmB;CACpD,IAAI,IAAI,YAAY,IAAI,UAAU,OAAO;CACzC,OAAO,YAAY,CAAC,CAAC,IAAI,iBAAiB,CAAC,CAAC,MAAK,UAAS,UAAU,QAAQ,IAAI,KAAK,WAAW,GAAG,MAAM,EAAE,CAAC;AAC9G;;ACdA,IAAM,MAAM;;;;;;;AAQZ,eAAsB,eAAe,WAA6C,WAA8B,UAAmB,KAA+C;CAChL,MAAM,EAAE,YAAY;CACpB,MAAM,WAAW,UAAU,MAAK,MAAK,EAAE,OAAO,QAAQ,QAAQ;CAC9D,IAAI,CAAC,UAAU,MAAM,IAAI,MAAM,8CAA8C;CAC7E,IAAI,QAAQ,YAAY,QAAQ,WAAW,KAAK,IAAI,S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1
  {
2
2
  "name": "@ghostlytools/sdk",
3
- "version": "1.13.2",
3
+ "version": "1.13.4",
4
4
  "type": "module",
5
5
  "description": "Build a wallet source, an identity proof, a mini-app or a client for Ghostly without reading its internals: the adapter contracts, their fakes and contract test suites, the plugin registry, and the mini-app API types (Apps run in Ghostly 1.2 and later).",
6
6
  "license": "MIT",