@ghostlytools/cli 1.13.3 → 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.
Files changed (86) hide show
  1. package/dist/assets/{api-DO0YMLiB.js → api-B5qxNMgg.js} +2 -2
  2. package/dist/assets/{api-Dz2cw7WD.js → api-iiij_pP5.js} +71 -28
  3. package/dist/assets/api-iiij_pP5.js.map +1 -0
  4. package/dist/assets/{apiKit-DAFsWtyk.js → apiKit-BPuHOoXF.js} +2 -2
  5. package/dist/assets/{apiKit-DAFsWtyk.js.map → apiKit-BPuHOoXF.js.map} +1 -1
  6. package/dist/assets/{appFetch-BQO5Pk7W.js → appFetch-D89FnCxr.js} +2 -2
  7. package/dist/assets/{appFetch-BQO5Pk7W.js.map → appFetch-D89FnCxr.js.map} +1 -1
  8. package/dist/assets/{apps-D4KRpZB4.js → apps-BpZcd86Y.js} +1 -1
  9. package/dist/assets/{apps-B88rYWRm.js → apps-D2YGSPJe.js} +5 -5
  10. package/dist/assets/{apps-B88rYWRm.js.map → apps-D2YGSPJe.js.map} +1 -1
  11. package/dist/assets/{backup-CNLY905d.js → backup-BrMe9VPY.js} +4 -4
  12. package/dist/assets/{backup-CNLY905d.js.map → backup-BrMe9VPY.js.map} +1 -1
  13. package/dist/assets/{backup-BeXBtbVL.js → backup-COkkM8Yy.js} +1 -1
  14. package/dist/assets/{bitcoind-BXZdQ1wZ.js → bitcoind-CK1QEUHn.js} +2 -2
  15. package/dist/assets/{bitcoind-BXZdQ1wZ.js.map → bitcoind-CK1QEUHn.js.map} +1 -1
  16. package/dist/assets/{blobFiles-DDs34n0r.js → blobFiles-DA3UEn37.js} +3 -3
  17. package/dist/assets/{blobFiles-DDs34n0r.js.map → blobFiles-DA3UEn37.js.map} +1 -1
  18. package/dist/assets/buttons-BWEdoxgK.js +1 -0
  19. package/dist/assets/{buttons-BKojbx0Q.js → buttons-UsDPQJsQ.js} +4 -4
  20. package/dist/assets/{buttons-BKojbx0Q.js.map → buttons-UsDPQJsQ.js.map} +1 -1
  21. package/dist/assets/{client-BtPhfWjK.js → client-Cj-VLeTs.js} +2 -2
  22. package/dist/assets/{client-BtPhfWjK.js.map → client-Cj-VLeTs.js.map} +1 -1
  23. package/dist/assets/{fileBytes-CfvUXdSy.js → fileBytes-B2jXQI8e.js} +3 -3
  24. package/dist/assets/{fileBytes-CfvUXdSy.js.map → fileBytes-B2jXQI8e.js.map} +1 -1
  25. package/dist/assets/{fileBytes-tj6-VZcB.js → fileBytes-BQrW3m-d.js} +2 -2
  26. package/dist/assets/{fileBytes-tj6-VZcB.js.map → fileBytes-BQrW3m-d.js.map} +1 -1
  27. package/dist/assets/{fileBytes-CCKbwqG_.js → fileBytes-CtjxJ6AL.js} +1 -1
  28. package/dist/assets/{fileBytesIdb-BJirUAjI.js → fileBytesIdb-B7Wjw0S8.js} +3 -3
  29. package/dist/assets/{fileBytesIdb-BJirUAjI.js.map → fileBytesIdb-B7Wjw0S8.js.map} +1 -1
  30. package/dist/assets/fileBytesIdb-Fcj2mwj6.js +1 -0
  31. package/dist/assets/{fileBytesOpfs-DRUYLER4.js → fileBytesOpfs-BW0u-_f_.js} +3 -3
  32. package/dist/assets/{fileBytesOpfs-DRUYLER4.js.map → fileBytesOpfs-BW0u-_f_.js.map} +1 -1
  33. package/dist/assets/{fixedHosts-BJFL8Ell.js → fixedHosts-CrO01M_y.js} +3 -3
  34. package/dist/assets/{fixedHosts-BJFL8Ell.js.map → fixedHosts-CrO01M_y.js.map} +1 -1
  35. package/dist/assets/{groupMeta-Cz95F6sX.js → groupMeta-DHJxOu0K.js} +3 -3
  36. package/dist/assets/groupMeta-DHJxOu0K.js.map +1 -0
  37. package/dist/assets/{host-BsBWxTtW.js → host-C4J4y-Zq.js} +24 -16
  38. package/dist/assets/host-C4J4y-Zq.js.map +1 -0
  39. package/dist/assets/{idb-ewvbqyDI.js → idb-CmIR_bxg.js} +2 -1
  40. package/dist/assets/idb-CmIR_bxg.js.map +1 -0
  41. package/dist/assets/{identityProofs-zI_Iy9uI.js → identityProofs-C0rIGT6y.js} +6 -3
  42. package/dist/assets/identityProofs-C0rIGT6y.js.map +1 -0
  43. package/dist/assets/{irohWeb-BLDcHwYz.js → irohWeb-BXgunUhu.js} +69 -26
  44. package/dist/assets/irohWeb-BXgunUhu.js.map +1 -0
  45. package/dist/assets/{main-D48Ben7C.js → main-BLs-zUTt.js} +18 -18
  46. package/dist/assets/{main-D48Ben7C.js.map → main-BLs-zUTt.js.map} +1 -1
  47. package/dist/assets/{mainline-CDUXtV-I.js → mainline-CYek1H10.js} +2 -2
  48. package/dist/assets/{mainline-CDUXtV-I.js.map → mainline-CYek1H10.js.map} +1 -1
  49. package/dist/assets/{networkReason-DYlPZS5M.js → networkReason-C6LYbjF2.js} +2 -2
  50. package/dist/assets/{networkReason-DYlPZS5M.js.map → networkReason-C6LYbjF2.js.map} +1 -1
  51. package/dist/assets/{ownDid-CwxFBzOH.js → ownDid-Dg-8e_hs.js} +4 -4
  52. package/dist/assets/{ownDid-CwxFBzOH.js.map → ownDid-Dg-8e_hs.js.map} +1 -1
  53. package/dist/assets/{ownStatus-DjD0sQKF.js → ownStatus-BOx4vLi6.js} +3 -3
  54. package/dist/assets/{ownStatus-DjD0sQKF.js.map → ownStatus-BOx4vLi6.js.map} +1 -1
  55. package/dist/assets/{profiles-BAJf0c9E.js → profiles-BA0ePikY.js} +2 -2
  56. package/dist/assets/{profiles-BAJf0c9E.js.map → profiles-BA0ePikY.js.map} +1 -1
  57. package/dist/assets/{registry-CHwHTWbK.js → registry-DuSwXntJ.js} +1 -1
  58. package/dist/assets/{registry-CPuexTle.js → registry-OoIgxDrO.js} +5 -5
  59. package/dist/assets/{registry-CPuexTle.js.map → registry-OoIgxDrO.js.map} +1 -1
  60. package/dist/assets/{relay-gJTOYQJZ.js → relay-NT5bf1WA.js} +9 -6
  61. package/dist/assets/relay-NT5bf1WA.js.map +1 -0
  62. package/dist/assets/{resolve-BqmGXKn4.js → resolve-DUmE70Eo.js} +3 -3
  63. package/dist/assets/{resolve-BqmGXKn4.js.map → resolve-DUmE70Eo.js.map} +1 -1
  64. package/dist/assets/{restoredRows-D_WSHE7H.js → restoredRows-Cgaxx1xW.js} +2 -2
  65. package/dist/assets/{restoredRows-D_WSHE7H.js.map → restoredRows-Cgaxx1xW.js.map} +1 -1
  66. package/dist/assets/{server-e4oKeNez.js → server-WWlXICVB.js} +166 -32
  67. package/dist/assets/server-WWlXICVB.js.map +1 -0
  68. package/dist/assets/{sshForges-Cqt3qfWe.js → sshForges-Cfu-dSwc.js} +2 -2
  69. package/dist/assets/{sshForges-Cqt3qfWe.js.map → sshForges-Cfu-dSwc.js.map} +1 -1
  70. package/dist/assets/{usdt-DLmtf8F9.js → usdt-BkO4SY07.js} +2 -2
  71. package/dist/assets/{usdt-DLmtf8F9.js.map → usdt-BkO4SY07.js.map} +1 -1
  72. package/dist/assets/{waitNotice-mB0Ym145.js → waitNotice-DSECf6II.js} +2 -2
  73. package/dist/assets/{waitNotice-mB0Ym145.js.map → waitNotice-DSECf6II.js.map} +1 -1
  74. package/dist/ghostly.mjs +1 -1
  75. package/npm-shrinkwrap.json +2 -2
  76. package/package.json +1 -1
  77. package/dist/assets/api-Dz2cw7WD.js.map +0 -1
  78. package/dist/assets/buttons-_5Fw8uHn.js +0 -1
  79. package/dist/assets/fileBytesIdb-B0zzJ6p7.js +0 -1
  80. package/dist/assets/groupMeta-Cz95F6sX.js.map +0 -1
  81. package/dist/assets/host-BsBWxTtW.js.map +0 -1
  82. package/dist/assets/idb-ewvbqyDI.js.map +0 -1
  83. package/dist/assets/identityProofs-zI_Iy9uI.js.map +0 -1
  84. package/dist/assets/irohWeb-BLDcHwYz.js.map +0 -1
  85. package/dist/assets/relay-gJTOYQJZ.js.map +0 -1
  86. package/dist/assets/server-e4oKeNez.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  import { c as toBase64, d as utf8Decode, f as utf8Encode, n as concatBytes, r as fromBase64, t as bytesEqual } from "./bytes-C1DNGY18.js";
2
- import { s as IdentityCheckUnavailable } from "./identityProofs-zI_Iy9uI.js";
2
+ import { s as IdentityCheckUnavailable } from "./identityProofs-C0rIGT6y.js";
3
3
  import { ed25519 } from "@noble/curves/ed25519.js";
4
4
  import { sha256, sha512 } from "@noble/hashes/sha2.js";
5
5
  import { p256, p384, p521 } from "@noble/curves/nist.js";
@@ -536,4 +536,4 @@ async function checkSshForge(forge, login, key, fetcher, signal) {
536
536
  }
537
537
  export { sshSignCommand as _, PUBKY_RELAYS as a, isConfigured as c, providerForIssuer as d, SSHSIG_MAX_ARMOR as f, parseSshSignature as g, parseSshPublicKey as h, validForgeLogin as i, issuerFor as l, SshSigError as m, SSH_FORGE_LABEL as n, audiences as o, SSHSIG_NAMESPACE as p, checkSshForge as r, clientIdFor as s, SSH_FORGE_HOST as t, oidcProviders as u, verifySshSignature as v };
538
538
 
539
- //# sourceMappingURL=sshForges-Cqt3qfWe.js.map
539
+ //# sourceMappingURL=sshForges-Cfu-dSwc.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sshForges-Cqt3qfWe.js","names":[],"sources":["../../../core/src/sshsig.ts","../../../browser/src/proofs/oidc/providers.ts","../../../browser/src/proofs/pubkyRelays.ts","../../../browser/src/proofs/sshForges.ts"],"sourcesContent":["import { ed25519 } from '@noble/curves/ed25519.js';\nimport { p256, p384, p521 } from '@noble/curves/nist.js';\nimport { sha256, sha512 } from '@noble/hashes/sha2.js';\nimport { bytesEqual, concatBytes, fromBase64, toBase64, utf8Decode, utf8Encode } from './bytes';\n\n/** OpenSSH signatures over a Ghostly statement (`ssh-keygen -Y sign -n ghostly`),\n * following PROTOCOL.sshsig. Everything here is local: parsing, the public key\n * the signature names and the signature itself. Which key a person *should*\n * have signed with is the caller's question (an expected fingerprint, or a\n * key list published by a forge; see the browser proof provider). */\n\nexport const SSHSIG_NAMESPACE = 'ghostly';\n/** A pasted armored signature: an 8192-bit RSA key plus its signature is ~3 KB. */\nexport const SSHSIG_MAX_ARMOR = 6144;\n/** A pasted `.pub` line; comments are dropped. */\nexport const SSH_PUBLIC_KEY_MAX = 4096;\nconst RSA_MIN_BITS = 2048;\nconst RSA_MAX_BITS = 8192;\nconst SK_APPLICATION_MAX = 256;\nconst SK_USER_PRESENT = 0x01;\nconst SK_USER_VERIFIED = 0x04;\n\nexport type SshKeyType =\n | 'ssh-ed25519' | 'ecdsa-sha2-nistp256' | 'ecdsa-sha2-nistp384' | 'ecdsa-sha2-nistp521' | 'ssh-rsa'\n | 'sk-ssh-ed25519@openssh.com' | 'sk-ecdsa-sha2-nistp256@openssh.com';\nexport const SSH_KEY_TYPES: readonly SshKeyType[] = ['ssh-ed25519', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', 'ecdsa-sha2-nistp521',\n 'ssh-rsa', 'sk-ssh-ed25519@openssh.com', 'sk-ecdsa-sha2-nistp256@openssh.com'];\n\nexport interface SshPublicKey {\n type: SshKeyType;\n /** The wire-format key blob, which is what fingerprints and forge key lists name. */\n blob: Uint8Array;\n /** `SHA256:` + unpadded base64, exactly as `ssh-keygen -l` prints it. */\n fingerprint: string;\n /** `type base64`, the form `.pub` files and forge key lists use (no comment). */\n line: string;\n /** Security keys only: the FIDO application, `ssh:` unless chosen at creation. */\n application?: string;\n /** RSA modulus size. */\n bits?: number;\n}\nexport interface SshSignatureCheck {\n key: SshPublicKey;\n hashAlgorithm: 'sha256' | 'sha512';\n /** Security keys only: what the authenticator asserted for this signature. */\n securityKey?: { userPresent: boolean; userVerified: boolean; counter: number };\n}\n\nexport class SshSigError extends Error {}\nconst fail = (message: string): never => { throw new SshSigError(message); };\n\nclass Reader {\n private at = 0;\n constructor(private bytes: Uint8Array) {}\n get done() { return this.at === this.bytes.length; }\n raw(n: number): Uint8Array {\n if (n > this.bytes.length - this.at) fail('Truncated SSH data');\n return this.bytes.subarray(this.at, this.at += n);\n }\n u8(): number { return this.raw(1)[0]; }\n u32(): number { const b = this.raw(4); return ((b[0] << 24) >>> 0) + (b[1] << 16) + (b[2] << 8) + b[3]; }\n string(max = this.bytes.length): Uint8Array {\n const n = this.u32();\n if (n > max) fail('SSH field too long');\n return this.raw(n);\n }\n text(max: number): string {\n const b = this.string(max);\n if (!b.every(c => c >= 0x20 && c < 0x7f)) fail('SSH name is not printable ASCII');\n return utf8Decode(b);\n }\n /** Positive mpint in canonical form: no redundant leading zero, sign bit clear. */\n mpint(maxBytes: number): Uint8Array {\n const b = this.string(maxBytes + 1);\n if (!b.length || b[0] & 0x80 || (b[0] === 0 && (b.length === 1 || !(b[1] & 0x80)))) fail('Non-canonical SSH integer');\n return b[0] === 0 ? b.subarray(1) : b;\n }\n end() { if (!this.done) fail('Trailing bytes in SSH data'); }\n}\nconst u32 = (n: number) => Uint8Array.of(n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255);\nconst sshString = (b: Uint8Array) => concatBytes(u32(b.length), b);\n\nfunction strictBase64(text: string, max: number): Uint8Array {\n if (text.length > max || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(text)) fail('Invalid base64');\n const bytes = fromBase64(text);\n if (toBase64(bytes) !== text) fail('Non-canonical base64');\n return bytes;\n}\nexport function sshFingerprint(blob: Uint8Array): string {\n return `SHA256:${toBase64(sha256(blob)).replace(/=+$/, '')}`;\n}\n\ninterface CurveInfo { name: string; curve: typeof p256 | typeof p384 | typeof p521; size: number }\nconst CURVES: Record<string, CurveInfo> = {\n 'ecdsa-sha2-nistp256': { name: 'nistp256', curve: p256, size: 32 },\n 'ecdsa-sha2-nistp384': { name: 'nistp384', curve: p384, size: 48 },\n 'ecdsa-sha2-nistp521': { name: 'nistp521', curve: p521, size: 66 },\n 'sk-ecdsa-sha2-nistp256@openssh.com': { name: 'nistp256', curve: p256, size: 32 },\n};\ninterface ParsedKey extends SshPublicKey { point?: Uint8Array; rsa?: { n: Uint8Array; e: Uint8Array } }\n\nfunction parseKeyBlob(blob: Uint8Array): ParsedKey {\n if (blob.length > 1100) fail('SSH public key too large');\n const r = new Reader(blob);\n const type = r.text(64) as SshKeyType;\n // Named only when it is DSA, a type older OpenSSH made: any other type is words the key's owner chose.\n if (!SSH_KEY_TYPES.includes(type)) fail(`Unsupported SSH key type${(type as string) === 'ssh-dss' ? ' \"ssh-dss\"' : ''}`);\n const key: ParsedKey = { type, blob, fingerprint: sshFingerprint(blob), line: `${type} ${toBase64(blob)}` };\n if (type === 'ssh-ed25519' || type === 'sk-ssh-ed25519@openssh.com') {\n key.point = r.string(32);\n if (key.point.length !== 32) fail('Invalid Ed25519 public key');\n try { ed25519.Point.fromBytes(key.point, false).assertValidity(); } catch { fail('Invalid Ed25519 public key'); }\n } else if (type === 'ssh-rsa') {\n const e = r.mpint(8), n = r.mpint(RSA_MAX_BITS / 8);\n const bits = (n.length - 1) * 8 + (32 - Math.clz32(n[0]));\n if (bits < RSA_MIN_BITS || bits > RSA_MAX_BITS) fail(`RSA keys must be ${RSA_MIN_BITS}-${RSA_MAX_BITS} bits`);\n if (!(e[e.length - 1] & 1) || (e.length === 1 && e[0] < 3)) fail('Invalid RSA exponent');\n key.rsa = { n, e }; key.bits = bits;\n } else {\n const info = CURVES[type];\n if (r.text(16) !== info.name) fail('ECDSA curve does not match the key type');\n key.point = r.string(1 + 2 * info.size);\n if (key.point.length !== 1 + 2 * info.size || key.point[0] !== 4) fail('Invalid ECDSA public key');\n try { info.curve.Point.fromBytes(key.point).assertValidity(); } catch { fail('Invalid ECDSA public key'); }\n }\n if (type.startsWith('sk-')) key.application = r.text(SK_APPLICATION_MAX);\n r.end();\n return key;\n}\n\n/** Parses one `.pub` style line (`type base64 [comment]`). */\nexport function parseSshPublicKey(line: string): SshPublicKey {\n if (typeof line !== 'string' || line.length > SSH_PUBLIC_KEY_MAX) fail('SSH public key too long');\n // Trimmed first: a pattern that ends in `[^\\n]*\\s*` tries every split of a run of spaces between the two.\n const m = /^(\\S+)\\s+(\\S+)(?:\\s[^\\n]*)?$/.exec(line.trim());\n if (!m) fail('Paste one SSH public key line (the contents of a .pub file)');\n const key = parseKeyBlob(strictBase64(m![2], SSH_PUBLIC_KEY_MAX));\n if (key.type !== m![1]) fail('SSH key type does not match its data');\n return publicView(key);\n}\nconst publicView = ({ type, blob, fingerprint, line, application, bits }: ParsedKey): SshPublicKey =>\n ({ type, blob, fingerprint, line, ...(application !== undefined ? { application } : {}), ...(bits ? { bits } : {}) });\n\ninterface ParsedSignature { key: ParsedKey; namespace: string; hashAlgorithm: 'sha256' | 'sha512'; signature: Uint8Array }\n\n/** Unwraps `-----BEGIN SSH SIGNATURE-----` armor and the SSHSIG envelope, without verifying. */\nexport function parseSshSignature(armored: string): ParsedSignature {\n if (typeof armored !== 'string' || armored.length > SSHSIG_MAX_ARMOR) fail('SSH signature too long');\n const lines = armored.replace(/\\r\\n/g, '\\n').trim().split('\\n').map(l => l.trim());\n if (lines.length < 3 || lines[0] !== '-----BEGIN SSH SIGNATURE-----' || lines[lines.length - 1] !== '-----END SSH SIGNATURE-----')\n fail('Paste the whole signature, from -----BEGIN SSH SIGNATURE----- to -----END SSH SIGNATURE-----');\n const r = new Reader(strictBase64(lines.slice(1, -1).join(''), SSHSIG_MAX_ARMOR));\n if (!bytesEqual(r.raw(6), utf8Encode('SSHSIG'))) fail('Not an SSH signature');\n if (r.u32() !== 1) fail('Unsupported SSH signature version');\n const key = parseKeyBlob(r.string(1100));\n const namespace = r.text(64);\n if (r.string(64).length) fail('Unsupported SSH signature extension');\n const hashAlgorithm = r.text(16) as ParsedSignature['hashAlgorithm'];\n if (hashAlgorithm !== 'sha256' && hashAlgorithm !== 'sha512') fail('SSH signature hash must be sha256 or sha512');\n const signature = r.string(1200);\n r.end();\n return { key, namespace, hashAlgorithm, signature };\n}\n\nasync function verifyRsa(key: ParsedKey, hash: 'SHA-256' | 'SHA-512', sig: Uint8Array, data: Uint8Array): Promise<boolean> {\n const n = key.rsa!.n, size = n.length;\n if (sig.length > size) return false;\n const padded = new Uint8Array(size); padded.set(sig, size - sig.length);\n const b64u = (b: Uint8Array) => toBase64(b).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n const cryptoKey = await crypto.subtle.importKey('jwk', { kty: 'RSA', n: b64u(n), e: b64u(key.rsa!.e), ext: true },\n { name: 'RSASSA-PKCS1-v1_5', hash }, false, ['verify']);\n return crypto.subtle.verify('RSASSA-PKCS1-v1_5', cryptoKey, padded, new Uint8Array(data));\n}\n\nfunction ecdsaSignature(blob: Uint8Array, size: number): Uint8Array {\n const r = new Reader(blob);\n const a = r.mpint(size), b = r.mpint(size);\n r.end();\n const out = new Uint8Array(2 * size);\n out.set(a, size - a.length); out.set(b, 2 * size - b.length);\n return out;\n}\n\n/** Verifies an armored SSHSIG over `message` in `namespace` and returns the key that\n * made it. Throws SshSigError for anything malformed, mismatched or unverifiable.\n * Security-key signatures must assert user presence (a touch) unless explicitly\n * allowed otherwise, matching OpenSSH's default for keys created without\n * `no-touch-required`. */\nexport async function verifySshSignature(armored: string, message: Uint8Array | string, options: { namespace?: string; allowNoTouch?: boolean } = {}): Promise<SshSignatureCheck> {\n const parsed = parseSshSignature(armored);\n const namespace = options.namespace ?? SSHSIG_NAMESPACE;\n // Never the signature's own namespace: the reason is shown on the checking side, and the signer chose those words.\n if (parsed.namespace !== namespace) fail(`Signed for another namespace, not ${JSON.stringify(namespace)}. Use -n ${namespace}.`);\n const bytes = typeof message === 'string' ? utf8Encode(message) : message;\n const digest = parsed.hashAlgorithm === 'sha512' ? sha512(bytes) : sha256(bytes);\n const signed = concatBytes(utf8Encode('SSHSIG'), sshString(utf8Encode(parsed.namespace)), sshString(new Uint8Array()),\n sshString(utf8Encode(parsed.hashAlgorithm)), sshString(digest));\n const { key } = parsed;\n const r = new Reader(parsed.signature);\n const algorithm = r.text(64);\n const blob = r.string(RSA_MAX_BITS / 8);\n let securityKey: SshSignatureCheck['securityKey'];\n let data = signed;\n if (key.type.startsWith('sk-')) {\n const flags = r.u8(), counter = r.u32();\n securityKey = { userPresent: !!(flags & SK_USER_PRESENT), userVerified: !!(flags & SK_USER_VERIFIED), counter };\n data = concatBytes(sha256(utf8Encode(key.application!)), Uint8Array.of(flags), u32(counter), sha256(signed));\n }\n r.end();\n const verifyWith = async (): Promise<boolean> => {\n if (key.type === 'ssh-rsa') {\n if (algorithm !== 'rsa-sha2-512' && algorithm !== 'rsa-sha2-256') fail('RSA signatures must use rsa-sha2-256 or rsa-sha2-512');\n return verifyRsa(key, algorithm === 'rsa-sha2-512' ? 'SHA-512' : 'SHA-256', blob, data);\n }\n if (algorithm !== key.type) fail('Signature algorithm does not match the key');\n if (key.type === 'ssh-ed25519' || key.type === 'sk-ssh-ed25519@openssh.com')\n return blob.length === 64 && ed25519.verify(blob, data, key.point!, { zip215: false });\n const info = CURVES[key.type];\n return info.curve.verify(ecdsaSignature(blob, info.size), data, key.point!, { lowS: false, prehash: true });\n };\n let ok: boolean;\n try { ok = await verifyWith(); } catch (e) { if (e instanceof SshSigError) throw e; ok = false; }\n if (!ok) fail('The signature does not match this statement');\n if (securityKey && !securityKey.userPresent && !options.allowNoTouch) fail('The security key did not confirm a touch for this signature');\n return { key: publicView(key), hashAlgorithm: parsed.hashAlgorithm, ...(securityKey ? { securityKey } : {}) };\n}\n\n/** Whether two keys are the same, comparing wire blobs (comments never matter). */\nexport const sameSshKey = (a: Pick<SshPublicKey, 'blob'>, b: Pick<SshPublicKey, 'blob'>) => bytesEqual(a.blob, b.blob);\n\n/** 32-byte digest of the key blob as lowercase hex: the fingerprint's bytes, in the\n * shape peer-proof external keys already use. */\nexport const sshKeyDigestHex = (key: Pick<SshPublicKey, 'blob'>) =>\n Array.from(sha256(key.blob), b => b.toString(16).padStart(2, '0')).join('');\n\n/** A POSIX shell one-liner that signs `statement` exactly (no trailing newline) and\n * prints the armored signature. Refuses anything that would need escaping, so what\n * is shown is what gets signed. */\nexport function sshSignCommand(statement: string, keyPath = '~/.ssh/id_ed25519'): string {\n if (/['\\\\\\n\\r]/.test(statement)) fail('Statement cannot be quoted for a shell');\n if (!/^[\\w~./@+-]{1,256}$/.test(keyPath)) fail('Use a plain key path without spaces or quotes');\n return `printf '%s' '${statement}' | ssh-keygen -Y sign -n ${SSHSIG_NAMESPACE} -f ${keyPath}`;\n}\n","/**\n * The OpenID Connect providers Ghostly can ask for a signed ID token. A contact\n * verifies that token against the provider's published keys, with no Ghostly\n * server in between, so a provider is only listed when its ID tokens are signed\n * and its keys and sign-in page are reachable from a browser without a client\n * secret. See docs/wisps/3xx-oidc-proofs.md for the providers that are not\n * (Facebook, X, LinkedIn, GitHub) and why.\n *\n * Client IDs are public configuration, identical in every build, because the\n * contact's app checks `aud` against them. They stay empty until the OAuth\n * clients are registered (docs/OIDC-PROVIDERS.md); a provider without a client\n * ID is neither offered nor accepted.\n */\n\nexport type OidcProviderId = 'google' | 'microsoft' | 'apple' | 'gitlab' | 'twitch' | 'test';\nexport type OidcAlg = 'RS256' | 'ES256';\nexport type OidcPlatform = 'web' | 'extension' | 'desktop';\n/** What the person chooses to put in the token beyond the account identifier. */\nexport type OidcReveal = 'email' | 'profile';\n\nexport interface OidcProvider {\n id: OidcProviderId;\n name: string;\n /** Exact `iss`. Microsoft's contains the tenant: see `issuerFor`. */\n issuer: string;\n /** Other spellings the provider documents for the same issuer. */\n issuerAliases?: string[];\n discovery: string;\n authorizationEndpoint: string;\n /** Pinned rather than discovered, so a changed discovery document cannot redirect key lookup. */\n jwksUri: string;\n /** Only for `code`: the token endpoint, reached with PKCE and no secret. */\n tokenEndpoint?: string;\n /** Best effort after a `code` exchange: the access token Ghostly never wanted is revoked at once. */\n revocationEndpoint?: string;\n /** Pinned per provider; the token header's `alg` must be one of these. */\n algs: OidcAlg[];\n /**\n * `id_token` returns only the signed ID token in the fragment: no access\n * token, no code, nothing to exchange, so no secret. `code id_token` is\n * Apple's shape (its code needs a secret; Ghostly drops it). `code` is for\n * providers without an ID-token-only response, exchanged with PKCE.\n */\n responseType: 'id_token' | 'code id_token' | 'code';\n /** Which extra claims this provider can add, and the scope (or claims request) for each. */\n reveal: Partial<Record<OidcReveal, { scope?: string; claims?: string[] }>>;\n /** What the provider puts in the token whatever the person picks. Shown before sign-in. */\n alwaysIncluded: string;\n /**\n * Claims the provider adds on its own for some accounts that say more than the account, each with the\n * choice that already shares as much. The signature covers the whole token, so such a claim cannot be\n * stripped: a token carrying one the person did not choose to share is turned down before it is used.\n */\n disclosing?: Record<string, OidcReveal>;\n /** Extra authorization parameters, e.g. an account chooser. */\n extraParams?: Record<string, string>;\n /** Client IDs per platform. Desktop signs in through the web callback page, so it uses the web client. */\n clientIds: Partial<Record<OidcPlatform, string>>;\n}\n\nexport const TEST_ISSUER = /^https:\\/\\/[a-z0-9-]+(\\.[a-z0-9-]+)*\\.test$/;\nconst MICROSOFT_TENANT = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\n\nexport const OIDC_PROVIDERS: Record<Exclude<OidcProviderId, 'test'>, OidcProvider> = {\n google: {\n id: 'google', name: 'Google',\n issuer: 'https://accounts.google.com', issuerAliases: ['accounts.google.com'],\n discovery: 'https://accounts.google.com/.well-known/openid-configuration',\n authorizationEndpoint: 'https://accounts.google.com/o/oauth2/v2/auth',\n jwksUri: 'https://www.googleapis.com/oauth2/v3/certs',\n algs: ['RS256'], responseType: 'id_token',\n reveal: { email: { scope: 'email' }, profile: { scope: 'profile' } },\n alwaysIncluded: 'A Google account identifier. For a work or school account Google also adds its organisation’s domain, so one is only accepted with your email shared.',\n // `hd`: a Workspace or Cloud organisation account's domain, in every token Google signs for it.\n disclosing: { hd: 'email' },\n extraParams: { prompt: 'select_account' },\n clientIds: { web: '', extension: '' },\n },\n microsoft: {\n // `common` takes work, school and personal accounts; the issuer names the account's tenant.\n id: 'microsoft', name: 'Microsoft',\n issuer: 'https://login.microsoftonline.com/{tenantid}/v2.0',\n discovery: 'https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration',\n authorizationEndpoint: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',\n jwksUri: 'https://login.microsoftonline.com/common/discovery/v2.0/keys',\n algs: ['RS256'], responseType: 'id_token',\n reveal: { email: { scope: 'email' }, profile: { scope: 'profile' } },\n alwaysIncluded: 'A Microsoft account identifier and the directory (tenant) the account belongs to.',\n extraParams: { prompt: 'select_account', response_mode: 'fragment' },\n clientIds: { web: '', extension: '' },\n },\n apple: {\n // Apple only returns the ID token in the fragment when no scope is asked\n // for; name and email need `form_post`, which a static page cannot read.\n id: 'apple', name: 'Apple',\n issuer: 'https://appleid.apple.com',\n discovery: 'https://appleid.apple.com/.well-known/openid-configuration',\n authorizationEndpoint: 'https://appleid.apple.com/auth/authorize',\n jwksUri: 'https://appleid.apple.com/auth/keys',\n algs: ['RS256'], responseType: 'code id_token',\n reveal: {},\n alwaysIncluded: 'An Apple ID identifier that only Ghostly sees. Apple cannot add your email here without a Ghostly server.',\n extraParams: { response_mode: 'fragment' },\n clientIds: { web: '', extension: '' },\n },\n gitlab: {\n id: 'gitlab', name: 'GitLab',\n issuer: 'https://gitlab.com',\n discovery: 'https://gitlab.com/.well-known/openid-configuration',\n authorizationEndpoint: 'https://gitlab.com/oauth/authorize',\n tokenEndpoint: 'https://gitlab.com/oauth/token',\n revocationEndpoint: 'https://gitlab.com/oauth/revoke',\n jwksUri: 'https://gitlab.com/oauth/discovery/keys',\n algs: ['RS256'], responseType: 'code',\n reveal: { email: { scope: 'email' }, profile: { scope: 'profile' } },\n alwaysIncluded: 'A GitLab.com user ID and the groups you belong to directly: GitLab adds them to every ID token.',\n clientIds: { web: '', extension: '' },\n },\n twitch: {\n // Twitch's email claim needs `user:read:email`, an API scope: not asked for.\n id: 'twitch', name: 'Twitch',\n issuer: 'https://id.twitch.tv/oauth2',\n discovery: 'https://id.twitch.tv/oauth2/.well-known/openid-configuration',\n authorizationEndpoint: 'https://id.twitch.tv/oauth2/authorize',\n jwksUri: 'https://id.twitch.tv/oauth2/keys',\n algs: ['RS256'], responseType: 'id_token',\n reveal: { profile: { claims: ['preferred_username'] } },\n alwaysIncluded: 'A Twitch user ID.',\n extraParams: { force_verify: 'true' },\n clientIds: { web: '', extension: '' },\n },\n};\n\n/**\n * The local issuer the e2e suite runs (e2e/support/oidcIssuer.ts). It exists\n * only in a build made with VITE_OIDC_TEST_ISSUER, and only on a `.test` host\n * (a name reserved for testing, never a real issuer); a release build has no\n * such provider, so a token from it is refused like any unknown issuer.\n */\nexport function testProvider(issuer: string): OidcProvider {\n if (!TEST_ISSUER.test(issuer)) throw new Error('A test issuer lives on a .test host');\n const base = issuer;\n return {\n id: 'test', name: 'Test issuer', issuer: base,\n discovery: `${base}/.well-known/openid-configuration`,\n authorizationEndpoint: `${base}/authorize`,\n jwksUri: `${base}/jwks`,\n algs: ['RS256', 'ES256'], responseType: 'id_token',\n reveal: { email: { scope: 'email' }, profile: { scope: 'profile' } },\n alwaysIncluded: 'A test account identifier.',\n clientIds: { web: 'ghostly-e2e', extension: 'ghostly-e2e', desktop: 'ghostly-e2e' },\n };\n}\n\nfunction configuredTestIssuer(): string | undefined {\n try {\n const value = import.meta.env?.VITE_OIDC_TEST_ISSUER as string | undefined;\n return value && TEST_ISSUER.test(value) ? value : undefined;\n } catch { return undefined; }\n}\n\n/** Every provider this build knows, configured or not. */\nexport function oidcProviders(testIssuer = configuredTestIssuer()): OidcProvider[] {\n return [...Object.values(OIDC_PROVIDERS), ...(testIssuer ? [testProvider(testIssuer)] : [])];\n}\n\nexport function oidcProvider(id: string, testIssuer = configuredTestIssuer()): OidcProvider | undefined {\n return oidcProviders(testIssuer).find(p => p.id === id);\n}\n\n/** Every client ID this provider has, on any platform: a contact may use another platform than the prover. */\nexport function audiences(provider: OidcProvider): string[] {\n return [...new Set(Object.values(provider.clientIds).filter((id): id is string => !!id))];\n}\n\nexport function clientIdFor(provider: OidcProvider, platform: OidcPlatform): string {\n return provider.clientIds[platform] || provider.clientIds.web || '';\n}\n\n/** A provider is offered only once its client ID for this platform exists. */\nexport function isConfigured(provider: OidcProvider, platform: OidcPlatform): boolean {\n return !!clientIdFor(provider, platform);\n}\n\n/** The exact issuer a token from this provider must carry, or undefined when its claims do not name one. */\nexport function issuerFor(provider: OidcProvider, claims: { tid?: unknown }): string[] {\n if (provider.id !== 'microsoft') return [provider.issuer, ...(provider.issuerAliases ?? [])];\n return typeof claims.tid === 'string' && MICROSOFT_TENANT.test(claims.tid) ? [provider.issuer.replace('{tenantid}', claims.tid)] : [];\n}\n\n/** The provider a proof's subject (an issuer, as `OidcProvider.issuer` spells it) names. */\nexport function providerForIssuer(issuer: string, list = oidcProviders()): OidcProvider | undefined {\n return list.find(p => p.issuer === issuer);\n}\n","/**\n * Pkarr relays a Pubky key's records are read from: Pubky's own, the ones the Pubky SDK uses. A module of its own so\n * that naming them (`fixedHosts.ts`) does not bring `./pubky` into the entry: the web app's install leaves that chunk\n * to its first use (`apps/web/src/sw/policy.ts`).\n */\nexport const PUBKY_RELAYS: readonly string[] = [\"https://pkarr.pubky.org\", \"https://pkarr.pubky.app\"];\n","import { IdentityCheckUnavailable, parseSshPublicKey, sameSshKey, type SshPublicKey } from '@ghostly/core';\nimport type { IdentityFetch } from './contract';\n\n/** \"This account publishes that key\", without OAuth: GitHub and GitLab publish every account's SSH\n * public keys, and only the account holder can add one. The verifier's own lookup, through the\n * engine's bounded `ctx.fetch`; it tells the forge (and the network) which account was checked. */\n\nexport type SshForge = 'github' | 'gitlab';\nexport const SSH_FORGE_LABEL: Record<SshForge, string> = { github: 'GitHub', gitlab: 'GitLab' };\n/** The only host each forge lookup contacts, for the privacy line. */\nexport const SSH_FORGE_HOST: Record<SshForge, string> = { github: 'api.github.com', gitlab: 'gitlab.com' };\n\nexport type SshForgeStatus = 'linked' | 'not-listed' | 'no-account';\n\nconst MAX_BODY = 256 * 1024;\nconst MAX_KEYS = 200;\n\nexport function validForgeLogin(forge: SshForge, login: string): boolean {\n if (typeof login !== 'string') return false;\n // GitHub: 1-39 alphanumerics or single inner hyphens. GitLab: letters, digits, _ . - ;\n // not starting with - and not ending in .git/.atom. Capped at 64 so it fits every label.\n return forge === 'github'\n ? /^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$/.test(login)\n : /^[A-Za-z0-9_.][A-Za-z0-9_.-]{0,63}$/.test(login) && !/\\.(?:git|atom)$/i.test(login);\n}\n\n/** A forge that could not be asked (not reached, limiting lookups, an error or a page that is not its API) is IdentityCheckUnavailable: it says nothing about the key. */\nasync function get(fetcher: IdentityFetch, url: string, signal?: AbortSignal): Promise<{ status: 404 } | { status: 200; body: unknown }> {\n const host = new URL(url).host;\n let response: Awaited<ReturnType<IdentityFetch>>;\n try { response = await fetcher(url, { maxBytes: MAX_BODY, signal }); }\n catch (e) { throw e instanceof IdentityCheckUnavailable ? e : new IdentityCheckUnavailable(`${host} could not be reached: ${e instanceof Error ? e.message : String(e)}`); }\n if (response.status === 404) return { status: 404 };\n if (response.status === 403 || response.status === 429) throw new IdentityCheckUnavailable(`${host} is limiting lookups; check again later`);\n if (response.status !== 200) throw new IdentityCheckUnavailable(`${host} answered HTTP ${response.status}`);\n try { return { status: 200, body: JSON.parse(response.text) }; } catch { throw new IdentityCheckUnavailable(`Unexpected answer from ${host}`); }\n}\n\nfunction keysFrom(body: unknown): SshPublicKey[] {\n if (!Array.isArray(body)) throw new Error('Unexpected key list');\n const keys: SshPublicKey[] = [];\n for (const entry of body.slice(0, MAX_KEYS)) {\n const line = (entry as { key?: unknown } | null)?.key;\n if (typeof line !== 'string') continue;\n try { keys.push(parseSshPublicKey(line)); } catch { /* A key type Ghostly cannot verify never matches. */ }\n }\n return keys;\n}\n\n/** The account's published keys, or null when there is no such account. */\nasync function listKeys(forge: SshForge, login: string, fetcher: IdentityFetch, signal?: AbortSignal): Promise<SshPublicKey[] | null> {\n if (forge === 'github') {\n const r = await get(fetcher, `https://api.github.com/users/${encodeURIComponent(login)}/keys?per_page=100`, signal);\n return r.status === 404 ? null : keysFrom(r.body);\n }\n const users = await get(fetcher, `https://gitlab.com/api/v4/users?username=${encodeURIComponent(login)}`, signal);\n const list = users.status === 200 && Array.isArray(users.body) ? users.body as { id?: unknown; username?: unknown }[] : [];\n const user = list.find(u => typeof u?.username === 'string' && u.username.toLowerCase() === login.toLowerCase());\n if (!user) return null;\n if (!Number.isSafeInteger(user.id) || (user.id as number) <= 0) throw new Error('Unexpected answer from gitlab.com');\n const r = await get(fetcher, `https://gitlab.com/api/v4/users/${user.id as number}/keys?per_page=100`, signal);\n return r.status === 404 ? null : keysFrom(r.body);\n}\n\n// Only concurrent identical lookups share a request. What stays checked is the verifier's stored\n// result, which the app offers to re-check once the provider's `recheck` time has passed.\nconst inFlight = new WeakMap<IdentityFetch, Map<string, Promise<SshPublicKey[] | null>>>();\n\n/** Whether `key` is one of `login`'s published SSH keys. Throws when the forge cannot be asked. */\nexport async function checkSshForge(forge: SshForge, login: string, key: Pick<SshPublicKey, 'blob'>, fetcher: IdentityFetch, signal?: AbortSignal): Promise<SshForgeStatus> {\n if (!validForgeLogin(forge, login)) throw new Error(`Not a ${SSH_FORGE_LABEL[forge]} username`);\n let pending = inFlight.get(fetcher);\n if (!pending) inFlight.set(fetcher, pending = new Map());\n const map = pending, id = `${forge}:${login.toLowerCase()}`;\n let lookup = map.get(id);\n if (!lookup) {\n lookup = listKeys(forge, login, fetcher, signal).finally(() => map.delete(id));\n map.set(id, lookup);\n }\n const keys = await lookup;\n if (!keys) return 'no-account';\n return keys.some(k => sameSshKey(k, key)) ? 'linked' : 'not-listed';\n}\n"],"mappings":";;;;;;;;;;;AAWA,IAAa,mBAAmB;;AAEhC,IAAa,mBAAmB;;AAEhC,IAAa,qBAAqB;AAClC,IAAM,eAAe;AACrB,IAAM,eAAe;AACrB,IAAM,qBAAqB;AAC3B,IAAM,kBAAkB;AACxB,IAAM,mBAAmB;AAKzB,IAAa,gBAAuC;CAAC;CAAe;CAAuB;CAAuB;CAChH;CAAW;CAA8B;AAAoC;AAsB/E,IAAa,c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,"file":"sshForges-Cfu-dSwc.js","names":[],"sources":["../../../core/src/sshsig.ts","../../../browser/src/proofs/oidc/providers.ts","../../../browser/src/proofs/pubkyRelays.ts","../../../browser/src/proofs/sshForges.ts"],"sourcesContent":["import { ed25519 } from '@noble/curves/ed25519.js';\nimport { p256, p384, p521 } from '@noble/curves/nist.js';\nimport { sha256, sha512 } from '@noble/hashes/sha2.js';\nimport { bytesEqual, concatBytes, fromBase64, toBase64, utf8Decode, utf8Encode } from './bytes';\n\n/** OpenSSH signatures over a Ghostly statement (`ssh-keygen -Y sign -n ghostly`),\n * following PROTOCOL.sshsig. Everything here is local: parsing, the public key\n * the signature names and the signature itself. Which key a person *should*\n * have signed with is the caller's question (an expected fingerprint, or a\n * key list published by a forge; see the browser proof provider). */\n\nexport const SSHSIG_NAMESPACE = 'ghostly';\n/** A pasted armored signature: an 8192-bit RSA key plus its signature is ~3 KB. */\nexport const SSHSIG_MAX_ARMOR = 6144;\n/** A pasted `.pub` line; comments are dropped. */\nexport const SSH_PUBLIC_KEY_MAX = 4096;\nconst RSA_MIN_BITS = 2048;\nconst RSA_MAX_BITS = 8192;\nconst SK_APPLICATION_MAX = 256;\nconst SK_USER_PRESENT = 0x01;\nconst SK_USER_VERIFIED = 0x04;\n\nexport type SshKeyType =\n | 'ssh-ed25519' | 'ecdsa-sha2-nistp256' | 'ecdsa-sha2-nistp384' | 'ecdsa-sha2-nistp521' | 'ssh-rsa'\n | 'sk-ssh-ed25519@openssh.com' | 'sk-ecdsa-sha2-nistp256@openssh.com';\nexport const SSH_KEY_TYPES: readonly SshKeyType[] = ['ssh-ed25519', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', 'ecdsa-sha2-nistp521',\n 'ssh-rsa', 'sk-ssh-ed25519@openssh.com', 'sk-ecdsa-sha2-nistp256@openssh.com'];\n\nexport interface SshPublicKey {\n type: SshKeyType;\n /** The wire-format key blob, which is what fingerprints and forge key lists name. */\n blob: Uint8Array;\n /** `SHA256:` + unpadded base64, exactly as `ssh-keygen -l` prints it. */\n fingerprint: string;\n /** `type base64`, the form `.pub` files and forge key lists use (no comment). */\n line: string;\n /** Security keys only: the FIDO application, `ssh:` unless chosen at creation. */\n application?: string;\n /** RSA modulus size. */\n bits?: number;\n}\nexport interface SshSignatureCheck {\n key: SshPublicKey;\n hashAlgorithm: 'sha256' | 'sha512';\n /** Security keys only: what the authenticator asserted for this signature. */\n securityKey?: { userPresent: boolean; userVerified: boolean; counter: number };\n}\n\nexport class SshSigError extends Error {}\nconst fail = (message: string): never => { throw new SshSigError(message); };\n\nclass Reader {\n private at = 0;\n constructor(private bytes: Uint8Array) {}\n get done() { return this.at === this.bytes.length; }\n raw(n: number): Uint8Array {\n if (n > this.bytes.length - this.at) fail('Truncated SSH data');\n return this.bytes.subarray(this.at, this.at += n);\n }\n u8(): number { return this.raw(1)[0]; }\n u32(): number { const b = this.raw(4); return ((b[0] << 24) >>> 0) + (b[1] << 16) + (b[2] << 8) + b[3]; }\n string(max = this.bytes.length): Uint8Array {\n const n = this.u32();\n if (n > max) fail('SSH field too long');\n return this.raw(n);\n }\n text(max: number): string {\n const b = this.string(max);\n if (!b.every(c => c >= 0x20 && c < 0x7f)) fail('SSH name is not printable ASCII');\n return utf8Decode(b);\n }\n /** Positive mpint in canonical form: no redundant leading zero, sign bit clear. */\n mpint(maxBytes: number): Uint8Array {\n const b = this.string(maxBytes + 1);\n if (!b.length || b[0] & 0x80 || (b[0] === 0 && (b.length === 1 || !(b[1] & 0x80)))) fail('Non-canonical SSH integer');\n return b[0] === 0 ? b.subarray(1) : b;\n }\n end() { if (!this.done) fail('Trailing bytes in SSH data'); }\n}\nconst u32 = (n: number) => Uint8Array.of(n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255);\nconst sshString = (b: Uint8Array) => concatBytes(u32(b.length), b);\n\nfunction strictBase64(text: string, max: number): Uint8Array {\n if (text.length > max || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(text)) fail('Invalid base64');\n const bytes = fromBase64(text);\n if (toBase64(bytes) !== text) fail('Non-canonical base64');\n return bytes;\n}\nexport function sshFingerprint(blob: Uint8Array): string {\n return `SHA256:${toBase64(sha256(blob)).replace(/=+$/, '')}`;\n}\n\ninterface CurveInfo { name: string; curve: typeof p256 | typeof p384 | typeof p521; size: number }\nconst CURVES: Record<string, CurveInfo> = {\n 'ecdsa-sha2-nistp256': { name: 'nistp256', curve: p256, size: 32 },\n 'ecdsa-sha2-nistp384': { name: 'nistp384', curve: p384, size: 48 },\n 'ecdsa-sha2-nistp521': { name: 'nistp521', curve: p521, size: 66 },\n 'sk-ecdsa-sha2-nistp256@openssh.com': { name: 'nistp256', curve: p256, size: 32 },\n};\ninterface ParsedKey extends SshPublicKey { point?: Uint8Array; rsa?: { n: Uint8Array; e: Uint8Array } }\n\nfunction parseKeyBlob(blob: Uint8Array): ParsedKey {\n if (blob.length > 1100) fail('SSH public key too large');\n const r = new Reader(blob);\n const type = r.text(64) as SshKeyType;\n // Named only when it is DSA, a type older OpenSSH made: any other type is words the key's owner chose.\n if (!SSH_KEY_TYPES.includes(type)) fail(`Unsupported SSH key type${(type as string) === 'ssh-dss' ? ' \"ssh-dss\"' : ''}`);\n const key: ParsedKey = { type, blob, fingerprint: sshFingerprint(blob), line: `${type} ${toBase64(blob)}` };\n if (type === 'ssh-ed25519' || type === 'sk-ssh-ed25519@openssh.com') {\n key.point = r.string(32);\n if (key.point.length !== 32) fail('Invalid Ed25519 public key');\n try { ed25519.Point.fromBytes(key.point, false).assertValidity(); } catch { fail('Invalid Ed25519 public key'); }\n } else if (type === 'ssh-rsa') {\n const e = r.mpint(8), n = r.mpint(RSA_MAX_BITS / 8);\n const bits = (n.length - 1) * 8 + (32 - Math.clz32(n[0]));\n if (bits < RSA_MIN_BITS || bits > RSA_MAX_BITS) fail(`RSA keys must be ${RSA_MIN_BITS}-${RSA_MAX_BITS} bits`);\n if (!(e[e.length - 1] & 1) || (e.length === 1 && e[0] < 3)) fail('Invalid RSA exponent');\n key.rsa = { n, e }; key.bits = bits;\n } else {\n const info = CURVES[type];\n if (r.text(16) !== info.name) fail('ECDSA curve does not match the key type');\n key.point = r.string(1 + 2 * info.size);\n if (key.point.length !== 1 + 2 * info.size || key.point[0] !== 4) fail('Invalid ECDSA public key');\n try { info.curve.Point.fromBytes(key.point).assertValidity(); } catch { fail('Invalid ECDSA public key'); }\n }\n if (type.startsWith('sk-')) key.application = r.text(SK_APPLICATION_MAX);\n r.end();\n return key;\n}\n\n/** Parses one `.pub` style line (`type base64 [comment]`). */\nexport function parseSshPublicKey(line: string): SshPublicKey {\n if (typeof line !== 'string' || line.length > SSH_PUBLIC_KEY_MAX) fail('SSH public key too long');\n // Trimmed first: a pattern that ends in `[^\\n]*\\s*` tries every split of a run of spaces between the two.\n const m = /^(\\S+)\\s+(\\S+)(?:\\s[^\\n]*)?$/.exec(line.trim());\n if (!m) fail('Paste one SSH public key line (the contents of a .pub file)');\n const key = parseKeyBlob(strictBase64(m![2], SSH_PUBLIC_KEY_MAX));\n if (key.type !== m![1]) fail('SSH key type does not match its data');\n return publicView(key);\n}\nconst publicView = ({ type, blob, fingerprint, line, application, bits }: ParsedKey): SshPublicKey =>\n ({ type, blob, fingerprint, line, ...(application !== undefined ? { application } : {}), ...(bits ? { bits } : {}) });\n\ninterface ParsedSignature { key: ParsedKey; namespace: string; hashAlgorithm: 'sha256' | 'sha512'; signature: Uint8Array }\n\n/** Unwraps `-----BEGIN SSH SIGNATURE-----` armor and the SSHSIG envelope, without verifying. */\nexport function parseSshSignature(armored: string): ParsedSignature {\n if (typeof armored !== 'string' || armored.length > SSHSIG_MAX_ARMOR) fail('SSH signature too long');\n const lines = armored.replace(/\\r\\n/g, '\\n').trim().split('\\n').map(l => l.trim());\n if (lines.length < 3 || lines[0] !== '-----BEGIN SSH SIGNATURE-----' || lines[lines.length - 1] !== '-----END SSH SIGNATURE-----')\n fail('Paste the whole signature, from -----BEGIN SSH SIGNATURE----- to -----END SSH SIGNATURE-----');\n const r = new Reader(strictBase64(lines.slice(1, -1).join(''), SSHSIG_MAX_ARMOR));\n if (!bytesEqual(r.raw(6), utf8Encode('SSHSIG'))) fail('Not an SSH signature');\n if (r.u32() !== 1) fail('Unsupported SSH signature version');\n const key = parseKeyBlob(r.string(1100));\n const namespace = r.text(64);\n if (r.string(64).length) fail('Unsupported SSH signature extension');\n const hashAlgorithm = r.text(16) as ParsedSignature['hashAlgorithm'];\n if (hashAlgorithm !== 'sha256' && hashAlgorithm !== 'sha512') fail('SSH signature hash must be sha256 or sha512');\n const signature = r.string(1200);\n r.end();\n return { key, namespace, hashAlgorithm, signature };\n}\n\nasync function verifyRsa(key: ParsedKey, hash: 'SHA-256' | 'SHA-512', sig: Uint8Array, data: Uint8Array): Promise<boolean> {\n const n = key.rsa!.n, size = n.length;\n if (sig.length > size) return false;\n const padded = new Uint8Array(size); padded.set(sig, size - sig.length);\n const b64u = (b: Uint8Array) => toBase64(b).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n const cryptoKey = await crypto.subtle.importKey('jwk', { kty: 'RSA', n: b64u(n), e: b64u(key.rsa!.e), ext: true },\n { name: 'RSASSA-PKCS1-v1_5', hash }, false, ['verify']);\n return crypto.subtle.verify('RSASSA-PKCS1-v1_5', cryptoKey, padded, new Uint8Array(data));\n}\n\nfunction ecdsaSignature(blob: Uint8Array, size: number): Uint8Array {\n const r = new Reader(blob);\n const a = r.mpint(size), b = r.mpint(size);\n r.end();\n const out = new Uint8Array(2 * size);\n out.set(a, size - a.length); out.set(b, 2 * size - b.length);\n return out;\n}\n\n/** Verifies an armored SSHSIG over `message` in `namespace` and returns the key that\n * made it. Throws SshSigError for anything malformed, mismatched or unverifiable.\n * Security-key signatures must assert user presence (a touch) unless explicitly\n * allowed otherwise, matching OpenSSH's default for keys created without\n * `no-touch-required`. */\nexport async function verifySshSignature(armored: string, message: Uint8Array | string, options: { namespace?: string; allowNoTouch?: boolean } = {}): Promise<SshSignatureCheck> {\n const parsed = parseSshSignature(armored);\n const namespace = options.namespace ?? SSHSIG_NAMESPACE;\n // Never the signature's own namespace: the reason is shown on the checking side, and the signer chose those words.\n if (parsed.namespace !== namespace) fail(`Signed for another namespace, not ${JSON.stringify(namespace)}. Use -n ${namespace}.`);\n const bytes = typeof message === 'string' ? utf8Encode(message) : message;\n const digest = parsed.hashAlgorithm === 'sha512' ? sha512(bytes) : sha256(bytes);\n const signed = concatBytes(utf8Encode('SSHSIG'), sshString(utf8Encode(parsed.namespace)), sshString(new Uint8Array()),\n sshString(utf8Encode(parsed.hashAlgorithm)), sshString(digest));\n const { key } = parsed;\n const r = new Reader(parsed.signature);\n const algorithm = r.text(64);\n const blob = r.string(RSA_MAX_BITS / 8);\n let securityKey: SshSignatureCheck['securityKey'];\n let data = signed;\n if (key.type.startsWith('sk-')) {\n const flags = r.u8(), counter = r.u32();\n securityKey = { userPresent: !!(flags & SK_USER_PRESENT), userVerified: !!(flags & SK_USER_VERIFIED), counter };\n data = concatBytes(sha256(utf8Encode(key.application!)), Uint8Array.of(flags), u32(counter), sha256(signed));\n }\n r.end();\n const verifyWith = async (): Promise<boolean> => {\n if (key.type === 'ssh-rsa') {\n if (algorithm !== 'rsa-sha2-512' && algorithm !== 'rsa-sha2-256') fail('RSA signatures must use rsa-sha2-256 or rsa-sha2-512');\n return verifyRsa(key, algorithm === 'rsa-sha2-512' ? 'SHA-512' : 'SHA-256', blob, data);\n }\n if (algorithm !== key.type) fail('Signature algorithm does not match the key');\n if (key.type === 'ssh-ed25519' || key.type === 'sk-ssh-ed25519@openssh.com')\n return blob.length === 64 && ed25519.verify(blob, data, key.point!, { zip215: false });\n const info = CURVES[key.type];\n return info.curve.verify(ecdsaSignature(blob, info.size), data, key.point!, { lowS: false, prehash: true });\n };\n let ok: boolean;\n try { ok = await verifyWith(); } catch (e) { if (e instanceof SshSigError) throw e; ok = false; }\n if (!ok) fail('The signature does not match this statement');\n if (securityKey && !securityKey.userPresent && !options.allowNoTouch) fail('The security key did not confirm a touch for this signature');\n return { key: publicView(key), hashAlgorithm: parsed.hashAlgorithm, ...(securityKey ? { securityKey } : {}) };\n}\n\n/** Whether two keys are the same, comparing wire blobs (comments never matter). */\nexport const sameSshKey = (a: Pick<SshPublicKey, 'blob'>, b: Pick<SshPublicKey, 'blob'>) => bytesEqual(a.blob, b.blob);\n\n/** 32-byte digest of the key blob as lowercase hex: the fingerprint's bytes, in the\n * shape peer-proof external keys already use. */\nexport const sshKeyDigestHex = (key: Pick<SshPublicKey, 'blob'>) =>\n Array.from(sha256(key.blob), b => b.toString(16).padStart(2, '0')).join('');\n\n/** A POSIX shell one-liner that signs `statement` exactly (no trailing newline) and\n * prints the armored signature. Refuses anything that would need escaping, so what\n * is shown is what gets signed. */\nexport function sshSignCommand(statement: string, keyPath = '~/.ssh/id_ed25519'): string {\n if (/['\\\\\\n\\r]/.test(statement)) fail('Statement cannot be quoted for a shell');\n if (!/^[\\w~./@+-]{1,256}$/.test(keyPath)) fail('Use a plain key path without spaces or quotes');\n return `printf '%s' '${statement}' | ssh-keygen -Y sign -n ${SSHSIG_NAMESPACE} -f ${keyPath}`;\n}\n","/**\n * The OpenID Connect providers Ghostly can ask for a signed ID token. A contact\n * verifies that token against the provider's published keys, with no Ghostly\n * server in between, so a provider is only listed when its ID tokens are signed\n * and its keys and sign-in page are reachable from a browser without a client\n * secret. See docs/wisps/3xx-oidc-proofs.md for the providers that are not\n * (Facebook, X, LinkedIn, GitHub) and why.\n *\n * Client IDs are public configuration, identical in every build, because the\n * contact's app checks `aud` against them. They stay empty until the OAuth\n * clients are registered (docs/OIDC-PROVIDERS.md); a provider without a client\n * ID is neither offered nor accepted.\n */\n\nexport type OidcProviderId = 'google' | 'microsoft' | 'apple' | 'gitlab' | 'twitch' | 'test';\nexport type OidcAlg = 'RS256' | 'ES256';\nexport type OidcPlatform = 'web' | 'extension' | 'desktop';\n/** What the person chooses to put in the token beyond the account identifier. */\nexport type OidcReveal = 'email' | 'profile';\n\nexport interface OidcProvider {\n id: OidcProviderId;\n name: string;\n /** Exact `iss`. Microsoft's contains the tenant: see `issuerFor`. */\n issuer: string;\n /** Other spellings the provider documents for the same issuer. */\n issuerAliases?: string[];\n discovery: string;\n authorizationEndpoint: string;\n /** Pinned rather than discovered, so a changed discovery document cannot redirect key lookup. */\n jwksUri: string;\n /** Only for `code`: the token endpoint, reached with PKCE and no secret. */\n tokenEndpoint?: string;\n /** Best effort after a `code` exchange: the access token Ghostly never wanted is revoked at once. */\n revocationEndpoint?: string;\n /** Pinned per provider; the token header's `alg` must be one of these. */\n algs: OidcAlg[];\n /**\n * `id_token` returns only the signed ID token in the fragment: no access\n * token, no code, nothing to exchange, so no secret. `code id_token` is\n * Apple's shape (its code needs a secret; Ghostly drops it). `code` is for\n * providers without an ID-token-only response, exchanged with PKCE.\n */\n responseType: 'id_token' | 'code id_token' | 'code';\n /** Which extra claims this provider can add, and the scope (or claims request) for each. */\n reveal: Partial<Record<OidcReveal, { scope?: string; claims?: string[] }>>;\n /** What the provider puts in the token whatever the person picks. Shown before sign-in. */\n alwaysIncluded: string;\n /**\n * Claims the provider adds on its own for some accounts that say more than the account, each with the\n * choice that already shares as much. The signature covers the whole token, so such a claim cannot be\n * stripped: a token carrying one the person did not choose to share is turned down before it is used.\n */\n disclosing?: Record<string, OidcReveal>;\n /** Extra authorization parameters, e.g. an account chooser. */\n extraParams?: Record<string, string>;\n /** Client IDs per platform. Desktop signs in through the web callback page, so it uses the web client. */\n clientIds: Partial<Record<OidcPlatform, string>>;\n}\n\nexport const TEST_ISSUER = /^https:\\/\\/[a-z0-9-]+(\\.[a-z0-9-]+)*\\.test$/;\nconst MICROSOFT_TENANT = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\n\nexport const OIDC_PROVIDERS: Record<Exclude<OidcProviderId, 'test'>, OidcProvider> = {\n google: {\n id: 'google', name: 'Google',\n issuer: 'https://accounts.google.com', issuerAliases: ['accounts.google.com'],\n discovery: 'https://accounts.google.com/.well-known/openid-configuration',\n authorizationEndpoint: 'https://accounts.google.com/o/oauth2/v2/auth',\n jwksUri: 'https://www.googleapis.com/oauth2/v3/certs',\n algs: ['RS256'], responseType: 'id_token',\n reveal: { email: { scope: 'email' }, profile: { scope: 'profile' } },\n alwaysIncluded: 'A Google account identifier. For a work or school account Google also adds its organisation’s domain, so one is only accepted with your email shared.',\n // `hd`: a Workspace or Cloud organisation account's domain, in every token Google signs for it.\n disclosing: { hd: 'email' },\n extraParams: { prompt: 'select_account' },\n clientIds: { web: '', extension: '' },\n },\n microsoft: {\n // `common` takes work, school and personal accounts; the issuer names the account's tenant.\n id: 'microsoft', name: 'Microsoft',\n issuer: 'https://login.microsoftonline.com/{tenantid}/v2.0',\n discovery: 'https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration',\n authorizationEndpoint: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',\n jwksUri: 'https://login.microsoftonline.com/common/discovery/v2.0/keys',\n algs: ['RS256'], responseType: 'id_token',\n reveal: { email: { scope: 'email' }, profile: { scope: 'profile' } },\n alwaysIncluded: 'A Microsoft account identifier and the directory (tenant) the account belongs to.',\n extraParams: { prompt: 'select_account', response_mode: 'fragment' },\n clientIds: { web: '', extension: '' },\n },\n apple: {\n // Apple only returns the ID token in the fragment when no scope is asked\n // for; name and email need `form_post`, which a static page cannot read.\n id: 'apple', name: 'Apple',\n issuer: 'https://appleid.apple.com',\n discovery: 'https://appleid.apple.com/.well-known/openid-configuration',\n authorizationEndpoint: 'https://appleid.apple.com/auth/authorize',\n jwksUri: 'https://appleid.apple.com/auth/keys',\n algs: ['RS256'], responseType: 'code id_token',\n reveal: {},\n alwaysIncluded: 'An Apple ID identifier that only Ghostly sees. Apple cannot add your email here without a Ghostly server.',\n extraParams: { response_mode: 'fragment' },\n clientIds: { web: '', extension: '' },\n },\n gitlab: {\n id: 'gitlab', name: 'GitLab',\n issuer: 'https://gitlab.com',\n discovery: 'https://gitlab.com/.well-known/openid-configuration',\n authorizationEndpoint: 'https://gitlab.com/oauth/authorize',\n tokenEndpoint: 'https://gitlab.com/oauth/token',\n revocationEndpoint: 'https://gitlab.com/oauth/revoke',\n jwksUri: 'https://gitlab.com/oauth/discovery/keys',\n algs: ['RS256'], responseType: 'code',\n reveal: { email: { scope: 'email' }, profile: { scope: 'profile' } },\n alwaysIncluded: 'A GitLab.com user ID and the groups you belong to directly: GitLab adds them to every ID token.',\n clientIds: { web: '', extension: '' },\n },\n twitch: {\n // Twitch's email claim needs `user:read:email`, an API scope: not asked for.\n id: 'twitch', name: 'Twitch',\n issuer: 'https://id.twitch.tv/oauth2',\n discovery: 'https://id.twitch.tv/oauth2/.well-known/openid-configuration',\n authorizationEndpoint: 'https://id.twitch.tv/oauth2/authorize',\n jwksUri: 'https://id.twitch.tv/oauth2/keys',\n algs: ['RS256'], responseType: 'id_token',\n reveal: { profile: { claims: ['preferred_username'] } },\n alwaysIncluded: 'A Twitch user ID.',\n extraParams: { force_verify: 'true' },\n clientIds: { web: '', extension: '' },\n },\n};\n\n/**\n * The local issuer the e2e suite runs (e2e/support/oidcIssuer.ts). It exists\n * only in a build made with VITE_OIDC_TEST_ISSUER, and only on a `.test` host\n * (a name reserved for testing, never a real issuer); a release build has no\n * such provider, so a token from it is refused like any unknown issuer.\n */\nexport function testProvider(issuer: string): OidcProvider {\n if (!TEST_ISSUER.test(issuer)) throw new Error('A test issuer lives on a .test host');\n const base = issuer;\n return {\n id: 'test', name: 'Test issuer', issuer: base,\n discovery: `${base}/.well-known/openid-configuration`,\n authorizationEndpoint: `${base}/authorize`,\n jwksUri: `${base}/jwks`,\n algs: ['RS256', 'ES256'], responseType: 'id_token',\n reveal: { email: { scope: 'email' }, profile: { scope: 'profile' } },\n alwaysIncluded: 'A test account identifier.',\n clientIds: { web: 'ghostly-e2e', extension: 'ghostly-e2e', desktop: 'ghostly-e2e' },\n };\n}\n\nfunction configuredTestIssuer(): string | undefined {\n try {\n const value = import.meta.env?.VITE_OIDC_TEST_ISSUER as string | undefined;\n return value && TEST_ISSUER.test(value) ? value : undefined;\n } catch { return undefined; }\n}\n\n/** Every provider this build knows, configured or not. */\nexport function oidcProviders(testIssuer = configuredTestIssuer()): OidcProvider[] {\n return [...Object.values(OIDC_PROVIDERS), ...(testIssuer ? [testProvider(testIssuer)] : [])];\n}\n\nexport function oidcProvider(id: string, testIssuer = configuredTestIssuer()): OidcProvider | undefined {\n return oidcProviders(testIssuer).find(p => p.id === id);\n}\n\n/** Every client ID this provider has, on any platform: a contact may use another platform than the prover. */\nexport function audiences(provider: OidcProvider): string[] {\n return [...new Set(Object.values(provider.clientIds).filter((id): id is string => !!id))];\n}\n\nexport function clientIdFor(provider: OidcProvider, platform: OidcPlatform): string {\n return provider.clientIds[platform] || provider.clientIds.web || '';\n}\n\n/** A provider is offered only once its client ID for this platform exists. */\nexport function isConfigured(provider: OidcProvider, platform: OidcPlatform): boolean {\n return !!clientIdFor(provider, platform);\n}\n\n/** The exact issuer a token from this provider must carry, or undefined when its claims do not name one. */\nexport function issuerFor(provider: OidcProvider, claims: { tid?: unknown }): string[] {\n if (provider.id !== 'microsoft') return [provider.issuer, ...(provider.issuerAliases ?? [])];\n return typeof claims.tid === 'string' && MICROSOFT_TENANT.test(claims.tid) ? [provider.issuer.replace('{tenantid}', claims.tid)] : [];\n}\n\n/** The provider a proof's subject (an issuer, as `OidcProvider.issuer` spells it) names. */\nexport function providerForIssuer(issuer: string, list = oidcProviders()): OidcProvider | undefined {\n return list.find(p => p.issuer === issuer);\n}\n","/**\n * Pkarr relays a Pubky key's records are read from: Pubky's own, the ones the Pubky SDK uses. A module of its own so\n * that naming them (`fixedHosts.ts`) does not bring `./pubky` into the entry: the web app's install leaves that chunk\n * to its first use (`apps/web/src/sw/policy.ts`).\n */\nexport const PUBKY_RELAYS: readonly string[] = [\"https://pkarr.pubky.org\", \"https://pkarr.pubky.app\"];\n","import { IdentityCheckUnavailable, parseSshPublicKey, sameSshKey, type SshPublicKey } from '@ghostly/core';\nimport type { IdentityFetch } from './contract';\n\n/** \"This account publishes that key\", without OAuth: GitHub and GitLab publish every account's SSH\n * public keys, and only the account holder can add one. The verifier's own lookup, through the\n * engine's bounded `ctx.fetch`; it tells the forge (and the network) which account was checked. */\n\nexport type SshForge = 'github' | 'gitlab';\nexport const SSH_FORGE_LABEL: Record<SshForge, string> = { github: 'GitHub', gitlab: 'GitLab' };\n/** The only host each forge lookup contacts, for the privacy line. */\nexport const SSH_FORGE_HOST: Record<SshForge, string> = { github: 'api.github.com', gitlab: 'gitlab.com' };\n\nexport type SshForgeStatus = 'linked' | 'not-listed' | 'no-account';\n\nconst MAX_BODY = 256 * 1024;\nconst MAX_KEYS = 200;\n\nexport function validForgeLogin(forge: SshForge, login: string): boolean {\n if (typeof login !== 'string') return false;\n // GitHub: 1-39 alphanumerics or single inner hyphens. GitLab: letters, digits, _ . - ;\n // not starting with - and not ending in .git/.atom. Capped at 64 so it fits every label.\n return forge === 'github'\n ? /^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$/.test(login)\n : /^[A-Za-z0-9_.][A-Za-z0-9_.-]{0,63}$/.test(login) && !/\\.(?:git|atom)$/i.test(login);\n}\n\n/** A forge that could not be asked (not reached, limiting lookups, an error or a page that is not its API) is IdentityCheckUnavailable: it says nothing about the key. */\nasync function get(fetcher: IdentityFetch, url: string, signal?: AbortSignal): Promise<{ status: 404 } | { status: 200; body: unknown }> {\n const host = new URL(url).host;\n let response: Awaited<ReturnType<IdentityFetch>>;\n try { response = await fetcher(url, { maxBytes: MAX_BODY, signal }); }\n catch (e) { throw e instanceof IdentityCheckUnavailable ? e : new IdentityCheckUnavailable(`${host} could not be reached: ${e instanceof Error ? e.message : String(e)}`); }\n if (response.status === 404) return { status: 404 };\n if (response.status === 403 || response.status === 429) throw new IdentityCheckUnavailable(`${host} is limiting lookups; check again later`);\n if (response.status !== 200) throw new IdentityCheckUnavailable(`${host} answered HTTP ${response.status}`);\n try { return { status: 200, body: JSON.parse(response.text) }; } catch { throw new IdentityCheckUnavailable(`Unexpected answer from ${host}`); }\n}\n\nfunction keysFrom(body: unknown): SshPublicKey[] {\n if (!Array.isArray(body)) throw new Error('Unexpected key list');\n const keys: SshPublicKey[] = [];\n for (const entry of body.slice(0, MAX_KEYS)) {\n const line = (entry as { key?: unknown } | null)?.key;\n if (typeof line !== 'string') continue;\n try { keys.push(parseSshPublicKey(line)); } catch { /* A key type Ghostly cannot verify never matches. */ }\n }\n return keys;\n}\n\n/** The account's published keys, or null when there is no such account. */\nasync function listKeys(forge: SshForge, login: string, fetcher: IdentityFetch, signal?: AbortSignal): Promise<SshPublicKey[] | null> {\n if (forge === 'github') {\n const r = await get(fetcher, `https://api.github.com/users/${encodeURIComponent(login)}/keys?per_page=100`, signal);\n return r.status === 404 ? null : keysFrom(r.body);\n }\n const users = await get(fetcher, `https://gitlab.com/api/v4/users?username=${encodeURIComponent(login)}`, signal);\n const list = users.status === 200 && Array.isArray(users.body) ? users.body as { id?: unknown; username?: unknown }[] : [];\n const user = list.find(u => typeof u?.username === 'string' && u.username.toLowerCase() === login.toLowerCase());\n if (!user) return null;\n if (!Number.isSafeInteger(user.id) || (user.id as number) <= 0) throw new Error('Unexpected answer from gitlab.com');\n const r = await get(fetcher, `https://gitlab.com/api/v4/users/${user.id as number}/keys?per_page=100`, signal);\n return r.status === 404 ? null : keysFrom(r.body);\n}\n\n// Only concurrent identical lookups share a request. What stays checked is the verifier's stored\n// result, which the app offers to re-check once the provider's `recheck` time has passed.\nconst inFlight = new WeakMap<IdentityFetch, Map<string, Promise<SshPublicKey[] | null>>>();\n\n/** Whether `key` is one of `login`'s published SSH keys. Throws when the forge cannot be asked. */\nexport async function checkSshForge(forge: SshForge, login: string, key: Pick<SshPublicKey, 'blob'>, fetcher: IdentityFetch, signal?: AbortSignal): Promise<SshForgeStatus> {\n if (!validForgeLogin(forge, login)) throw new Error(`Not a ${SSH_FORGE_LABEL[forge]} username`);\n let pending = inFlight.get(fetcher);\n if (!pending) inFlight.set(fetcher, pending = new Map());\n const map = pending, id = `${forge}:${login.toLowerCase()}`;\n let lookup = map.get(id);\n if (!lookup) {\n lookup = listKeys(forge, login, fetcher, signal).finally(() => map.delete(id));\n map.set(id, lookup);\n }\n const keys = await lookup;\n if (!keys) return 'no-account';\n return keys.some(k => sameSshKey(k, key)) ? 'linked' : 'not-listed';\n}\n"],"mappings":";;;;;;;;;;;AAWA,IAAa,mBAAmB;;AAEhC,IAAa,mBAAmB;;AAEhC,IAAa,qBAAqB;AAClC,IAAM,eAAe;AACrB,IAAM,eAAe;AACrB,IAAM,qBAAqB;AAC3B,IAAM,kBAAkB;AACxB,IAAM,mBAAmB;AAKzB,IAAa,gBAAuC;CAAC;CAAe;CAAuB;CAAuB;CAChH;CAAW;CAA8B;AAAoC;AAsB/E,IAAa,cAAb,cAAiC,MAAM,CAAC;AACxC,IAAM,QAAQ,YAA2B;CAAE,MAAM,IAAI,YAAY,OAAO;AAAG;AAE3E,IAAM,SAAN,MAAa;CAES;CADpB,KAAa;CACb,YAAY,OAA2B;EAAnB,KAAA,QAAA;CAAoB;CACxC,IAAI,OAAO;EAAE,OAAO,KAAK,OAAO,KAAK,MAAM;CAAQ;CACnD,IAAI,GAAuB;EACzB,IAAI,IAAI,KAAK,MAAM,SAAS,KAAK,IAAI,KAAK,oBAAoB;EAC9D,OAAO,KAAK,MAAM,SAAS,KAAK,IAAI,KAAK,MAAM,CAAC;CAClD;CACA,KAAa;EAAE,OAAO,KAAK,IAAI,CAAC,CAAC,CAAC;CAAI;CACtC,MAAc;EAAE,MAAM,IAAI,KAAK,IAAI,CAAC;EAAG,QAAS,EAAE,MAAM,OAAQ,MAAM,EAAE,MAAM,OAAO,EAAE,MAAM,KAAK,EAAE;CAAI;CACxG,OAAO,MAAM,KAAK,MAAM,QAAoB;EAC1C,MAAM,IAAI,KAAK,IAAI;EACnB,IAAI,IAAI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K,IAAI,CAAC,gBAAgB,OAAO,KAAK,GAAG,MAAM,IAAI,MAAM,SAAS,gBAAgB,OAAO,UAAU;CAC9F,IAAI,UAAU,SAAS,IAAI,OAAO;CAClC,IAAI,CAAC,SAAS,SAAS,IAAI,SAAS,0BAAU,IAAI,IAAI,CAAC;CACvD,MAAM,MAAM,SAAS,KAAK,GAAG,MAAM,GAAG,MAAM,YAAY;CACxD,IAAI,SAAS,IAAI,IAAI,EAAE;CACvB,IAAI,CAAC,QAAQ;EACX,SAAS,SAAS,OAAO,OAAO,SAAS,MAAM,CAAC,CAAC,cAAc,IAAI,OAAO,EAAE,CAAC;EAC7E,IAAI,IAAI,IAAI,MAAM;CACpB;CACA,MAAM,OAAO,MAAM;CACnB,IAAI,CAAC,MAAM,OAAO;CAClB,OAAO,KAAK,MAAK,MAAK,WAAW,GAAG,GAAG,CAAC,IAAI,WAAW;AACzD"}
@@ -1,6 +1,6 @@
1
1
  import { a as SEPOLIA_TEST_USDT, c as USDT_PUBLIC_RPC, h as validatePaymentTarget, i as PaymentPreflightError, n as EVM_TEST_CHAINS, o as SEPOLIA_TEST_USDT_FAUCET, s as TEST_USDT_FAUCET_AMOUNT } from "./paymentIntent-Cr3uZa_0.js";
2
2
  import { r as engineError } from "./engineErrors-wWlLy54D.js";
3
- import { a as sealSeed, n as rpcHost, o as unsealSeed, t as networkReason } from "./networkReason-DYlPZS5M.js";
3
+ import { a as sealSeed, n as rpcHost, o as unsealSeed, t as networkReason } from "./networkReason-C6LYbjF2.js";
4
4
  import { mnemonicToSeedWebcrypto } from "@scure/bip39";
5
5
  import WalletManagerEvm from "@tetherto/wdk-wallet-evm";
6
6
  import { Interface, Transaction, getAddress, keccak256 } from "ethers";
@@ -410,4 +410,4 @@ var UsdtAdapter = class UsdtAdapter {
410
410
  };
411
411
  export { UsdtAdapter, wireProvider };
412
412
 
413
- //# sourceMappingURL=usdt-DLmtf8F9.js.map
413
+ //# sourceMappingURL=usdt-BkO4SY07.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"usdt-DLmtf8F9.js","names":[],"sources":["../../../browser/src/engine/paymentAdapters/usdt.ts"],"sourcesContent":["import { mnemonicToSeedWebcrypto } from '@scure/bip39';\nimport WalletManagerEvm, { type WalletAccountEvm } from '@tetherto/wdk-wallet-evm';\nimport { Interface, Transaction, getAddress, keccak256 } from 'ethers';\nimport { ETHEREUM_USDT, EVM_TEST_CHAINS, USDT_PUBLIC_RPC, SEPOLIA_TEST_USDT, SEPOLIA_TEST_USDT_FAUCET, TEST_USDT_FAUCET_AMOUNT, PaymentPreflightError, engineError, validatePaymentTarget, type PaymentAdapter, type PaymentExecution, type PaymentReview, type PaymentTarget } from '@ghostly/core';\nimport { sealSeed, unsealSeed, type EncryptedSeed } from './persistence';\nimport { networkReason, rpcHost } from './networkReason';\n\nexport interface UsdtConfig {\n network: 'ethereum' | 'sepolia' | 'evm-local';\n provider: string;\n chainId: 1 | 11155111 | 31337;\n token: string;\n decimals: number;\n codeHash: string;\n}\nexport interface UsdtPrepared {\n from: string; to: string; data: string; value: string; chainId: number; nonce: number;\n gasLimit: string; maxFeePerGas: string; maxPriorityFeePerGas: string;\n signed?: EncryptedSeed; hash?: string;\n}\nconst faucet = new Interface(['function mint(address token,address to,uint256 amount) returns (uint256)']);\nconst erc20 = new Interface(['function decimals() view returns(uint8)', 'function balanceOf(address) view returns(uint256)', 'function transfer(address,uint256) returns(bool)', 'event Transfer(address indexed from,address indexed to,uint256 value)']);\nconst same = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();\nconst CONFIRMATIONS = 2;\n/** The JSON-RPC methods that only read: asked again once when they fail (see `UsdtAdapter.rpc`). */\nconst RETRIED_READS = new Set(['eth_chainId', 'eth_getCode', 'eth_call', 'eth_getBalance', 'eth_blockNumber', 'eth_getLogs', 'eth_getTransactionCount', 'eth_estimateGas', 'eth_getBlockByNumber', 'eth_maxPriorityFeePerGas', 'eth_gasPrice', 'eth_feeHistory', 'eth_getTransactionByHash', 'eth_getTransactionReceipt']);\nconst RETRY_AFTER_MS = 1000;\n/** Failures that would fail the same way again at once: not retried. */\nconst FINAL = new WeakSet<object>();\nconst timedOut = (error: unknown) => error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError');\n\n/**\n * The `provider` a request carries to the contact. Which RPC pays is the payer's own choice, so it names none of\n * this wallet's: a typed RPC URL may hold an API key (`/v3/<key>`), and every contact would read it. Older apps\n * require a URL here and pay only when it equals their own RPC, so it is the chain's public RPC (the default both\n * start with), and a local test chain's origin, without its path.\n */\nexport function wireProvider(config: Pick<UsdtConfig, 'network' | 'provider'>): string {\n return config.network === 'evm-local' ? new URL(config.provider).origin : USDT_PUBLIC_RPC[config.network];\n}\n\n/** WDK signs locally. Every network call uses the configured RPC, never a peer-supplied URL. */\nexport class UsdtAdapter implements PaymentAdapter<UsdtPrepared> {\n readonly method = 'usdt' as const;\n private manager?: WalletManagerEvm;\n private account?: WalletAccountEvm;\n private mnemonic = '';\n private nextId = 0;\n private queue: Promise<unknown> = Promise.resolve();\n private constructor(readonly config: UsdtConfig) {}\n\n static async inspect(config: Omit<UsdtConfig, 'decimals' | 'codeHash'>): Promise<UsdtConfig> {\n if (config.network === 'ethereum' ? config.chainId !== 1 || !same(config.token, ETHEREUM_USDT) : !(config.network in EVM_TEST_CHAINS) || config.chainId !== EVM_TEST_CHAINS[config.network]) throw new Error('Unsupported USDT network or contract');\n const token = getAddress(config.token);\n const url = new URL(config.provider);\n if (url.username || url.password || url.search || url.hash || (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost','127.0.0.1','[::1]'].includes(url.hostname)))) throw new Error('Use HTTPS or a loopback test RPC');\n const adapter = new UsdtAdapter({...config, token, decimals: 6, codeHash: ''});\n await adapter.chain();\n const code = await adapter.rpc<string>('eth_getCode', [token, 'latest']);\n if (code === '0x') throw new Error('No token contract exists on this chain');\n const result = await adapter.rpc<string>('eth_call', [{to: token, data: erc20.encodeFunctionData('decimals')}, 'latest']);\n const decimals = Number(erc20.decodeFunctionResult('decimals', result)[0]);\n if (!Number.isInteger(decimals) || decimals < 0 || decimals > 18 || (config.chainId === 1 && decimals !== 6)) throw new Error('Unexpected token decimals');\n return {...config, token, decimals, codeHash: keccak256(code)};\n }\n static async connect(config: UsdtConfig, mnemonic: string): Promise<UsdtAdapter> {\n const inspected = await UsdtAdapter.inspect(config);\n if (inspected.decimals !== config.decimals || inspected.codeHash !== config.codeHash) throw new Error('Token metadata changed; do not use this wallet configuration');\n const adapter = new UsdtAdapter(config);\n adapter.mnemonic = mnemonic;\n // Pass standard BIP-39 seed bytes: WDK's string helper assumes a Node Buffer global. Its 2,048 rounds of PBKDF2 go to\n // the browser's own (WebCrypto), off the page's thread: in script they held it at every start, about 80 ms on a\n // slow phone, for a wallet that opens by itself.\n const seed = await mnemonicToSeedWebcrypto(mnemonic);\n try { adapter.manager = new WalletManagerEvm(seed, {provider: {request: ({method, params}) => adapter.rpc(method, params as unknown[] ?? [])}, chainId: config.chainId}); } finally { seed.fill(0); }\n adapter.account = await adapter.manager.getAccount(0);\n return adapter;\n }\n /**\n * A read that fails is asked again, once, a moment later: a public RPC drops a request now and then, and a chain that\n * just made a block can refuse a read of \"latest\" it no longer holds. Without it a network switch, a restore or New\n * gave up on the first such answer. Never a broadcast or anything else that writes, nor a request that did not answer\n * in time (the person would wait twice as long), nor one the server refused as such (4xx).\n */\n async rpc<T>(method: string, params: unknown[] = []): Promise<T> {\n try { return await this.ask<T>(method, params); }\n catch (error) {\n if (!RETRIED_READS.has(method) || FINAL.has(error as object)) throw error;\n await new Promise((resolve) => setTimeout(resolve, RETRY_AFTER_MS));\n return this.ask<T>(method, params);\n }\n }\n private async ask<T>(method: string, params: unknown[]): Promise<T> {\n let response: Response;\n // The browser's words for a request that got no answer (\"Fetch is aborted\") say nothing: the RPC's host does.\n try { response = await fetch(this.config.provider, {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({jsonrpc:'2.0',id:++this.nextId,method,params}), signal:AbortSignal.timeout(15000)}); }\n catch (error) {\n const reason = networkReason(error, rpcHost(this.config.provider));\n const thrown = reason ? Object.assign(new Error(reason), {cause: error}) : error;\n if (timedOut(error) && thrown && typeof thrown === 'object') FINAL.add(thrown);\n throw thrown;\n }\n if (!response.ok) { const error = engineError('usdtRpcUnavailable'); if (response.status !== 429 && response.status < 500) FINAL.add(error); throw error; }\n const result = await response.json();\n if (result.error || !Object.prototype.hasOwnProperty.call(result, 'result')) throw new Error('USDT RPC rejected the operation');\n return result.result as T;\n }\n private async chain() {\n if (BigInt(await this.rpc<string>('eth_chainId')) !== BigInt(this.config.chainId)) throw new Error('RPC chain does not match this wallet');\n }\n private async assertToken() {\n await this.chain();\n const code = await this.rpc<string>('eth_getCode', [this.config.token, 'latest']);\n if (code === '0x' || keccak256(code) !== this.config.codeHash) throw new Error('Token contract changed');\n }\n /**\n * Sepolia only: asks Aave's public faucet for test USDT, to this wallet, paid with its own test ETH.\n * Everything is fixed here (chain, contract, token, amount, recipient): nothing comes from outside.\n */\n mintTestTokens(): Promise<string> { return this.serial(async () => {\n if (this.config.chainId !== EVM_TEST_CHAINS.sepolia || !same(this.config.token, SEPOLIA_TEST_USDT)) throw new Error('Test USDT comes from a faucet on Sepolia only');\n await this.chain();\n const account = this.current(), from = await account.getAddress();\n const data = faucet.encodeFunctionData('mint', [SEPOLIA_TEST_USDT, from, BigInt(TEST_USDT_FAUCET_AMOUNT)]);\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount', [from, 'pending'])));\n const estimate = BigInt(await this.rpc<string>('eth_estimateGas', [{ from, to: SEPOLIA_TEST_USDT_FAUCET, data, value: '0x0' }]));\n const block = await this.rpc<{ baseFeePerGas?: string }>('eth_getBlockByNumber', ['latest', false]);\n if (!block.baseFeePerGas) throw new Error('This wallet requires an EIP-1559 chain');\n const priority = BigInt(await this.rpc<string>('eth_maxPriorityFeePerGas'));\n const maxFeePerGas = BigInt(block.baseFeePerGas) * 2n + priority, gasLimit = (estimate * 120n + 99n) / 100n;\n if (BigInt((await this.balances()).gasBalance) < gasLimit * maxFeePerGas) throw engineError('usdtNeedsSepoliaGas');\n const raw = await account.signTransaction({ type: 2, to: SEPOLIA_TEST_USDT_FAUCET, data, value: 0n, chainId: this.config.chainId, nonce, gasLimit, maxFeePerGas, maxPriorityFeePerGas: priority });\n await account.sendTransaction(raw);\n return Transaction.from(raw).hash!;\n }); }\n private current(): WalletAccountEvm { if (!this.account) throw new Error('Unlock the USDT wallet first'); return this.account; }\n address() { return this.current().getAddress(); }\n /**\n * The token and gas balances. The chain and the contract are not asked again here: `connect` checked them, and every\n * payment does before it signs. The wallet reads this every 8 s, and the contract's whole code was most of each read.\n */\n async balances() {\n const address = await this.address();\n const [token, gas] = await Promise.all([this.rpc<string>('eth_call',[{to:this.config.token,data:erc20.encodeFunctionData('balanceOf',[address])},'latest']),this.rpc<string>('eth_getBalance',[address,'pending'])]);\n return {balance:erc20.decodeFunctionResult('balanceOf',token)[0].toString(),gasBalance:BigInt(gas).toString()};\n }\n async target(): Promise<PaymentTarget> {\n const now = Date.now();\n return {method:'usdt',network:this.config.network,provider:wireProvider(this.config),asset:this.config.chainId === 1 ? 'USDT':'TEST-USDT',unit:'token-base',address:await this.address(),chainId:this.config.chainId,token:this.config.token,decimals:this.config.decimals,issuedAt:now,expiresAt:now+15*60*1000};\n }\n /** The request is for this wallet's token on its chain. Its `provider` is not compared: this wallet's own RPC pays. */\n private matches(target: PaymentTarget) {\n validatePaymentTarget(target);\n if (target.method !== 'usdt' || target.network !== this.config.network || target.chainId !== this.config.chainId || !same(target.token!,this.config.token) || target.decimals !== this.config.decimals) throw new Error('Request does not match the configured token and network');\n }\n prepare(target: PaymentTarget, amount: number, feeCap: number) { return this.serial(async () => {\n this.matches(target);\n await this.assertToken();\n const from = await this.address(), to = this.config.token;\n if (same(target.address, from) || same(target.address, to)) throw new Error('Choose a different recipient address');\n const {balance,gasBalance} = await this.balances();\n if (BigInt(balance) < BigInt(amount)) throw engineError('usdtNotEnoughTokens');\n const data = erc20.encodeFunctionData('transfer', [getAddress(target.address),BigInt(amount)]);\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount',[from,'pending'])));\n if (!Number.isSafeInteger(nonce)) throw new Error('Invalid account nonce');\n const estimate = BigInt(await this.rpc<string>('eth_estimateGas',[{from,to,data,value:'0x0'}]));\n const block = await this.rpc<{baseFeePerGas?:string}>('eth_getBlockByNumber',['latest',false]);\n if (!block.baseFeePerGas) throw new Error('This wallet requires an EIP-1559 chain');\n const priority = BigInt(await this.rpc<string>('eth_maxPriorityFeePerGas'));\n const maxFee = BigInt(block.baseFeePerGas)*2n + priority;\n const gasLimit = (estimate*120n+99n)/100n;\n const maximum = gasLimit*maxFee;\n if (maximum > BigInt(feeCap) || maximum > BigInt(Number.MAX_SAFE_INTEGER)) throw engineError('usdtGasAboveLimit');\n if (BigInt(gasBalance) < maximum) throw engineError('usdtNotEnoughGas');\n const prepared:UsdtPrepared = {from,to,data,value:'0',chainId:this.config.chainId,nonce,gasLimit:gasLimit.toString(),maxFeePerGas:maxFee.toString(),maxPriorityFeePerGas:priority.toString()};\n return {fee:Number(maximum),prepared,evm:{from,nonce,gasLimit:prepared.gasLimit,maxFeePerGas:prepared.maxFeePerGas,maxPriorityFeePerGas:prepared.maxPriorityFeePerGas,confirmations:CONFIRMATIONS}};\n }); }\n private verifyPrepared(review: PaymentReview, tx: UsdtPrepared) {\n if (tx.chainId !== this.config.chainId || !same(tx.to,this.config.token) || tx.value !== '0' || tx.data !== erc20.encodeFunctionData('transfer',[getAddress(review.address),BigInt(review.amount)]) || BigInt(tx.gasLimit)*BigInt(tx.maxFeePerGas) !== BigInt(review.fee) || review.fee > review.feeCap || tx.nonce !== review.evm?.nonce || !same(tx.from,review.evm?.from ?? '')) throw new Error('Transaction no longer matches the approved review');\n }\n private verifySigned(raw: string, saved: UsdtPrepared) {\n const tx = Transaction.from(raw);\n if (!tx.hash || !tx.from || !same(tx.from,saved.from) || tx.chainId !== BigInt(saved.chainId) || !tx.to || !same(tx.to,saved.to) || tx.data !== saved.data || tx.value !== 0n || tx.nonce !== saved.nonce || tx.gasLimit !== BigInt(saved.gasLimit) || tx.maxFeePerGas !== BigInt(saved.maxFeePerGas) || tx.maxPriorityFeePerGas !== BigInt(saved.maxPriorityFeePerGas)) throw new Error('Signature does not match the approved transaction');\n return tx.hash;\n }\n execute(review: PaymentReview, prepared: UsdtPrepared, persist?:()=>Promise<void>) { return this.serial(async () => {\n let account:WalletAccountEvm;\n try {\n this.matches(review); this.verifyPrepared(review,prepared);\n await this.assertToken(); account=this.current();\n if (!same(await account.getAddress(),prepared.from)) throw new Error('Wrong wallet');\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount',[prepared.from,'pending'])));\n if (nonce !== prepared.nonce) throw new Error('Account nonce changed. Create a new review');\n const balances = await this.balances();\n if (BigInt(balances.balance)<BigInt(review.amount) || BigInt(balances.gasBalance)<BigInt(review.fee)) throw new Error('Token or gas balance changed. Create a new review');\n if (!persist) throw new Error('Durable payment journal required');\n } catch (error) { throw new PaymentPreflightError(error instanceof Error ? error.message : 'Could not validate payment'); }\n const raw = await account.signTransaction({type:2,to:prepared.to,data:prepared.data,value:0n,chainId:prepared.chainId,nonce:prepared.nonce,gasLimit:BigInt(prepared.gasLimit),maxFeePerGas:BigInt(prepared.maxFeePerGas),maxPriorityFeePerGas:BigInt(prepared.maxPriorityFeePerGas)});\n prepared.hash = this.verifySigned(raw,prepared);\n prepared.signed = await sealSeed(raw,this.mnemonic);\n await persist!(); // Nothing may broadcast before the encrypted bytes are durable.\n await account.sendTransaction(raw);\n return this.receipt(prepared.hash,review,prepared.from);\n }); }\n reconcile(review: PaymentReview, prepared: UsdtPrepared) { return this.serial(async () => {\n await this.assertToken(); this.verifyPrepared(review,prepared);\n if (!prepared.signed || !prepared.hash) return {settled:false,failed:true,error:'No signed transaction was submitted. Create a new review.'};\n const result = await this.receipt(prepared.hash,review,prepared.from);\n if (result.settled || result.failed || result.pending) return result;\n // An uncertain network response permits only replay of exactly the saved bytes.\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount',[prepared.from,'pending'])));\n if (nonce > prepared.nonce) return result;\n const raw = await unsealSeed(prepared.signed,this.mnemonic);\n if (this.verifySigned(raw,prepared) !== prepared.hash || !same(await this.address(),prepared.from)) throw new Error('Recovery wallet mismatch');\n await this.current().sendTransaction(raw);\n return this.receipt(prepared.hash,review,prepared.from);\n }); }\n async receipt(hash: string, target: PaymentTarget & {amount:number}, expectedFrom?:string): Promise<PaymentExecution> {\n if (!/^0x[0-9a-fA-F]{64}$/.test(hash) || target.chainId !== this.config.chainId || !same(target.token ?? '',this.config.token) || target.decimals !== this.config.decimals) throw new Error('Invalid receipt target');\n await this.assertToken();\n const tx = await this.rpc<{from:string;to:string;input:string;value:string;nonce:string}|null>('eth_getTransactionByHash',[hash]);\n if (!tx) return {txid:hash,settled:false};\n if (!same(tx.to,this.config.token) || (expectedFrom && !same(tx.from,expectedFrom)) || BigInt(tx.value)!==0n || tx.input !== erc20.encodeFunctionData('transfer',[getAddress(target.address),BigInt(target.amount)])) throw new Error('Transaction is not the requested token transfer');\n const receipt = await this.rpc<{status:string;blockNumber:string;blockHash:string;logs:Array<{address:string;topics:string[];data:string}>}|null>('eth_getTransactionReceipt',[hash]);\n if (!receipt) return {txid:hash,settled:false,pending:true};\n const block = await this.rpc<{hash:string;timestamp:string}>('eth_getBlockByNumber',[receipt.blockNumber,false]);\n if (!block || block.hash !== receipt.blockHash || BigInt(block.timestamp)*1000n < BigInt((target.issuedAt ?? 0)-1000)) return {txid:hash,settled:false};\n const height = BigInt(await this.rpc<string>('eth_blockNumber'));\n if (height-BigInt(receipt.blockNumber)+1n < BigInt(CONFIRMATIONS)) return {txid:hash,settled:false,pending:true};\n if (BigInt(receipt.status)!==1n) return {txid:hash,settled:false,failed:true,error:'Transaction reverted. Tokens were not sent; gas was spent.'};\n const transfer = receipt.logs.some(log=>{\n if (!same(log.address,this.config.token)) return false;\n try {const event=erc20.parseLog(log);return event?.name==='Transfer' && same(event.args[0],tx.from) && same(event.args[1],target.address) && event.args[2]===BigInt(target.amount);} catch {return false;}\n });\n if (!transfer) throw new Error('Receipt has no matching token Transfer');\n return {txid:hash,settled:true};\n }\n async dispose() { await this.queue.catch(()=>{}); this.account=undefined;this.manager?.dispose();this.manager=undefined;this.mnemonic=''; }\n private serial<T>(work:()=>Promise<T>):Promise<T> { const operation=this.queue.then(work,work);this.queue=operation.catch(()=>{});return operation; }\n}\n"],"mappings":";;;;;;;AAoBA,IAAM,SAAS,IAAI,UAAU,CAAC,0EAA0E,CAAC;AACzG,IAAM,QAAQ,IAAI,UAAU;CAAC;CAA2C;CAAqD;CAAoD;AAAuE,CAAC;AACzP,IAAM,QAAQ,GAAW,MAAc,EAAE,YAAY,MAAM,EAAE,YAAY;AACzE,IAAM,gBAAgB;;AAEtB,IAAM,gCAAgB,IAAI,IAAI;CAAC;CAAe;CAAe;CAAY;CAAkB;CAAmB;CAAe;CAA2B;CAAmB;CAAwB;CAA4B;CAAgB;CAAkB;CAA4B;AAA2B,CAAC;AACzT,IAAM,iBAAiB;;AAEvB,IAAM,wBAAQ,IAAI,QAAgB;AAClC,IAAM,YAAY,UAAmB,iBAAiB,UAAU,MAAM,SAAS,gBAAgB,MAAM,SAAS;;;;;;;AAQ9G,SAAgB,aAAa,QAA0D;CACrF,OAAO,OAAO,YAAY,cAAc,IAAI,IAAI,OAAO,QAAQ,CAAC,CAAC,SAAS,gBAAgB,OAAO;AACnG;;AAGA,IAAa,cAAb,MAAa,YAAoD;CAOlC;CAN7B,SAAkB;CAClB;CACA;CACA,WAAmB;CACnB,SAAiB;CACjB,QAAkC,QAAQ,QAAQ;CAClD,YAAoB,QAA6B;EAApB,KAAA,SAAA;CAAqB;CAElD,aAAa,QAAQ,QAAwE;EAC3F,IAAI,OAAO,YAAY,aAAa,OAAO,YAAY,KAAK,CAAC,KAAK,OAAO,OAAA,4CAAoB,IAAI,EAAE,OAAO,WAAW,oBA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,IAAI,CAAC,KAAK,IAAI,SAAQ,KAAK,OAAO,KAAK,GAAG,OAAO;GACjD,IAAI;IAAC,MAAM,QAAM,MAAM,SAAS,GAAG;IAAE,OAAO,OAAO,SAAO,cAAc,KAAK,MAAM,KAAK,IAAG,GAAG,IAAI,KAAK,KAAK,MAAM,KAAK,IAAG,OAAO,OAAO,KAAK,MAAM,KAAK,OAAK,OAAO,OAAO,MAAM;GAAE,QAAQ;IAAC,OAAO;GAAM;EAC3M,CACK,GAAU,MAAM,IAAI,MAAM,wCAAwC;EACvE,OAAO;GAAC,MAAK;GAAK,SAAQ;EAAI;CAChC;CACA,MAAM,UAAU;EAAE,MAAM,KAAK,MAAM,YAAU,CAAC,CAAC;EAAG,KAAK,UAAQ,KAAA;EAAU,KAAK,SAAS,QAAQ;EAAE,KAAK,UAAQ,KAAA;EAAU,KAAK,WAAS;CAAI;CAC1I,OAAkB,MAAgC;EAAE,MAAM,YAAU,KAAK,MAAM,KAAK,MAAK,IAAI;EAAE,KAAK,QAAM,UAAU,YAAU,CAAC,CAAC;EAAE,OAAO;CAAW;AACtJ"}
1
+ {"version":3,"file":"usdt-BkO4SY07.js","names":[],"sources":["../../../browser/src/engine/paymentAdapters/usdt.ts"],"sourcesContent":["import { mnemonicToSeedWebcrypto } from '@scure/bip39';\nimport WalletManagerEvm, { type WalletAccountEvm } from '@tetherto/wdk-wallet-evm';\nimport { Interface, Transaction, getAddress, keccak256 } from 'ethers';\nimport { ETHEREUM_USDT, EVM_TEST_CHAINS, USDT_PUBLIC_RPC, SEPOLIA_TEST_USDT, SEPOLIA_TEST_USDT_FAUCET, TEST_USDT_FAUCET_AMOUNT, PaymentPreflightError, engineError, validatePaymentTarget, type PaymentAdapter, type PaymentExecution, type PaymentReview, type PaymentTarget } from '@ghostly/core';\nimport { sealSeed, unsealSeed, type EncryptedSeed } from './persistence';\nimport { networkReason, rpcHost } from './networkReason';\n\nexport interface UsdtConfig {\n network: 'ethereum' | 'sepolia' | 'evm-local';\n provider: string;\n chainId: 1 | 11155111 | 31337;\n token: string;\n decimals: number;\n codeHash: string;\n}\nexport interface UsdtPrepared {\n from: string; to: string; data: string; value: string; chainId: number; nonce: number;\n gasLimit: string; maxFeePerGas: string; maxPriorityFeePerGas: string;\n signed?: EncryptedSeed; hash?: string;\n}\nconst faucet = new Interface(['function mint(address token,address to,uint256 amount) returns (uint256)']);\nconst erc20 = new Interface(['function decimals() view returns(uint8)', 'function balanceOf(address) view returns(uint256)', 'function transfer(address,uint256) returns(bool)', 'event Transfer(address indexed from,address indexed to,uint256 value)']);\nconst same = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();\nconst CONFIRMATIONS = 2;\n/** The JSON-RPC methods that only read: asked again once when they fail (see `UsdtAdapter.rpc`). */\nconst RETRIED_READS = new Set(['eth_chainId', 'eth_getCode', 'eth_call', 'eth_getBalance', 'eth_blockNumber', 'eth_getLogs', 'eth_getTransactionCount', 'eth_estimateGas', 'eth_getBlockByNumber', 'eth_maxPriorityFeePerGas', 'eth_gasPrice', 'eth_feeHistory', 'eth_getTransactionByHash', 'eth_getTransactionReceipt']);\nconst RETRY_AFTER_MS = 1000;\n/** Failures that would fail the same way again at once: not retried. */\nconst FINAL = new WeakSet<object>();\nconst timedOut = (error: unknown) => error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError');\n\n/**\n * The `provider` a request carries to the contact. Which RPC pays is the payer's own choice, so it names none of\n * this wallet's: a typed RPC URL may hold an API key (`/v3/<key>`), and every contact would read it. Older apps\n * require a URL here and pay only when it equals their own RPC, so it is the chain's public RPC (the default both\n * start with), and a local test chain's origin, without its path.\n */\nexport function wireProvider(config: Pick<UsdtConfig, 'network' | 'provider'>): string {\n return config.network === 'evm-local' ? new URL(config.provider).origin : USDT_PUBLIC_RPC[config.network];\n}\n\n/** WDK signs locally. Every network call uses the configured RPC, never a peer-supplied URL. */\nexport class UsdtAdapter implements PaymentAdapter<UsdtPrepared> {\n readonly method = 'usdt' as const;\n private manager?: WalletManagerEvm;\n private account?: WalletAccountEvm;\n private mnemonic = '';\n private nextId = 0;\n private queue: Promise<unknown> = Promise.resolve();\n private constructor(readonly config: UsdtConfig) {}\n\n static async inspect(config: Omit<UsdtConfig, 'decimals' | 'codeHash'>): Promise<UsdtConfig> {\n if (config.network === 'ethereum' ? config.chainId !== 1 || !same(config.token, ETHEREUM_USDT) : !(config.network in EVM_TEST_CHAINS) || config.chainId !== EVM_TEST_CHAINS[config.network]) throw new Error('Unsupported USDT network or contract');\n const token = getAddress(config.token);\n const url = new URL(config.provider);\n if (url.username || url.password || url.search || url.hash || (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost','127.0.0.1','[::1]'].includes(url.hostname)))) throw new Error('Use HTTPS or a loopback test RPC');\n const adapter = new UsdtAdapter({...config, token, decimals: 6, codeHash: ''});\n await adapter.chain();\n const code = await adapter.rpc<string>('eth_getCode', [token, 'latest']);\n if (code === '0x') throw new Error('No token contract exists on this chain');\n const result = await adapter.rpc<string>('eth_call', [{to: token, data: erc20.encodeFunctionData('decimals')}, 'latest']);\n const decimals = Number(erc20.decodeFunctionResult('decimals', result)[0]);\n if (!Number.isInteger(decimals) || decimals < 0 || decimals > 18 || (config.chainId === 1 && decimals !== 6)) throw new Error('Unexpected token decimals');\n return {...config, token, decimals, codeHash: keccak256(code)};\n }\n static async connect(config: UsdtConfig, mnemonic: string): Promise<UsdtAdapter> {\n const inspected = await UsdtAdapter.inspect(config);\n if (inspected.decimals !== config.decimals || inspected.codeHash !== config.codeHash) throw new Error('Token metadata changed; do not use this wallet configuration');\n const adapter = new UsdtAdapter(config);\n adapter.mnemonic = mnemonic;\n // Pass standard BIP-39 seed bytes: WDK's string helper assumes a Node Buffer global. Its 2,048 rounds of PBKDF2 go to\n // the browser's own (WebCrypto), off the page's thread: in script they held it at every start, about 80 ms on a\n // slow phone, for a wallet that opens by itself.\n const seed = await mnemonicToSeedWebcrypto(mnemonic);\n try { adapter.manager = new WalletManagerEvm(seed, {provider: {request: ({method, params}) => adapter.rpc(method, params as unknown[] ?? [])}, chainId: config.chainId}); } finally { seed.fill(0); }\n adapter.account = await adapter.manager.getAccount(0);\n return adapter;\n }\n /**\n * A read that fails is asked again, once, a moment later: a public RPC drops a request now and then, and a chain that\n * just made a block can refuse a read of \"latest\" it no longer holds. Without it a network switch, a restore or New\n * gave up on the first such answer. Never a broadcast or anything else that writes, nor a request that did not answer\n * in time (the person would wait twice as long), nor one the server refused as such (4xx).\n */\n async rpc<T>(method: string, params: unknown[] = []): Promise<T> {\n try { return await this.ask<T>(method, params); }\n catch (error) {\n if (!RETRIED_READS.has(method) || FINAL.has(error as object)) throw error;\n await new Promise((resolve) => setTimeout(resolve, RETRY_AFTER_MS));\n return this.ask<T>(method, params);\n }\n }\n private async ask<T>(method: string, params: unknown[]): Promise<T> {\n let response: Response;\n // The browser's words for a request that got no answer (\"Fetch is aborted\") say nothing: the RPC's host does.\n try { response = await fetch(this.config.provider, {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({jsonrpc:'2.0',id:++this.nextId,method,params}), signal:AbortSignal.timeout(15000)}); }\n catch (error) {\n const reason = networkReason(error, rpcHost(this.config.provider));\n const thrown = reason ? Object.assign(new Error(reason), {cause: error}) : error;\n if (timedOut(error) && thrown && typeof thrown === 'object') FINAL.add(thrown);\n throw thrown;\n }\n if (!response.ok) { const error = engineError('usdtRpcUnavailable'); if (response.status !== 429 && response.status < 500) FINAL.add(error); throw error; }\n const result = await response.json();\n if (result.error || !Object.prototype.hasOwnProperty.call(result, 'result')) throw new Error('USDT RPC rejected the operation');\n return result.result as T;\n }\n private async chain() {\n if (BigInt(await this.rpc<string>('eth_chainId')) !== BigInt(this.config.chainId)) throw new Error('RPC chain does not match this wallet');\n }\n private async assertToken() {\n await this.chain();\n const code = await this.rpc<string>('eth_getCode', [this.config.token, 'latest']);\n if (code === '0x' || keccak256(code) !== this.config.codeHash) throw new Error('Token contract changed');\n }\n /**\n * Sepolia only: asks Aave's public faucet for test USDT, to this wallet, paid with its own test ETH.\n * Everything is fixed here (chain, contract, token, amount, recipient): nothing comes from outside.\n */\n mintTestTokens(): Promise<string> { return this.serial(async () => {\n if (this.config.chainId !== EVM_TEST_CHAINS.sepolia || !same(this.config.token, SEPOLIA_TEST_USDT)) throw new Error('Test USDT comes from a faucet on Sepolia only');\n await this.chain();\n const account = this.current(), from = await account.getAddress();\n const data = faucet.encodeFunctionData('mint', [SEPOLIA_TEST_USDT, from, BigInt(TEST_USDT_FAUCET_AMOUNT)]);\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount', [from, 'pending'])));\n const estimate = BigInt(await this.rpc<string>('eth_estimateGas', [{ from, to: SEPOLIA_TEST_USDT_FAUCET, data, value: '0x0' }]));\n const block = await this.rpc<{ baseFeePerGas?: string }>('eth_getBlockByNumber', ['latest', false]);\n if (!block.baseFeePerGas) throw new Error('This wallet requires an EIP-1559 chain');\n const priority = BigInt(await this.rpc<string>('eth_maxPriorityFeePerGas'));\n const maxFeePerGas = BigInt(block.baseFeePerGas) * 2n + priority, gasLimit = (estimate * 120n + 99n) / 100n;\n if (BigInt((await this.balances()).gasBalance) < gasLimit * maxFeePerGas) throw engineError('usdtNeedsSepoliaGas');\n const raw = await account.signTransaction({ type: 2, to: SEPOLIA_TEST_USDT_FAUCET, data, value: 0n, chainId: this.config.chainId, nonce, gasLimit, maxFeePerGas, maxPriorityFeePerGas: priority });\n await account.sendTransaction(raw);\n return Transaction.from(raw).hash!;\n }); }\n private current(): WalletAccountEvm { if (!this.account) throw new Error('Unlock the USDT wallet first'); return this.account; }\n address() { return this.current().getAddress(); }\n /**\n * The token and gas balances. The chain and the contract are not asked again here: `connect` checked them, and every\n * payment does before it signs. The wallet reads this every 8 s, and the contract's whole code was most of each read.\n */\n async balances() {\n const address = await this.address();\n const [token, gas] = await Promise.all([this.rpc<string>('eth_call',[{to:this.config.token,data:erc20.encodeFunctionData('balanceOf',[address])},'latest']),this.rpc<string>('eth_getBalance',[address,'pending'])]);\n return {balance:erc20.decodeFunctionResult('balanceOf',token)[0].toString(),gasBalance:BigInt(gas).toString()};\n }\n async target(): Promise<PaymentTarget> {\n const now = Date.now();\n return {method:'usdt',network:this.config.network,provider:wireProvider(this.config),asset:this.config.chainId === 1 ? 'USDT':'TEST-USDT',unit:'token-base',address:await this.address(),chainId:this.config.chainId,token:this.config.token,decimals:this.config.decimals,issuedAt:now,expiresAt:now+15*60*1000};\n }\n /** The request is for this wallet's token on its chain. Its `provider` is not compared: this wallet's own RPC pays. */\n private matches(target: PaymentTarget) {\n validatePaymentTarget(target);\n if (target.method !== 'usdt' || target.network !== this.config.network || target.chainId !== this.config.chainId || !same(target.token!,this.config.token) || target.decimals !== this.config.decimals) throw new Error('Request does not match the configured token and network');\n }\n prepare(target: PaymentTarget, amount: number, feeCap: number) { return this.serial(async () => {\n this.matches(target);\n await this.assertToken();\n const from = await this.address(), to = this.config.token;\n if (same(target.address, from) || same(target.address, to)) throw new Error('Choose a different recipient address');\n const {balance,gasBalance} = await this.balances();\n if (BigInt(balance) < BigInt(amount)) throw engineError('usdtNotEnoughTokens');\n const data = erc20.encodeFunctionData('transfer', [getAddress(target.address),BigInt(amount)]);\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount',[from,'pending'])));\n if (!Number.isSafeInteger(nonce)) throw new Error('Invalid account nonce');\n const estimate = BigInt(await this.rpc<string>('eth_estimateGas',[{from,to,data,value:'0x0'}]));\n const block = await this.rpc<{baseFeePerGas?:string}>('eth_getBlockByNumber',['latest',false]);\n if (!block.baseFeePerGas) throw new Error('This wallet requires an EIP-1559 chain');\n const priority = BigInt(await this.rpc<string>('eth_maxPriorityFeePerGas'));\n const maxFee = BigInt(block.baseFeePerGas)*2n + priority;\n const gasLimit = (estimate*120n+99n)/100n;\n const maximum = gasLimit*maxFee;\n if (maximum > BigInt(feeCap) || maximum > BigInt(Number.MAX_SAFE_INTEGER)) throw engineError('usdtGasAboveLimit');\n if (BigInt(gasBalance) < maximum) throw engineError('usdtNotEnoughGas');\n const prepared:UsdtPrepared = {from,to,data,value:'0',chainId:this.config.chainId,nonce,gasLimit:gasLimit.toString(),maxFeePerGas:maxFee.toString(),maxPriorityFeePerGas:priority.toString()};\n return {fee:Number(maximum),prepared,evm:{from,nonce,gasLimit:prepared.gasLimit,maxFeePerGas:prepared.maxFeePerGas,maxPriorityFeePerGas:prepared.maxPriorityFeePerGas,confirmations:CONFIRMATIONS}};\n }); }\n private verifyPrepared(review: PaymentReview, tx: UsdtPrepared) {\n if (tx.chainId !== this.config.chainId || !same(tx.to,this.config.token) || tx.value !== '0' || tx.data !== erc20.encodeFunctionData('transfer',[getAddress(review.address),BigInt(review.amount)]) || BigInt(tx.gasLimit)*BigInt(tx.maxFeePerGas) !== BigInt(review.fee) || review.fee > review.feeCap || tx.nonce !== review.evm?.nonce || !same(tx.from,review.evm?.from ?? '')) throw new Error('Transaction no longer matches the approved review');\n }\n private verifySigned(raw: string, saved: UsdtPrepared) {\n const tx = Transaction.from(raw);\n if (!tx.hash || !tx.from || !same(tx.from,saved.from) || tx.chainId !== BigInt(saved.chainId) || !tx.to || !same(tx.to,saved.to) || tx.data !== saved.data || tx.value !== 0n || tx.nonce !== saved.nonce || tx.gasLimit !== BigInt(saved.gasLimit) || tx.maxFeePerGas !== BigInt(saved.maxFeePerGas) || tx.maxPriorityFeePerGas !== BigInt(saved.maxPriorityFeePerGas)) throw new Error('Signature does not match the approved transaction');\n return tx.hash;\n }\n execute(review: PaymentReview, prepared: UsdtPrepared, persist?:()=>Promise<void>) { return this.serial(async () => {\n let account:WalletAccountEvm;\n try {\n this.matches(review); this.verifyPrepared(review,prepared);\n await this.assertToken(); account=this.current();\n if (!same(await account.getAddress(),prepared.from)) throw new Error('Wrong wallet');\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount',[prepared.from,'pending'])));\n if (nonce !== prepared.nonce) throw new Error('Account nonce changed. Create a new review');\n const balances = await this.balances();\n if (BigInt(balances.balance)<BigInt(review.amount) || BigInt(balances.gasBalance)<BigInt(review.fee)) throw new Error('Token or gas balance changed. Create a new review');\n if (!persist) throw new Error('Durable payment journal required');\n } catch (error) { throw new PaymentPreflightError(error instanceof Error ? error.message : 'Could not validate payment'); }\n const raw = await account.signTransaction({type:2,to:prepared.to,data:prepared.data,value:0n,chainId:prepared.chainId,nonce:prepared.nonce,gasLimit:BigInt(prepared.gasLimit),maxFeePerGas:BigInt(prepared.maxFeePerGas),maxPriorityFeePerGas:BigInt(prepared.maxPriorityFeePerGas)});\n prepared.hash = this.verifySigned(raw,prepared);\n prepared.signed = await sealSeed(raw,this.mnemonic);\n await persist!(); // Nothing may broadcast before the encrypted bytes are durable.\n await account.sendTransaction(raw);\n return this.receipt(prepared.hash,review,prepared.from);\n }); }\n reconcile(review: PaymentReview, prepared: UsdtPrepared) { return this.serial(async () => {\n await this.assertToken(); this.verifyPrepared(review,prepared);\n if (!prepared.signed || !prepared.hash) return {settled:false,failed:true,error:'No signed transaction was submitted. Create a new review.'};\n const result = await this.receipt(prepared.hash,review,prepared.from);\n if (result.settled || result.failed || result.pending) return result;\n // An uncertain network response permits only replay of exactly the saved bytes.\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount',[prepared.from,'pending'])));\n if (nonce > prepared.nonce) return result;\n const raw = await unsealSeed(prepared.signed,this.mnemonic);\n if (this.verifySigned(raw,prepared) !== prepared.hash || !same(await this.address(),prepared.from)) throw new Error('Recovery wallet mismatch');\n await this.current().sendTransaction(raw);\n return this.receipt(prepared.hash,review,prepared.from);\n }); }\n async receipt(hash: string, target: PaymentTarget & {amount:number}, expectedFrom?:string): Promise<PaymentExecution> {\n if (!/^0x[0-9a-fA-F]{64}$/.test(hash) || target.chainId !== this.config.chainId || !same(target.token ?? '',this.config.token) || target.decimals !== this.config.decimals) throw new Error('Invalid receipt target');\n await this.assertToken();\n const tx = await this.rpc<{from:string;to:string;input:string;value:string;nonce:string}|null>('eth_getTransactionByHash',[hash]);\n if (!tx) return {txid:hash,settled:false};\n if (!same(tx.to,this.config.token) || (expectedFrom && !same(tx.from,expectedFrom)) || BigInt(tx.value)!==0n || tx.input !== erc20.encodeFunctionData('transfer',[getAddress(target.address),BigInt(target.amount)])) throw new Error('Transaction is not the requested token transfer');\n const receipt = await this.rpc<{status:string;blockNumber:string;blockHash:string;logs:Array<{address:string;topics:string[];data:string}>}|null>('eth_getTransactionReceipt',[hash]);\n if (!receipt) return {txid:hash,settled:false,pending:true};\n const block = await this.rpc<{hash:string;timestamp:string}>('eth_getBlockByNumber',[receipt.blockNumber,false]);\n if (!block || block.hash !== receipt.blockHash || BigInt(block.timestamp)*1000n < BigInt((target.issuedAt ?? 0)-1000)) return {txid:hash,settled:false};\n const height = BigInt(await this.rpc<string>('eth_blockNumber'));\n if (height-BigInt(receipt.blockNumber)+1n < BigInt(CONFIRMATIONS)) return {txid:hash,settled:false,pending:true};\n if (BigInt(receipt.status)!==1n) return {txid:hash,settled:false,failed:true,error:'Transaction reverted. Tokens were not sent; gas was spent.'};\n const transfer = receipt.logs.some(log=>{\n if (!same(log.address,this.config.token)) return false;\n try {const event=erc20.parseLog(log);return event?.name==='Transfer' && same(event.args[0],tx.from) && same(event.args[1],target.address) && event.args[2]===BigInt(target.amount);} catch {return false;}\n });\n if (!transfer) throw new Error('Receipt has no matching token Transfer');\n return {txid:hash,settled:true};\n }\n async dispose() { await this.queue.catch(()=>{}); this.account=undefined;this.manager?.dispose();this.manager=undefined;this.mnemonic=''; }\n private serial<T>(work:()=>Promise<T>):Promise<T> { const operation=this.queue.then(work,work);this.queue=operation.catch(()=>{});return operation; }\n}\n"],"mappings":";;;;;;;AAoBA,IAAM,SAAS,IAAI,UAAU,CAAC,0EAA0E,CAAC;AACzG,IAAM,QAAQ,IAAI,UAAU;CAAC;CAA2C;CAAqD;CAAoD;AAAuE,CAAC;AACzP,IAAM,QAAQ,GAAW,MAAc,EAAE,YAAY,MAAM,EAAE,YAAY;AACzE,IAAM,gBAAgB;;AAEtB,IAAM,gCAAgB,IA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kB,MAAgC;EAAE,MAAM,YAAU,KAAK,MAAM,KAAK,MAAK,IAAI;EAAE,KAAK,QAAM,UAAU,YAAU,CAAC,CAAC;EAAE,OAAO;CAAW;AACtJ"}
@@ -1,4 +1,4 @@
1
- import { W as shellWord } from "./apiKit-DAFsWtyk.js";
1
+ import { W as shellWord } from "./apiKit-BPuHOoXF.js";
2
2
  import { basename } from "node:path";
3
3
  // src/waitNotice.ts
4
4
  /** What happens next to what a wait was waiting on: a daemon goes on, a one-shot's profile closes now. */
@@ -177,4 +177,4 @@ function dhtOnlyNotice(notice, params, chat, mode) {
177
177
  }
178
178
  export { heldWords as a, waitsFor as c, goesOn as i, dhtOnlyNote as n, longTextChat as o, dhtOnlyNotice as r, waitNotice as s, chatState as t };
179
179
 
180
- //# sourceMappingURL=waitNotice-mB0Ym145.js.map
180
+ //# sourceMappingURL=waitNotice-DSECf6II.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"waitNotice-mB0Ym145.js","names":[],"sources":["../../src/waitNotice.ts"],"sourcesContent":["/*\n * What a command that waits says while it waits and when Ctrl-C ends it (agents#2354). Kept apart from waits.ts, which\n * runs in the daemon or the one-shot's engine: this is read by the command's own process, which loads no engine module\n * for a command a daemon answers.\n */\n\nimport { basename } from \"node:path\";\nimport { DHT_TEXT_BYTES } from \"@ghostly/core\";\nimport { shellWord } from \"./shellWord\";\n\n/** What happens next to what a wait was waiting on: a daemon goes on, a one-shot's profile closes now. */\nexport const goesOn = (mode: \"daemon\" | \"one-shot\"): string => mode === \"one-shot\"\n ? \"goes with this profile's next command, or keep it online with `ghostly daemon --detach`\"\n : \"still goes by itself while this profile is online\";\n\n/**\n * A chat this side holds on the DHT only (`chat disconnect --hold`) until `until`: what waits for its end (`act`)\n * goes then by itself, or at once with `chat connect`, which ends the hold. A hold whose time is up and that is still\n * ending (`holdEnds`) says so. The time is this machine's: the hour and minute, with the day when it is not today.\n */\nexport function heldWords(until: number, ref: string, act: string, oneShot = false): string {\n const connect = `ghostly chat connect ${shellWord(ref, \"<chat>\")}`;\n const online = oneShot ? \" while this profile is online (ghostly daemon --detach)\" : \"\";\n if (until <= Date.now()) return `this chat's hold on the DHT only is ending: ${act} once the chat is live${online}, or now with ${connect}`;\n const at = new Date(until), two = (n: number) => String(n).padStart(2, \"0\");\n const day = at.toDateString() === new Date().toDateString() ? \"\" : `${at.getFullYear()}-${two(at.getMonth() + 1)}-${two(at.getDate())} `;\n return `this chat is held on the DHT only until ${day}${two(at.getHours())}:${two(at.getMinutes())}: ${act} then${online}, or now with ${connect}`;\n}\n\n/** Where a chat stands for `dhtOnlyNote`: this side's DHT only (and its hold's end, if a hold), the contact's. */\nexport interface DhtOnly { mine: boolean; theirs: boolean; heldUntil: number | null; oneShot: boolean }\n\n/**\n * Why a text that waits will not go by itself, or undefined: longer than the 256 bytes the DHT carries, in a chat on\n * the DHT only (this side's choice, the contact's, or both). It goes once the chat is live, which neither side's app\n * tries while either keeps it on the DHT only, so it is said with what ends that, or to shorten it. This side's DHT\n * only that is a hold (`chat disconnect --hold`) ends by itself: said with when, and the command that ends it now. The\n * engine says it on `send` and `forward` (api.ts), the command's process on its notice and Ctrl-C (`dhtOnlyNotice`).\n */\nexport function dhtOnlyNote(chat: DhtOnly, text: string, ref: string): string | undefined {\n const { mine, theirs, heldUntil: held } = chat;\n if ((!mine && !theirs) || new TextEncoder().encode(text.trim()).length <= DHT_TEXT_BYTES) return undefined;\n const chosen = mine && held === null;\n const switchBack = `ghostly chat transport ${shellWord(ref, \"<chat>\")} auto`;\n const who = chosen && theirs ? `you and the contact keep this chat on the DHT only: it goes once both choose a live transport (${switchBack}), or shorten it`\n : theirs ? \"the contact keeps this chat on the DHT only: it goes once they choose a live transport, or shorten it\"\n : held !== null ? heldWords(held, ref, \"it goes\", chat.oneShot)\n : `this chat is on the DHT only: it goes once you choose a live transport (${switchBack}), or shorten it`;\n return `Longer than the ${DHT_TEXT_BYTES} bytes the DHT carries, and ${who}`;\n}\n\n/**\n * The wait a one-shot does when no `--wait` is given (`ctx.mode === \"one-shot\"` defaults in api.ts, files.ts, buttons.ts\n * and statusCards.ts): what is not out yet leaves with the process, so it stays. A daemon answers those at once. A ref\n * written `group:<id>` is a group's, whose file, card or button press does not wait; a group named otherwise is told\n * only by the engine, and its notice comes only if the call is still going after WAIT_NOTICE_MS.\n */\nfunction oneShotWait(method: string, params: Record<string, unknown>): string | undefined {\n const group = typeof params.group === \"string\" || (typeof params.chat === \"string\" && params.chat.startsWith(\"group:\"));\n switch (method) {\n // On a chat nobody joined yet these answer at once (apiKit `oneShotWaits`); a notice comes only if a call is still\n // going after WAIT_NOTICE_MS.\n case \"chat.send\": return \"sent\";\n case \"chat.edit\": return \"confirmed\";\n case \"file.send\": case \"task.send\": case \"routine.send\": case \"button.press\": return group ? undefined : \"sent\";\n // `--all` reports to each 1:1 chat in turn, each waiting as one named would.\n case \"usage.send\": return group ? undefined : \"sent\";\n case \"task.update\": case \"routine.update\": return group ? undefined : \"confirmed\";\n case \"chat.react\": return \"confirmed\";\n case \"group.react\": return \"sent\";\n case \"chat.pin\": return group ? \"sent\" : \"confirmed\";\n case \"chat.delete\": return params.everyone !== true ? undefined : group ? \"sent\" : \"confirmed\";\n default: return undefined;\n }\n}\n\n/** The call's `wait`: the one given, or the one-shot's own default. */\nfunction waitOf(method: string, params: Record<string, unknown>, mode: \"daemon\" | \"one-shot\"): Record<string, unknown> {\n if (params.wait !== undefined || mode !== \"one-shot\") return params;\n const wait = oneShotWait(method, params);\n return wait === undefined ? params : { ...params, wait };\n}\n\n/**\n * The seconds a call without `--timeout` waits for the contact: the daemon's defaults (`num(params, \"timeout\", …)` in\n * api.ts, files.ts, buttons.ts and statusCards.ts), so that a bot's `chat wait` or `send --wait sent` on a daemon that\n * stopped answering ends when the wait would have (main.ts `answerWithin`). A call that does not wait is none.\n */\nexport function waitsFor(method: string, params: Record<string, unknown>): number | undefined {\n if (method === \"chat.wait\") return 60;\n if (method === \"file.wait\" || (method === \"file.save\" && params.wait === true) || (method === \"file.send\" && params.wait === \"sent\")) return 300;\n // send, edit, forward, a button, a task or routine card: `--wait sent|confirmed|delivered`, 30 s each.\n if (typeof params.wait === \"string\" && params.wait !== \"none\") return 30;\n return undefined;\n}\n\nexport interface WaitNotice {\n /** Said on stderr (a terminal's only) when the wait has gone on for a moment: what it waits for. */\n waiting: string;\n /** Said after \"stopped waiting (Ctrl-C): \" when Ctrl-C ends the wait: what becomes of what it waited on. */\n stopped: string;\n}\n\nconst word = (value: unknown): string | undefined => typeof value === \"string\" && value.trim() ? value : undefined;\n\n/**\n * A state `chat wait --until` waits for, as a sentence says it (`to`: the wait's timeout and notice, `not`: Ctrl-C).\n * The flag's word after \"to be\" read \"to be text\" and \"was not text yet\".\n */\nconst CHAT_STATES: Record<string, { to: string; not: string }> = {\n live: { to: \"to be live\", not: \"was not live yet\" },\n text: { to: \"to carry text\", not: \"could not carry text yet\" },\n paired: { to: \"to be paired\", not: \"was not paired yet\" },\n};\nexport const chatState = (until: string): { to: string; not: string } => CHAT_STATES[until] ?? { to: `to be ${until}`, not: `was not ${until} yet` };\n\n/** What a call waits for, in a person's words, or null for a call that does not wait. */\nexport function waitNotice(method: string, given: Record<string, unknown>, mode: \"daemon\" | \"one-shot\"): WaitNotice | null {\n // A one-shot join by a group's link waits to be let in (api.ts `letIn`); through a daemon it answers at once.\n if (method === \"group.join\") return mode === \"one-shot\"\n ? { waiting: \"waiting for a member's app to let this profile in (up to 60 s; Ctrl-C stops waiting)\", stopped: \"not let in yet: the knock goes on while this profile is running (ghostly daemon --detach)\" }\n : null;\n const params = waitOf(method, given, mode);\n // A daemon's file send answers once it has copied the file into the profile (files.ts `stage`): 6-30 s for 1 GiB, said\n // nothing, and read as a hung daemon. Ctrl-C there stops the send (files.ts `stageWhileAsked`): nothing goes.\n if (method === \"file.send\" && mode === \"daemon\" && params.wait !== \"sent\") {\n const file = word(params.name) ?? (word(params.path) ? basename(params.path as string) : \"the file\");\n const chatRef = word(params.chat) ?? \"the chat\", chat = chatRef.startsWith(\"group:\") ? `group ${chatRef.slice(\"group:\".length)}` : chatRef;\n return { waiting: `copying ${file} into the profile before it goes to ${chat} (Ctrl-C stops the send)`, stopped: `${file} was not sent to ${chat}: send it again when you want it` };\n }\n const waits = waitsFor(method, params);\n if (waits === undefined) return null;\n const seconds = typeof params.timeout === \"number\" ? params.timeout : waits;\n // One that waits for the contact (`--wait sent`, a one-shot's own wait) copies the file in first as well, and Ctrl-C\n // then stops the send (a daemon's `stageWhileAsked`, a one-shot's profile closing under the copy): it said \"it is kept\n // here and still goes\" with nothing in the chat. Which of the two it was, only the chat's file list tells.\n if (method === \"file.send\") {\n const file = word(params.name) ?? (word(params.path) ? basename(params.path as string) : \"the file\");\n const chatRef = word(params.chat), chat = chatRef ?? \"the contact\";\n const list = chatRef ? ` (ghostly file list ${shellWord(chatRef, \"<chat>\")} says which)` : \"\";\n return {\n waiting: `copying ${file} into the profile, then waiting for it to go out to ${chat} (up to ${seconds} s; Ctrl-C stops the send while it is copied in, then only the waiting)`,\n stopped: `${file} was not sent to ${chat} if it was still being copied in; if it was in the chat, it is kept here and ${goesOn(mode)}${list}`,\n };\n }\n const upTo = `up to ${seconds} s; Ctrl-C stops waiting`;\n if (method === \"chat.wait\") {\n const chat = word(params.chat) ?? \"the chat\", state = chatState(word(params.until) ?? \"live\");\n return { waiting: `waiting for chat ${chat} ${state.to} (${upTo})`, stopped: `chat ${chat} ${state.not}` };\n }\n if (method === \"file.wait\" || method === \"file.save\") {\n const file = word(params.file) ?? \"the file\";\n const on = mode === \"one-shot\" ? \"goes on while this profile is online (`ghostly daemon --detach`)\" : \"goes on while this profile is online\";\n return { waiting: `waiting for file ${file}'s transfer to end (${upTo}; the transfer ${on})`, stopped: `file ${file}'s transfer ${on}` };\n }\n const chatRef = word(params.chat);\n // A forward's `chat` is where the messages come from; they go to `to`.\n const group = word(params.group) ?? (method.startsWith(\"group.\") ? chatRef\n : method !== \"chat.forward\" && chatRef?.startsWith(\"group:\") ? chatRef.slice(\"group:\".length) : undefined);\n const to = Array.isArray(params.to) ? params.to.filter((t): t is string => typeof t === \"string\").join(\", \") : undefined;\n const chat = (to || undefined) ?? chatRef ?? (params.all === true ? \"each contact\" : \"the contact\");\n const what = group !== undefined ? `a member's edge in group ${group} to take it`\n : params.wait === \"sent\" ? `it to go out to ${chat}`\n : `${chat}'s app to confirm it`;\n return { waiting: `waiting for ${what} (${upTo}, it still goes)`, stopped: `it is kept here and ${goesOn(mode)}` };\n}\n\n/**\n * A `send` that waits on a text past the 256 bytes the DHT carries: its notice said \"it still goes\" and\n * Ctrl-C that it \"still goes by itself\", which it does not while the chat stays on the DHT only. Only the chat's state\n * says so, which the command's process reads (`chat.get`) and hands to `dhtOnlyNotice`; the chat to read, or undefined.\n */\nexport function longTextChat(method: string, params: Record<string, unknown>): string | undefined {\n if (method !== \"chat.send\" || typeof params.text !== \"string\" || new TextEncoder().encode(params.text.trim()).length <= DHT_TEXT_BYTES) return undefined;\n const chat = word(params.chat);\n return chat?.startsWith(\"group:\") ? undefined : chat;\n}\n\n/**\n * That `send`'s notice once its chat was read (`chat.get`): said with why it waits when the chat is on the DHT only,\n * else as it was. A hold whose time is up and still ending reads as no hold there (`heldUntil`), so as a DHT only chosen.\n */\nexport function dhtOnlyNotice(notice: WaitNotice, params: Record<string, unknown>, chat: { deliveryMode?: unknown; peerDeliveryMode?: unknown; heldUntil?: unknown }, mode: \"daemon\" | \"one-shot\"): WaitNotice {\n const mine = chat.deliveryMode === \"dht\";\n const heldUntil = mine && typeof chat.heldUntil === \"number\" ? chat.heldUntil : null;\n const note = dhtOnlyNote({ mine, theirs: chat.peerDeliveryMode === \"dht\", heldUntil, oneShot: mode === \"one-shot\" }, params.text as string, params.chat as string);\n return note ? { waiting: `${notice.waiting.replace(/, it still goes\\)$/, \")\")}. ${note}`, stopped: `it is kept here. ${note}` } : notice;\n}\n"],"mappings":";;;;AAWA,IAAa,UAAU,SAAwC,SAAS,aACpE,4FACA;;;;;;AAOJ,SAAgB,U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S;CAAW,GAAG,OAAO,MAAgB,OAAO,IAAc;CACjK,OAAO,OAAO;EAAE,SAAS,GAAG,OAAO,QAAQ,QAAQ,sBAAsB,GAAG,EAAE,IAAI;EAAQ,SAAS,oBAAoB;CAAO,IAAI;AACpI"}
1
+ {"version":3,"file":"waitNotice-DSECf6II.js","names":[],"sources":["../../src/waitNotice.ts"],"sourcesContent":["/*\n * What a command that waits says while it waits and when Ctrl-C ends it (agents#2354). Kept apart from waits.ts, which\n * runs in the daemon or the one-shot's engine: this is read by the command's own process, which loads no engine module\n * for a command a daemon answers.\n */\n\nimport { basename } from \"node:path\";\nimport { DHT_TEXT_BYTES } from \"@ghostly/core\";\nimport { shellWord } from \"./shellWord\";\n\n/** What happens next to what a wait was waiting on: a daemon goes on, a one-shot's profile closes now. */\nexport const goesOn = (mode: \"daemon\" | \"one-shot\"): string => mode === \"one-shot\"\n ? \"goes with this profile's next command, or keep it online with `ghostly daemon --detach`\"\n : \"still goes by itself while this profile is online\";\n\n/**\n * A chat this side holds on the DHT only (`chat disconnect --hold`) until `until`: what waits for its end (`act`)\n * goes then by itself, or at once with `chat connect`, which ends the hold. A hold whose time is up and that is still\n * ending (`holdEnds`) says so. The time is this machine's: the hour and minute, with the day when it is not today.\n */\nexport function heldWords(until: number, ref: string, act: string, oneShot = false): string {\n const connect = `ghostly chat connect ${shellWord(ref, \"<chat>\")}`;\n const online = oneShot ? \" while this profile is online (ghostly daemon --detach)\" : \"\";\n if (until <= Date.now()) return `this chat's hold on the DHT only is ending: ${act} once the chat is live${online}, or now with ${connect}`;\n const at = new Date(until), two = (n: number) => String(n).padStart(2, \"0\");\n const day = at.toDateString() === new Date().toDateString() ? \"\" : `${at.getFullYear()}-${two(at.getMonth() + 1)}-${two(at.getDate())} `;\n return `this chat is held on the DHT only until ${day}${two(at.getHours())}:${two(at.getMinutes())}: ${act} then${online}, or now with ${connect}`;\n}\n\n/** Where a chat stands for `dhtOnlyNote`: this side's DHT only (and its hold's end, if a hold), the contact's. */\nexport interface DhtOnly { mine: boolean; theirs: boolean; heldUntil: number | null; oneShot: boolean }\n\n/**\n * Why a text that waits will not go by itself, or undefined: longer than the 256 bytes the DHT carries, in a chat on\n * the DHT only (this side's choice, the contact's, or both). It goes once the chat is live, which neither side's app\n * tries while either keeps it on the DHT only, so it is said with what ends that, or to shorten it. This side's DHT\n * only that is a hold (`chat disconnect --hold`) ends by itself: said with when, and the command that ends it now. The\n * engine says it on `send` and `forward` (api.ts), the command's process on its notice and Ctrl-C (`dhtOnlyNotice`).\n */\nexport function dhtOnlyNote(chat: DhtOnly, text: string, ref: string): string | undefined {\n const { mine, theirs, heldUntil: held } = chat;\n if ((!mine && !theirs) || new TextEncoder().encode(text.trim()).length <= DHT_TEXT_BYTES) return undefined;\n const chosen = mine && held === null;\n const switchBack = `ghostly chat transport ${shellWord(ref, \"<chat>\")} auto`;\n const who = chosen && theirs ? `you and the contact keep this chat on the DHT only: it goes once both choose a live transport (${switchBack}), or shorten it`\n : theirs ? \"the contact keeps this chat on the DHT only: it goes once they choose a live transport, or shorten it\"\n : held !== null ? heldWords(held, ref, \"it goes\", chat.oneShot)\n : `this chat is on the DHT only: it goes once you choose a live transport (${switchBack}), or shorten it`;\n return `Longer than the ${DHT_TEXT_BYTES} bytes the DHT carries, and ${who}`;\n}\n\n/**\n * The wait a one-shot does when no `--wait` is given (`ctx.mode === \"one-shot\"` defaults in api.ts, files.ts, buttons.ts\n * and statusCards.ts): what is not out yet leaves with the process, so it stays. A daemon answers those at once. A ref\n * written `group:<id>` is a group's, whose file, card or button press does not wait; a group named otherwise is told\n * only by the engine, and its notice comes only if the call is still going after WAIT_NOTICE_MS.\n */\nfunction oneShotWait(method: string, params: Record<string, unknown>): string | undefined {\n const group = typeof params.group === \"string\" || (typeof params.chat === \"string\" && params.chat.startsWith(\"group:\"));\n switch (method) {\n // On a chat nobody joined yet these answer at once (apiKit `oneShotWaits`); a notice comes only if a call is still\n // going after WAIT_NOTICE_MS.\n case \"chat.send\": return \"sent\";\n case \"chat.edit\": return \"confirmed\";\n case \"file.send\": case \"task.send\": case \"routine.send\": case \"button.press\": return group ? undefined : \"sent\";\n // `--all` reports to each 1:1 chat in turn, each waiting as one named would.\n case \"usage.send\": return group ? undefined : \"sent\";\n case \"task.update\": case \"routine.update\": return group ? undefined : \"confirmed\";\n case \"chat.react\": return \"confirmed\";\n case \"group.react\": return \"sent\";\n case \"chat.pin\": return group ? \"sent\" : \"confirmed\";\n case \"chat.delete\": return params.everyone !== true ? undefined : group ? \"sent\" : \"confirmed\";\n default: return undefined;\n }\n}\n\n/** The call's `wait`: the one given, or the one-shot's own default. */\nfunction waitOf(method: string, params: Record<string, unknown>, mode: \"daemon\" | \"one-shot\"): Record<string, unknown> {\n if (params.wait !== undefined || mode !== \"one-shot\") return params;\n const wait = oneShotWait(method, params);\n return wait === undefined ? params : { ...params, wait };\n}\n\n/**\n * The seconds a call without `--timeout` waits for the contact: the daemon's defaults (`num(params, \"timeout\", …)` in\n * api.ts, files.ts, buttons.ts and statusCards.ts), so that a bot's `chat wait` or `send --wait sent` on a daemon that\n * stopped answering ends when the wait would have (main.ts `answerWithin`). A call that does not wait is none.\n */\nexport function waitsFor(method: string, params: Record<string, unknown>): number | undefined {\n if (method === \"chat.wait\") return 60;\n if (method === \"file.wait\" || (method === \"file.save\" && params.wait === true) || (method === \"file.send\" && params.wait === \"sent\")) return 300;\n // send, edit, forward, a button, a task or routine card: `--wait sent|confirmed|delivered`, 30 s each.\n if (typeof params.wait === \"string\" && params.wait !== \"none\") return 30;\n return undefined;\n}\n\nexport interface WaitNotice {\n /** Said on stderr (a terminal's only) when the wait has gone on for a moment: what it waits for. */\n waiting: string;\n /** Said after \"stopped waiting (Ctrl-C): \" when Ctrl-C ends the wait: what becomes of what it waited on. */\n stopped: string;\n}\n\nconst word = (value: unknown): string | undefined => typeof value === \"string\" && value.trim() ? value : undefined;\n\n/**\n * A state `chat wait --until` waits for, as a sentence says it (`to`: the wait's timeout and notice, `not`: Ctrl-C).\n * The flag's word after \"to be\" read \"to be text\" and \"was not text yet\".\n */\nconst CHAT_STATES: Record<string, { to: string; not: string }> = {\n live: { to: \"to be live\", not: \"was not live yet\" },\n text: { to: \"to carry text\", not: \"could not carry text yet\" },\n paired: { to: \"to be paired\", not: \"was not paired yet\" },\n};\nexport const chatState = (until: string): { to: string; not: string } => CHAT_STATES[until] ?? { to: `to be ${until}`, not: `was not ${until} yet` };\n\n/** What a call waits for, in a person's words, or null for a call that does not wait. */\nexport function waitNotice(method: string, given: Record<string, unknown>, mode: \"daemon\" | \"one-shot\"): WaitNotice | null {\n // A one-shot join by a group's link waits to be let in (api.ts `letIn`); through a daemon it answers at once.\n if (method === \"group.join\") return mode === \"one-shot\"\n ? { waiting: \"waiting for a member's app to let this profile in (up to 60 s; Ctrl-C stops waiting)\", stopped: \"not let in yet: the knock goes on while this profile is running (ghostly daemon --detach)\" }\n : null;\n const params = waitOf(method, given, mode);\n // A daemon's file send answers once it has copied the file into the profile (files.ts `stage`): 6-30 s for 1 GiB, said\n // nothing, and read as a hung daemon. Ctrl-C there stops the send (files.ts `stageWhileAsked`): nothing goes.\n if (method === \"file.send\" && mode === \"daemon\" && params.wait !== \"sent\") {\n const file = word(params.name) ?? (word(params.path) ? basename(params.path as string) : \"the file\");\n const chatRef = word(params.chat) ?? \"the chat\", chat = chatRef.startsWith(\"group:\") ? `group ${chatRef.slice(\"group:\".length)}` : chatRef;\n return { waiting: `copying ${file} into the profile before it goes to ${chat} (Ctrl-C stops the send)`, stopped: `${file} was not sent to ${chat}: send it again when you want it` };\n }\n const waits = waitsFor(method, params);\n if (waits === undefined) return null;\n const seconds = typeof params.timeout === \"number\" ? params.timeout : waits;\n // One that waits for the contact (`--wait sent`, a one-shot's own wait) copies the file in first as well, and Ctrl-C\n // then stops the send (a daemon's `stageWhileAsked`, a one-shot's profile closing under the copy): it said \"it is kept\n // here and still goes\" with nothing in the chat. Which of the two it was, only the chat's file list tells.\n if (method === \"file.send\") {\n const file = word(params.name) ?? (word(params.path) ? basename(params.path as string) : \"the file\");\n const chatRef = word(params.chat), chat = chatRef ?? \"the contact\";\n const list = chatRef ? ` (ghostly file list ${shellWord(chatRef, \"<chat>\")} says which)` : \"\";\n return {\n waiting: `copying ${file} into the profile, then waiting for it to go out to ${chat} (up to ${seconds} s; Ctrl-C stops the send while it is copied in, then only the waiting)`,\n stopped: `${file} was not sent to ${chat} if it was still being copied in; if it was in the chat, it is kept here and ${goesOn(mode)}${list}`,\n };\n }\n const upTo = `up to ${seconds} s; Ctrl-C stops waiting`;\n if (method === \"chat.wait\") {\n const chat = word(params.chat) ?? \"the chat\", state = chatState(word(params.until) ?? \"live\");\n return { waiting: `waiting for chat ${chat} ${state.to} (${upTo})`, stopped: `chat ${chat} ${state.not}` };\n }\n if (method === \"file.wait\" || method === \"file.save\") {\n const file = word(params.file) ?? \"the file\";\n const on = mode === \"one-shot\" ? \"goes on while this profile is online (`ghostly daemon --detach`)\" : \"goes on while this profile is online\";\n return { waiting: `waiting for file ${file}'s transfer to end (${upTo}; the transfer ${on})`, stopped: `file ${file}'s transfer ${on}` };\n }\n const chatRef = word(params.chat);\n // A forward's `chat` is where the messages come from; they go to `to`.\n const group = word(params.group) ?? (method.startsWith(\"group.\") ? chatRef\n : method !== \"chat.forward\" && chatRef?.startsWith(\"group:\") ? chatRef.slice(\"group:\".length) : undefined);\n const to = Array.isArray(params.to) ? params.to.filter((t): t is string => typeof t === \"string\").join(\", \") : undefined;\n const chat = (to || undefined) ?? chatRef ?? (params.all === true ? \"each contact\" : \"the contact\");\n const what = group !== undefined ? `a member's edge in group ${group} to take it`\n : params.wait === \"sent\" ? `it to go out to ${chat}`\n : `${chat}'s app to confirm it`;\n return { waiting: `waiting for ${what} (${upTo}, it still goes)`, stopped: `it is kept here and ${goesOn(mode)}` };\n}\n\n/**\n * A `send` that waits on a text past the 256 bytes the DHT carries: its notice said \"it still goes\" and\n * Ctrl-C that it \"still goes by itself\", which it does not while the chat stays on the DHT only. Only the chat's state\n * says so, which the command's process reads (`chat.get`) and hands to `dhtOnlyNotice`; the chat to read, or undefined.\n */\nexport function longTextChat(method: string, params: Record<string, unknown>): string | undefined {\n if (method !== \"chat.send\" || typeof params.text !== \"string\" || new TextEncoder().encode(params.text.trim()).length <= DHT_TEXT_BYTES) return undefined;\n const chat = word(params.chat);\n return chat?.startsWith(\"group:\") ? undefined : chat;\n}\n\n/**\n * That `send`'s notice once its chat was read (`chat.get`): said with why it waits when the chat is on the DHT only,\n * else as it was. A hold whose time is up and still ending reads as no hold there (`heldUntil`), so as a DHT only chosen.\n */\nexport function dhtOnlyNotice(notice: WaitNotice, params: Record<string, unknown>, chat: { deliveryMode?: unknown; peerDeliveryMode?: unknown; heldUntil?: unknown }, mode: \"daemon\" | \"one-shot\"): WaitNotice {\n const mine = chat.deliveryMode === \"dht\";\n const heldUntil = mine && typeof chat.heldUntil === \"number\" ? chat.heldUntil : null;\n const note = dhtOnlyNote({ mine, theirs: chat.peerDeliveryMode === \"dht\", heldUntil, oneShot: mode === \"one-shot\" }, params.text as string, params.chat as string);\n return note ? { waiting: `${notice.waiting.replace(/, it still goes\\)$/, \")\")}. ${note}`, stopped: `it is kept here. ${note}` } : notice;\n}\n"],"mappings":";;;;AAWA,IAAa,UAAU,SAAwC,SAAS,aACpE,4FACA;;;;;;AAOJ,SAAgB,UAAU,OAAe,KAAa,KAAa,UAAU,OAAe;CAC1F,MAAM,UAAU,wBAAwB,UAAU,KAAK,QAAQ;CAC/D,MAAM,SAAS,UAAU,4DAA4D;CACrF,IAAI,SAAS,KAAK,IAAI,GAAG,OAAO,+CAA+C,IAAI,wBAAwB,OAAO,gBAAgB;CAClI,MAAM,KAAK,IAAI,KAAK,KAAK,GAAG,OAAO,MAAc,OAAO,CAAC,CAAC,CAAC,SAAS,GAAG,GAAG;CAE1E,OAAO,2CADK,GAAG,aAAa,uBAAM,IAAI,KAAK,EAAA,CAAE,aAAa,IAAI,KAAK,GAAG,GAAG,YAAY,EAAE,GAAG,IA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AAE,IAAI,OAAO,GAAG,QAAQ,MAAmB,OAAO,MAAM,QAAQ,CAAC,CAAC,KAAK,IAAI,IAAI,KAAA,MAC3F,KAAA,MAAc,YAAY,OAAO,QAAQ,OAAO,iBAAiB;CAIrF,OAAO;EAAE,SAAS,eAHL,UAAU,KAAA,IAAY,4BAA4B,MAAM,eACjE,OAAO,SAAS,SAAS,mBAAmB,SAC5C,GAAG,KAAK,sBAC0B,IAAI,KAAK;EAAmB,SAAS,uBAAuB,OAAO,IAAI;CAAI;AACnH;;;;;;AAOA,SAAgB,aAAa,QAAgB,QAAqD;CAChG,IAAI,WAAW,eAAe,OAAO,OAAO,SAAS,YAAY,IAAI,YAAY,CAAC,CAAC,OAAO,OAAO,KAAK,KAAK,CAAC,CAAC,CAAC,UAAA,KAA0B,OAAO,KAAA;CAC/I,MAAM,OAAO,KAAK,OAAO,IAAI;CAC7B,OAAO,MAAM,WAAW,QAAQ,IAAI,KAAA,IAAY;AAClD;;;;;AAMA,SAAgB,cAAc,QAAoB,QAAiC,MAAmF,MAAyC;CAC7M,MAAM,OAAO,KAAK,iBAAiB;CACnC,MAAM,YAAY,QAAQ,OAAO,KAAK,cAAc,WAAW,KAAK,YAAY;CAChF,MAAM,OAAO,YAAY;EAAE;EAAM,QAAQ,KAAK,qBAAqB;EAAO;EAAW,SAAS,SAAS;CAAW,GAAG,OAAO,MAAgB,OAAO,IAAc;CACjK,OAAO,OAAO;EAAE,SAAS,GAAG,OAAO,QAAQ,QAAQ,sBAAsB,GAAG,EAAE,IAAI;EAAQ,SAAS,oBAAoB;CAAO,IAAI;AACpI"}
package/dist/ghostly.mjs CHANGED
@@ -23,7 +23,7 @@ function quietWebStorage(scope = globalThis, execArgv = process.execArgv, nodeOp
23
23
  // src/bin.ts
24
24
  quietWebStorage();
25
25
  enableCompileCache();
26
- var { run } = await import("./assets/main-D48Ben7C.js");
26
+ var { run } = await import("./assets/main-BLs-zUTt.js");
27
27
  run(process.argv.slice(2));
28
28
  export {};
29
29
 
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ghostlytools/cli",
3
- "version": "1.13.3",
3
+ "version": "1.13.4",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@ghostlytools/cli",
9
- "version": "1.13.3",
9
+ "version": "1.13.4",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@arkade-os/sdk": "0.5.4",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ghostlytools/cli",
3
- "version": "1.13.3",
3
+ "version": "1.13.4",
4
4
  "type": "module",
5
5
  "description": "Ghostly for bots and terminals: the app's own engine, headless on Node, behind a daemon and a `ghostly` command with JSON output.",
6
6
  "license": "MIT",