@ghostlytools/cli 1.13.0 → 1.13.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -10
- package/dist/assets/api-DV52o7A8.js +3 -0
- package/dist/assets/{api-CjOaoG-v.js → api-O57SNJcb.js} +495 -99
- package/dist/assets/api-O57SNJcb.js.map +1 -0
- package/dist/assets/{apiKit-BAGvlQtm.js → apiKit-CPTFJHA7.js} +40 -8
- package/dist/assets/{apiKit-BAGvlQtm.js.map → apiKit-CPTFJHA7.js.map} +1 -1
- package/dist/assets/{appFetch-BwJd-kNq.js → appFetch-Ca9DNQQ2.js} +2 -2
- package/dist/assets/{appFetch-BwJd-kNq.js.map → appFetch-Ca9DNQQ2.js.map} +1 -1
- package/dist/assets/{apps-Cuk45sz5.js → apps-gXpGFPiv.js} +16 -14
- package/dist/assets/apps-gXpGFPiv.js.map +1 -0
- package/dist/assets/{apps-DjY095Af.js → apps-uZTu5FlR.js} +1 -1
- package/dist/assets/{arkade-DryM-q5n.js → arkade-B6UNf5HI.js} +2 -2
- package/dist/assets/{arkade-DryM-q5n.js.map → arkade-B6UNf5HI.js.map} +1 -1
- package/dist/assets/{backup-DekVCDWv.js → backup-CxH3auHB.js} +9 -7
- package/dist/assets/backup-CxH3auHB.js.map +1 -0
- package/dist/assets/{backup-B56sQqoQ.js → backup-Di2U6QVH.js} +1 -1
- package/dist/assets/bark_ffi_wasm_bg-CcafsJla.js.map +1 -1
- package/dist/assets/{bitcoind-B2bbVSzh.js → bitcoind-BpZn3bRN.js} +2 -2
- package/dist/assets/{bitcoind-B2bbVSzh.js.map → bitcoind-BpZn3bRN.js.map} +1 -1
- package/dist/assets/bitcoindevkit_bg-BWQHx7vd.js.map +1 -1
- package/dist/assets/{buttons-BGxzOtrq.js → buttons-D4udKEvT.js} +8 -8
- package/dist/assets/buttons-D4udKEvT.js.map +1 -0
- package/dist/assets/buttons-YTYEqvGC.js +1 -0
- package/dist/assets/{client-DcQAfc3h.js → client-DGx7E8b3.js} +3 -3
- package/dist/assets/{client-DcQAfc3h.js.map → client-DGx7E8b3.js.map} +1 -1
- package/dist/assets/{domainProofs-BDNP1dIy.js → domainProofs-b3Y1Gj9g.js} +6 -2
- package/dist/assets/{domainProofs-BDNP1dIy.js.map → domainProofs-b3Y1Gj9g.js.map} +1 -1
- package/dist/assets/{engineErrors--9hfgKlK.js → engineErrors-wWlLy54D.js} +11 -3
- package/dist/assets/engineErrors-wWlLy54D.js.map +1 -0
- package/dist/assets/{errors-DDLFO4Gf.js → errors-JVJsO8Iu.js} +18 -2
- package/dist/assets/errors-JVJsO8Iu.js.map +1 -0
- package/dist/assets/{fixedHosts-C3hBliM9.js → fixedHosts-CODN2pTL.js} +3 -3
- package/dist/assets/{fixedHosts-C3hBliM9.js.map → fixedHosts-CODN2pTL.js.map} +1 -1
- package/dist/assets/{ghostly_iroh_web-DIj5xGmR.js → ghostly_iroh_web-9VOwZcJQ.js} +30 -35
- package/dist/assets/ghostly_iroh_web-9VOwZcJQ.js.map +1 -0
- package/dist/assets/ghostly_iroh_web_bg.wasm +0 -0
- package/dist/assets/{groupMeta-goASqzOt.js → groupMeta-CeZpqVVC.js} +174 -37
- package/dist/assets/groupMeta-CeZpqVVC.js.map +1 -0
- package/dist/assets/{host-C2WRKj3g.js → host-CRA7h5A2.js} +270 -64
- package/dist/assets/host-CRA7h5A2.js.map +1 -0
- package/dist/assets/{hyperdhtRelay-DLUiwfnt.js → hyperdhtRelay-B34Zhz4P.js} +2 -2
- package/dist/assets/{hyperdhtRelay-DLUiwfnt.js.map → hyperdhtRelay-B34Zhz4P.js.map} +1 -1
- package/dist/assets/{hyperdhtRelay-bjNGacf5.js → hyperdhtRelay-DDwU5b4P.js} +2 -2
- package/dist/assets/{hyperdhtRelay-bjNGacf5.js.map → hyperdhtRelay-DDwU5b4P.js.map} +1 -1
- package/dist/assets/{identityProofs-Cksc_K7_.js → identityProofs-B8zCp5_0.js} +140 -27
- package/dist/assets/identityProofs-B8zCp5_0.js.map +1 -0
- package/dist/assets/{irohWeb-NfthOL98.js → irohWeb-mnOi2Jp7.js} +10838 -4837
- package/dist/assets/irohWeb-mnOi2Jp7.js.map +1 -0
- package/dist/assets/{linkPreview-DdMf-YAc.js → linkPreview-5kHmKUTN.js} +20 -8
- package/dist/assets/linkPreview-5kHmKUTN.js.map +1 -0
- package/dist/assets/{main-Dh7fePd8.js → main-Chc871HV.js} +119 -81
- package/dist/assets/main-Chc871HV.js.map +1 -0
- package/dist/assets/{mainline-DY95WbuK.js → mainline-CDUXtV-I.js} +2 -2
- package/dist/assets/{mainline-DY95WbuK.js.map → mainline-CDUXtV-I.js.map} +1 -1
- package/dist/assets/{networkReason-Be-hMghr.js → networkReason-DYlPZS5M.js} +2 -2
- package/dist/assets/{networkReason-Be-hMghr.js.map → networkReason-DYlPZS5M.js.map} +1 -1
- package/dist/assets/{ownDid-BErplN7N.js → ownDid-BOuSlDv-.js} +10 -6
- package/dist/assets/ownDid-BOuSlDv-.js.map +1 -0
- package/dist/assets/{ownStatus-ClrFjd7h.js → ownStatus-CLA1VPkL.js} +6 -6
- package/dist/assets/{ownStatus-ClrFjd7h.js.map → ownStatus-CLA1VPkL.js.map} +1 -1
- package/dist/assets/{pairedTransports-BKmvlKz1.js → pairedTransports-DAzupLYo.js} +23 -17
- package/dist/assets/pairedTransports-DAzupLYo.js.map +1 -0
- package/dist/assets/{paymentIntent-DySU3Ajm.js → paymentIntent-Cr3uZa_0.js} +2 -2
- package/dist/assets/{paymentIntent-DySU3Ajm.js.map → paymentIntent-Cr3uZa_0.js.map} +1 -1
- package/dist/assets/{profiles-B8xO8-oj.js → profiles-BH1bH9aE.js} +3 -3
- package/dist/assets/{profiles-B8xO8-oj.js.map → profiles-BH1bH9aE.js.map} +1 -1
- package/dist/assets/{registry--Rg2YvOH.js → registry-DAq16T-V.js} +1 -1
- package/dist/assets/{registry-CU8PevhI.js → registry-DP_-RA-v.js} +11 -7
- package/dist/assets/registry-DP_-RA-v.js.map +1 -0
- package/dist/assets/{relay-CHWg5hpZ.js → relay-gJTOYQJZ.js} +93 -7
- package/dist/assets/relay-gJTOYQJZ.js.map +1 -0
- package/dist/assets/{resolve-B1upovPM.js → resolve-B1eQ4dVQ.js} +10 -5
- package/dist/assets/resolve-B1eQ4dVQ.js.map +1 -0
- package/dist/assets/secretGuard-Bh11MPdI.js +1 -0
- package/dist/assets/{secretGuard-BrATm_gl.js → secretGuard-oz_3hBfW.js} +19 -2
- package/dist/assets/{secretGuard-BrATm_gl.js.map → secretGuard-oz_3hBfW.js.map} +1 -1
- package/dist/assets/{server-Dgxx_DaN.js → server-Bd2ofxc1.js} +1283 -6628
- package/dist/assets/server-Bd2ofxc1.js.map +1 -0
- package/dist/assets/{sshForges-BnvwmNj-.js → sshForges-As7dbGXM.js} +2 -2
- package/dist/assets/{sshForges-BnvwmNj-.js.map → sshForges-As7dbGXM.js.map} +1 -1
- package/dist/assets/{translate-BcbSWkuq.js → translate-DnuQMfj0.js} +22 -11
- package/dist/assets/translate-DnuQMfj0.js.map +1 -0
- package/dist/assets/{usdt-CBJ4Q5Ji.js → usdt-DLmtf8F9.js} +4 -4
- package/dist/assets/{usdt-CBJ4Q5Ji.js.map → usdt-DLmtf8F9.js.map} +1 -1
- package/dist/assets/{waitNotice-ylU3XwjO.js → waitNotice-BHuMofaH.js} +57 -3
- package/dist/assets/waitNotice-BHuMofaH.js.map +1 -0
- package/dist/ghostly.mjs +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/assets/api-CVtg7MpI.js +0 -3
- package/dist/assets/api-CjOaoG-v.js.map +0 -1
- package/dist/assets/apps-Cuk45sz5.js.map +0 -1
- package/dist/assets/backup-DekVCDWv.js.map +0 -1
- package/dist/assets/buttons-BGxzOtrq.js.map +0 -1
- package/dist/assets/buttons-CsN2WJOf.js +0 -1
- package/dist/assets/engineErrors--9hfgKlK.js.map +0 -1
- package/dist/assets/errors-DDLFO4Gf.js.map +0 -1
- package/dist/assets/ghostly_iroh_web-DIj5xGmR.js.map +0 -1
- package/dist/assets/groupMeta-goASqzOt.js.map +0 -1
- package/dist/assets/host-C2WRKj3g.js.map +0 -1
- package/dist/assets/identityProofs-Cksc_K7_.js.map +0 -1
- package/dist/assets/irohWeb-NfthOL98.js.map +0 -1
- package/dist/assets/linkPreview-DdMf-YAc.js.map +0 -1
- package/dist/assets/main-Dh7fePd8.js.map +0 -1
- package/dist/assets/ownDid-BErplN7N.js.map +0 -1
- package/dist/assets/pairedTransports-BKmvlKz1.js.map +0 -1
- package/dist/assets/registry-CU8PevhI.js.map +0 -1
- package/dist/assets/relay-CHWg5hpZ.js.map +0 -1
- package/dist/assets/resolve-B1upovPM.js.map +0 -1
- package/dist/assets/secretGuard-Bm6nci0I.js +0 -1
- package/dist/assets/server-Dgxx_DaN.js.map +0 -1
- package/dist/assets/translate-BcbSWkuq.js.map +0 -1
- package/dist/assets/waitNotice-ylU3XwjO.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"appFetch-BwJd-kNq.js","names":[],"sources":["../../../core/src/signer.ts","../../../core/src/appStore.ts","../../../core/src/appUpdates.ts","../../../browser/src/engine/appFetch.ts"],"sourcesContent":["import { ed25519 } from \"@noble/curves/ed25519.js\";\nimport { sign } from \"./identity\";\n\n/*\n * A signer (WISP 06 § Terms): an Ed25519 key that signs without the caller holding its seed. The device signing key\n * is non-extractable where WebCrypto offers Ed25519, so the app has no bytes to sign with; where it does not, the key\n * is a stored seed. Both are this one interface, and so is a chat's participation seed when a session is given one.\n *\n * Signing is asynchronous because WebCrypto is. The public key is known at once: a session puts it in its offer\n * before it signs anything.\n */\nexport interface Signer {\n /** The Ed25519 public key, 32 bytes. */\n readonly publicKey: Uint8Array;\n /** The 64-byte signature of `bytes`. */\n sign(bytes: Uint8Array): Promise<Uint8Array>;\n}\n\n/** A seed held by the app, as every key of a profile is today. */\nexport function seedSigner(seed: Uint8Array): Signer {\n if (seed.length !== 32) throw new Error(\"Seed must be exactly 32 bytes\");\n const publicKey = ed25519.getPublicKey(seed);\n return { publicKey, sign: async (bytes) => sign(bytes, seed) };\n}\n\n/**\n * A WebCrypto Ed25519 private key, non-extractable or not, with its raw public key. The app never sees the private\n * bytes: `crypto.subtle` signs.\n */\nexport function webCryptoSigner(privateKey: CryptoKey, publicKey: Uint8Array): Signer {\n if (publicKey.length !== 32) throw new Error(\"An Ed25519 public key is 32 bytes\");\n return {\n publicKey,\n sign: async (bytes) => new Uint8Array(await crypto.subtle.sign({ name: \"Ed25519\" }, privateKey, new Uint8Array(bytes))),\n };\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { toBase64Url, toZ32 } from \"./bytes\";\nimport { canonicalJsonBytes, readCanonicalJson, type JsonValue } from \"./canonicalJson\";\nimport { findAppForbiddenKey, isAppUrl } from \"./appBundle\";\nimport {\n APP_PREFIXES, isAppHash, isAppKey, isAppLine, isAppRef, readAppRevocationShape, readAppSignature, signAppObject, verifyAppRevocation, verifyAppSignature,\n type AppRevocationsChecked, type AppSignature, type SignedAppRevocation,\n} from \"./appStatements\";\nimport type { Signer } from \"./signer\";\n\n/*\n * A store index (WISP 1200 · Stores): `ghostly-store.json`, canonical JSON, signed by the store key under\n * `ghostly-store/1` in `ghostly-store.sig` beside it (the same statement as a bundle's). It lists apps by reference and\n * digest, the versions it removed, and publishers' revocations copied verbatim. Times are Unix seconds.\n *\n * A store lists and ranks; it never changes what installs: the bundle a listing points at is checked on its own, and\n * its icon and description come from the bundle. `listing.json` in a store's repository is one entry of `apps`.\n */\n\nexport const APP_STORE_LIMITS = {\n /** The index's bytes, uncompressed. */\n indexBytes: 16 * 1024 * 1024,\n /** How far ahead `expires` may be. */\n expiresAheadS: 90 * 24 * 60 * 60,\n name: 40,\n description: 2000,\n title: 40,\n tagline: 80,\n /** `category`, `developer`, `submitter`. */\n label: 40,\n reason: 200,\n urls: 4,\n apps: 4096,\n removed: 4096,\n revoked: 4096,\n} as const;\n\nexport const APP_STORE_KINDS = [\"curated\", \"indexed\"] as const;\nexport type AppStoreKind = typeof APP_STORE_KINDS[number];\n\nexport interface AppListing {\n ref: string;\n sequence: number;\n digest: string;\n urls: string[];\n title: string;\n tagline: string;\n category?: string;\n developer?: string;\n submitter?: string;\n repo?: string;\n support?: string;\n}\nexport interface AppRemoval { ref: string; digest: string; reason: string; at: number }\nexport interface AppStoreIndex {\n ghostlyStore: 1;\n key: string;\n name: string;\n description?: string;\n kind: AppStoreKind;\n sequence: number;\n expires: number;\n apps: AppListing[];\n removed: AppRemoval[];\n revoked: SignedAppRevocation[];\n}\n\nexport type AppStoreRefusal =\n | \"too-large\" | \"not-json\" | \"not-canonical\" | \"unsupported-format\" | \"unknown-key\" | \"missing-key\" | \"bad-field\"\n | \"duplicate-app\" | \"bad-signature-statement\" | \"signature-key\" | \"bad-signature\" | \"store-key\" | \"expires-too-far\"\n | \"bad-revocation\";\n\nconst isObject = (v: unknown): v is Record<string, JsonValue> => typeof v === \"object\" && v !== null && !Array.isArray(v);\nconst isText = (v: unknown, max: number): v is string => typeof v === \"string\" && [...v].length <= max && !/[^\\P{Cc}\\n]/u.test(v);\nconst isCount = (v: unknown, min: number): v is number => typeof v === \"number\" && Number.isSafeInteger(v) && v >= min;\n\ntype Check = { ok: true } | { ok: false; reason: AppStoreRefusal; detail?: string };\nconst fine: Check = { ok: true };\n\n/**\n * How a check treats a key it does not know. A reader (`readAppStore`, the client) ignores it, so a later format can\n * add an optional key without a client refusing the whole signed index; the signature still covers the bytes as they\n * are, unknown keys included. A writer (`signAppStore`, the CLI, a store's check of a `listing.json` through\n * `readAppListing`) passes `strict` and refuses it, so a misspelt key is caught before anything is signed. Required\n * keys, their types and their bounds hold in both, and `APP_FORBIDDEN_KEYS` are refused in both, at any level.\n */\nexport interface AppFormatOptions { strict?: boolean }\n\nfunction keysOf(value: Record<string, unknown>, required: readonly string[], optional: readonly string[], options: AppFormatOptions = {}): Check {\n // `__proto__` and its kin are refused in both modes, at any level (`findAppForbiddenKey`): a reader keeps what it ignores.\n const forbidden = findAppForbiddenKey(value);\n if (forbidden !== undefined) return { ok: false, reason: \"unknown-key\", detail: forbidden };\n for (const k of Object.keys(value)) {\n if (options.strict && !required.includes(k) && !optional.includes(k)) return { ok: false, reason: \"unknown-key\", detail: k };\n }\n for (const k of required) if (!(k in value)) return { ok: false, reason: \"missing-key\", detail: k };\n return fine;\n}\n\nconst LISTING_REQUIRED = [\"ref\", \"sequence\", \"digest\", \"urls\", \"title\", \"tagline\"] as const;\nconst LISTING_OPTIONAL = [\"category\", \"developer\", \"submitter\", \"repo\", \"support\"] as const;\n\n/** Checks one entry of `apps`, which is also the whole of a `listing.json`. An unknown key is ignored unless `strict`. */\nexport function checkAppListing(value: unknown, options: AppFormatOptions = {}): Check {\n if (!isObject(value)) return { ok: false, reason: \"bad-field\", detail: \"A listing is not an object\" };\n const keys = keysOf(value, LISTING_REQUIRED, LISTING_OPTIONAL, options);\n if (!keys.ok) return keys;\n const bad = (field: string): Check => ({ ok: false, reason: \"bad-field\", detail: `apps: ${field}` });\n if (!isAppRef(value.ref)) return bad(\"ref\");\n if (!isCount(value.sequence, 1)) return bad(\"sequence\");\n if (!isAppHash(value.digest)) return bad(\"digest\");\n const urls = value.urls;\n if (!Array.isArray(urls) || urls.length < 1 || urls.length > APP_STORE_LIMITS.urls || !urls.every(isAppUrl)) return bad(\"urls\");\n if (!isAppLine(value.title, APP_STORE_LIMITS.title, 1)) return bad(\"title\");\n if (!isAppLine(value.tagline, APP_STORE_LIMITS.tagline, 1)) return bad(\"tagline\");\n for (const k of [\"category\", \"developer\", \"submitter\"] as const) if (value[k] !== undefined && !isAppLine(value[k], APP_STORE_LIMITS.label, 1)) return bad(k);\n for (const k of [\"repo\", \"support\"] as const) if (value[k] !== undefined && !isAppUrl(value[k])) return bad(k);\n return fine;\n}\n\n/**\n * The first object key `text` writes twice in one object, as JSON.parse reads it (`\"title\"` is `title`), or null.\n * `text` is JSON that JSON.parse already took: one pass, each string read to its closing quote.\n */\nexport function repeatedJsonKey(text: string): string | null {\n /** Each open object's keys so far; null for an array. */\n const open: (Set<string> | null)[] = [];\n let keyNext = false;\n for (let i = 0; i < text.length; i++) {\n const c = text[i];\n if (c === \"\\\"\") {\n let end = i + 1;\n while (text[end] !== \"\\\"\") end += text[end] === \"\\\\\" ? 2 : 1;\n const keys = open[open.length - 1];\n if (keys && keyNext) {\n const key = JSON.parse(text.slice(i, end + 1)) as string;\n if (keys.has(key)) return key;\n keys.add(key);\n keyNext = false;\n }\n i = end;\n } else if (c === \"{\") { open.push(new Set()); keyNext = true; }\n else if (c === \"[\") open.push(null);\n else if (c === \"}\" || c === \"]\") open.pop();\n else if (c === \",\") keyNext = open[open.length - 1] !== null;\n }\n return null;\n}\n\n/**\n * Reads a `listing.json`: JSON holding exactly one listing (written by hand in release 1.2, so not required canonical).\n * A store reads it, as a writer: strict by default, so a misspelt key is refused before the owner signs the index (the\n * client never reads a `listing.json`, only the signed index). `{ strict: false }` reads it as a client reads an index\n * entry, ignoring a later key.\n */\nexport function readAppListing(text: string, options: AppFormatOptions = { strict: true }): { ok: true; listing: AppListing } | { ok: false; reason: AppStoreRefusal; detail?: string } {\n let value: unknown;\n try { value = JSON.parse(text); } catch (error) { return { ok: false, reason: \"not-json\", detail: String(error) }; }\n // JSON.parse keeps a key's last value, where a person reading the file sees the first: strict, both are refused.\n const twice = options.strict ? repeatedJsonKey(text) : null;\n if (twice !== null) return { ok: false, reason: \"not-json\", detail: `${JSON.stringify(twice)} is written twice` };\n const checked = checkAppListing(value, options);\n return checked.ok ? { ok: true, listing: value as AppListing } : checked;\n}\n\nfunction checkRemoval(value: unknown, options: AppFormatOptions): Check {\n if (!isObject(value)) return { ok: false, reason: \"bad-field\", detail: \"A removal is not an object\" };\n const keys = keysOf(value, [\"ref\", \"digest\", \"reason\", \"at\"], [], options);\n if (!keys.ok) return keys;\n if (!isAppRef(value.ref) || !isAppHash(value.digest) || !isAppLine(value.reason, APP_STORE_LIMITS.reason, 1) || !isCount(value.at, 0)) {\n return { ok: false, reason: \"bad-field\", detail: \"removed: not {ref, digest, reason, at}\" };\n }\n return fine;\n}\n\nconst STORE_REQUIRED = [\"ghostlyStore\", \"key\", \"name\", \"kind\", \"sequence\", \"expires\", \"apps\", \"removed\", \"revoked\"] as const;\n\n/** Runs a check written in steps to its end, in one go. */\nfunction inOneRun<T>(steps: Generator<void, T>): T {\n for (;;) {\n const step = steps.next();\n if (step.done) return step.value;\n }\n}\n\n/**\n * Checks an index's fields and bounds, and every revocation it carries (one that does not verify refuses the index:\n * the store copied it, so a broken one is the store's fault). The signature and `expires` are `readAppStore`'s. An\n * unknown key of the index, a listing or a removal is ignored unless `strict`; a revocation is its publisher's signed\n * statement and keeps its exact keys. With `checked`, a revocation it holds is not checked again.\n */\nexport function checkAppStoreIndex(value: unknown, options: AppFormatOptions = {}, checked?: AppRevocationsChecked): Check {\n const fields = inOneRun(checkAppStoreFieldsSteps(value, options));\n return fields.ok ? inOneRun(checkAppStoreRevocationsSteps(value as unknown as AppStoreIndex, checked)) : fields;\n}\n\n/**\n * The first half of `checkAppStoreIndex`: the fields and bounds, and the shape of every revocation, with no signature\n * checked. A step after each listing, removal and revocation (see `readAppStoreSteps`).\n */\nfunction* checkAppStoreFieldsSteps(value: unknown, options: AppFormatOptions = {}): Generator<void, Check> {\n if (!isObject(value)) return { ok: false, reason: \"bad-field\", detail: \"The index is not an object\" };\n if (value.ghostlyStore !== undefined && value.ghostlyStore !== 1) return { ok: false, reason: \"unsupported-format\", detail: \"ghostlyStore is not 1\" };\n const keys = keysOf(value, STORE_REQUIRED, [\"description\"], options);\n if (!keys.ok) return keys;\n const bad = (field: string): Check => ({ ok: false, reason: \"bad-field\", detail: field });\n if (!isAppKey(value.key)) return bad(\"key\");\n if (!isAppLine(value.name, APP_STORE_LIMITS.name, 1)) return bad(\"name\");\n if (value.description !== undefined && !isText(value.description, APP_STORE_LIMITS.description)) return bad(\"description\");\n if (!(APP_STORE_KINDS as readonly unknown[]).includes(value.kind)) return bad(\"kind\");\n if (!isCount(value.sequence, 1)) return bad(\"sequence\");\n if (!isCount(value.expires, 0)) return bad(\"expires\");\n const { apps, removed, revoked } = value;\n if (!Array.isArray(apps) || apps.length > APP_STORE_LIMITS.apps) return bad(\"apps\");\n const refs = new Set<string>();\n for (const listing of apps) {\n const checked = checkAppListing(listing, options);\n if (!checked.ok) return checked;\n const ref = (listing as { ref: string }).ref;\n if (refs.has(ref)) return { ok: false, reason: \"duplicate-app\", detail: ref };\n refs.add(ref);\n yield;\n }\n if (!Array.isArray(removed) || removed.length > APP_STORE_LIMITS.removed) return bad(\"removed\");\n for (const entry of removed) { const checked = checkRemoval(entry, options); if (!checked.ok) return checked; yield; }\n if (!Array.isArray(revoked) || revoked.length > APP_STORE_LIMITS.revoked) return bad(\"revoked\");\n for (const entry of revoked) {\n const read = readAppRevocationShape(entry);\n if (!read.ok) return { ok: false, reason: \"bad-revocation\", detail: read.detail ?? read.reason };\n yield;\n }\n return fine;\n}\n\n/** The second half: the signature of each revocation of an index whose fields hold, one step each. */\nfunction* checkAppStoreRevocationsSteps(index: AppStoreIndex, checked?: AppRevocationsChecked): Generator<void, Check> {\n for (const revocation of index.revoked) {\n const verified = verifyAppRevocation(revocation, checked);\n if (!verified.ok) return { ok: false, reason: \"bad-revocation\", detail: verified.reason };\n yield;\n }\n return fine;\n}\n\nexport interface AppStoreReading {\n index: AppStoreIndex;\n /** SHA-256 of the index's bytes, base64url: what the update rule compares at one `sequence`. */\n digest: string;\n /** Past `expires`: it still installs, and the Apps page says when the store was last updated. */\n expired: boolean;\n}\n\nexport type AppStoreRead = { ok: true; store: AppStoreReading } | { ok: false; reason: AppStoreRefusal; detail?: string };\n\n/**\n * Reads `ghostly-store.json` with its `ghostly-store.sig`, in this order: size, JSON, canonical bytes, fields and the\n * shape of each revocation, the signature statement, the key the reader holds for this store (when it holds one), the\n * signature, the signature of each revocation, then `expires` against `now` (seconds): more than 90 days ahead is\n * refused, past is `expired`. The index's own signature comes before its revocations': an index nobody signed costs\n * its reader one signature check, whatever it carries. A key it does not know is ignored (a later store's optional\n * field) and stays in the bytes the signature covers. With `checked`, a revocation it holds is not checked again.\n */\nexport function readAppStore(indexBytes: Uint8Array, sigBytes: Uint8Array, now: number, heldKey?: string, checked?: AppRevocationsChecked): AppStoreRead {\n return inOneRun(readAppStoreSteps(indexBytes, sigBytes, now, heldKey, checked));\n}\n\n/**\n * `readAppStore` in steps, for a reader that shares its thread (a page): it stops after each listing, removal and\n * revocation, and after each revocation's signature check, so the caller can let the thread go between two `next()`\n * and an index of 4096 revocations never holds it for seconds. With `checked`, a revocation it holds is not checked again.\n */\nexport function* readAppStoreSteps(indexBytes: Uint8Array, sigBytes: Uint8Array, now: number, heldKey?: string, checked?: AppRevocationsChecked): Generator<void, AppStoreRead> {\n if (indexBytes.length > APP_STORE_LIMITS.indexBytes) return { ok: false, reason: \"too-large\" };\n const read = readCanonicalJson(indexBytes);\n if (!read.ok) return read;\n yield;\n const fields = yield* checkAppStoreFieldsSteps(read.value);\n if (!fields.ok) return fields;\n const index = read.value as unknown as AppStoreIndex;\n const statement = readAppSignature(sigBytes);\n if (!statement.ok) return statement;\n if (heldKey !== undefined && index.key !== heldKey) return { ok: false, reason: \"store-key\", detail: \"Another key than the store's\" };\n const signed = verifyAppSignature(APP_PREFIXES.store, indexBytes, statement.signature, index.key);\n if (!signed.ok) return signed;\n yield;\n const revocations = yield* checkAppStoreRevocationsSteps(index, checked);\n if (!revocations.ok) return revocations;\n if (index.expires > now + APP_STORE_LIMITS.expiresAheadS) return { ok: false, reason: \"expires-too-far\" };\n return { ok: true, store: { index, digest: toBase64Url(sha256(indexBytes)), expired: index.expires < now } };\n}\n\n/**\n * Signs an index with the store key: its canonical bytes and the `ghostly-store.sig` bytes. Throws on a bad index, and\n * on a key this format does not define: a writer is strict, so a misspelt key is never signed. With `revocations`, a\n * revocation it holds is not checked again.\n */\nexport async function signAppStore(index: AppStoreIndex, signer: Signer, revocations?: AppRevocationsChecked): Promise<{ indexBytes: Uint8Array; sigBytes: Uint8Array; signature: AppSignature }> {\n if (index.key !== toZ32(signer.publicKey)) throw new Error(\"A store index is signed by its own key\");\n const checked = checkAppStoreIndex(JSON.parse(JSON.stringify(index)), { strict: true }, revocations);\n if (!checked.ok) throw new Error(`Not a valid store index (${checked.reason}${checked.detail ? `: ${checked.detail}` : \"\"})`);\n const { bytes, signature } = await signAppObject(APP_PREFIXES.store, index, signer);\n return { indexBytes: bytes, sigBytes: canonicalJsonBytes(signature), signature };\n}\n","import { appRefPublisher, type SignedAppRevocation } from \"./appStatements\";\nimport type { AppRemoval, AppStoreKind } from \"./appStore\";\n\n/*\n * The client's rules for updates, rollback, removals and revocations (WISP 1200 · Updates and rollback, Takedowns), as\n * pure functions over what the client holds. A client keeps, per installed app, the reference (publisher key and\n * name), the highest `sequence` it has seen and the digest of that version; per store, its key, `sequence` and the\n * digest of its index. Where a version came from never matters: the bytes are checked, not the messenger.\n */\n\n/** A version of an app, as the client holds it or a checked bundle shows it. */\nexport interface AppVersion { ref: string; sequence: number; digest: string }\n\n/**\n * What a valid package means next to the installed one:\n * - `update`: the same app with a higher `sequence`, from anywhere;\n * - `same`: the version installed;\n * - `rollback`: a lower `sequence`, never installed over a higher one;\n * - `equivocation`: the same `sequence` with another digest; the client keeps what it runs, refuses the other and marks\n * the app (\"Two different versions 7 exist\");\n * - `other-app`: another reference (another publisher key or another name), never an update of this one.\n */\nexport type AppUpdateDecision = \"update\" | \"same\" | \"rollback\" | \"equivocation\" | \"other-app\";\n\nexport function appUpdateDecision(installed: AppVersion, candidate: AppVersion): AppUpdateDecision {\n if (installed.ref !== candidate.ref) return \"other-app\";\n if (candidate.sequence > installed.sequence) return \"update\";\n if (candidate.sequence < installed.sequence) return \"rollback\";\n return candidate.digest === installed.digest ? \"same\" : \"equivocation\";\n}\n\n/** The permissions an update adds: when there is any, the update waits for the person, who sees only these. */\nexport function addedAppPermissions(granted: readonly string[], requested: readonly string[]): string[] {\n return requested.filter((p) => !granted.includes(p));\n}\n\n/**\n * What to do with a newer package: install it (the permissions it keeps or drops apply by themselves) or ask about the\n * permissions it adds. Anything but `update` from `appUpdateDecision` is not installed.\n */\nexport type AppUpdatePlan =\n | { action: \"install\" }\n | { action: \"ask\"; added: string[] }\n | { action: \"refuse\"; decision: Exclude<AppUpdateDecision, \"update\"> };\n\nexport function planAppUpdate(installed: AppVersion & { permissions: readonly string[] }, candidate: AppVersion & { permissions: readonly string[] }): AppUpdatePlan {\n const decision = appUpdateDecision(installed, candidate);\n if (decision !== \"update\") return { action: \"refuse\", decision };\n const added = addedAppPermissions(installed.permissions, candidate.permissions);\n return added.length ? { action: \"ask\", added } : { action: \"install\" };\n}\n\n/**\n * The revocation that stops a version, or null: one signed by the app's own publisher (a reader verified it) that names\n * its digest, or reaches its `sequence` with `upTo`.\n */\nexport function appRevocationFor(version: AppVersion, revocations: readonly SignedAppRevocation[]): SignedAppRevocation | null {\n const publisher = appRefPublisher(version.ref);\n for (const r of revocations) {\n const s = r.statement;\n if (s.app !== version.ref || r.signature.key !== publisher) continue;\n if (\"digests\" in s ? s.digests.includes(version.digest) : version.sequence <= s.upTo) return r;\n }\n return null;\n}\n\n/** A store the person added, as the run check needs it. */\nexport interface AppStoreView { key: string; name: string; kind: AppStoreKind; removed: readonly AppRemoval[]; revoked: readonly SignedAppRevocation[] }\n\n/**\n * The check before Install is enabled, at every update check and before a run:\n * - `revoked`: its publisher revoked it; it stops, with no \"Run anyway\";\n * - `removed`: a store the person added removed this digest; it stops and the person decides (Remove, Keep it stopped,\n * or, behind Details, Run anyway);\n * - `ok`.\n * Revocations come from the app's sources and from every store's `revoked`; a store the person did not add has no say.\n */\nexport type AppRunCheck =\n | { status: \"ok\" }\n | { status: \"revoked\"; revocation: SignedAppRevocation }\n | { status: \"removed\"; by: { store: string; name: string; reason: string; at: number }[] };\n\nexport function checkAppBeforeRun(version: AppVersion, stores: readonly AppStoreView[], revocations: readonly SignedAppRevocation[] = []): AppRunCheck {\n for (const list of [revocations, ...stores.map((s) => s.revoked)]) {\n const revocation = appRevocationFor(version, indexed(list, (r) => r.statement.app).get(version.ref) ?? []);\n if (revocation) return { status: \"revoked\", revocation };\n }\n const by = stores.flatMap((s) => (indexed(s.removed, (r) => `${r.ref} ${r.digest}`).get(`${version.ref} ${version.digest}`) ?? [])\n .map((r) => ({ store: s.key, name: s.name, reason: r.reason, at: r.at })));\n return by.length ? { status: \"removed\", by } : { status: \"ok\" };\n}\n\n/*\n * A list's entries by key, in the list's order, made once per list: a store's `revoked` and `removed` reach 4096 entries\n * each (`APP_STORE_LIMITS`), and an app's every storage call, frame and read lane answer is checked against them. The\n * lists are never changed in place (a new index is a new list); one whose length changed is read again all the same.\n */\nconst indexes = new WeakMap<readonly object[], { length: number; byKey: Map<string, unknown[]> }>();\n\nfunction indexed<T extends object>(list: readonly T[], key: (entry: T) => string): Map<string, T[]> {\n const held = indexes.get(list);\n if (held && held.length === list.length) return held.byKey as Map<string, T[]>;\n const byKey = new Map<string, T[]>();\n for (const entry of list) {\n const k = key(entry);\n const same = byKey.get(k);\n if (same) same.push(entry);\n else byKey.set(k, [entry]);\n }\n indexes.set(list, { length: list.length, byKey });\n return byKey;\n}\n\n/** A store index as the client holds it. */\nexport interface AppStoreVersion { key: string; sequence: number; digest: string }\n\n/**\n * What a newly read index means next to the one held: `new` (none held), `update`, `same`, `rollback` (a lower\n * `sequence`, refused), `equivocation` (the same `sequence`, other bytes: refused, the held one kept) or `other-key`\n * (another store: a store is its key).\n */\nexport type AppStoreDecision = \"new\" | \"update\" | \"same\" | \"rollback\" | \"equivocation\" | \"other-key\";\n\nexport function appStoreDecision(held: AppStoreVersion | null, read: AppStoreVersion): AppStoreDecision {\n if (!held) return \"new\";\n if (held.key !== read.key) return \"other-key\";\n if (read.sequence > held.sequence) return \"update\";\n if (read.sequence < held.sequence) return \"rollback\";\n return read.digest === held.digest ? \"same\" : \"equivocation\";\n}\n","import { isAppUrl } from \"@ghostly/core\";\n\n/*\n * Where mini-apps and stores are read from (WISP 1200 § Stores, § Apps sent in a chat): in phase 1 only two hosts,\n * `raw.githubusercontent.com` and `cdn.jsdelivr.net` pinned to a full commit, both readable from a page (CORS `*`).\n * HTTPS only, no user or password, no port, no redirect (one would walk out of the list), no cookies, no referrer, and a\n * cap on the bytes read while the body streams in. Every read of the apps feature goes through `boundedAppFetch`.\n */\n\n/** The hosts phase 1 reads from. A jsDelivr URL must also name a 40-character commit (`isAppUrl`). */\nexport const APP_FETCH_HOSTS = [\"raw.githubusercontent.com\", \"cdn.jsdelivr.net\"] as const;\n\nexport const APP_FETCH_LIMITS = {\n /**\n * A store index as read (WISP 1200 § Stores, Privacy): 4 MiB in phase 1, under the format's 16 MiB. Counted on the body\n * as it arrives, after the browser undid any compression, since a page never sees the compressed size.\n */\n storeIndexBytes: 4 * 1024 * 1024,\n /** A store's signature statement, `ghostly-store.sig` (canonical, at most 1 KiB). */\n sigBytes: 1024,\n /** `ghostly-revoke.json`: at most 4096 signed revocations. */\n revocationsBytes: 16 * 1024 * 1024,\n /** How long the host has to answer (the response's headers). */\n timeoutMs: 30_000,\n /** How long the body may go without a byte: a read still arriving is never cut by the clock alone. */\n idleMs: 30_000,\n /** A whole read at most: the 16 MiB cap at about 224 kbit/s. */\n totalMs: 10 * 60_000,\n} as const;\n\n/** A URL this client may read an app, a store or a revocation list from. */\nexport function isAppFetchUrl(value: unknown): value is string {\n if (!isAppUrl(value)) return false;\n const url = new URL(value);\n return url.port === \"\" && (APP_FETCH_HOSTS as readonly string[]).includes(url.hostname.toLowerCase());\n}\n\n/** `slow`: the host did not answer in time, went silent, or the read ran past its whole budget. */\nexport type AppFetchErrorCode = \"host\" | \"offline\" | \"status\" | \"too-large\" | \"network\" | \"slow\";\n\nexport class AppFetchError extends Error {\n constructor(readonly code: AppFetchErrorCode, message: string, readonly status?: number) {\n // Its code first, as every error of the apps calls (`<code>: words`).\n super(`${code}: ${message}`);\n this.name = \"AppFetchError\";\n }\n}\n\n/**\n * Reads a URL of the list: its bytes, at most `maxBytes`. With `peek`, the first `maxBytes` bytes and no more, the rest\n * left unread (a bundle's manifest, to see whether it is newer before reading all of it). `signal` stops a read whose\n * bytes nobody will use any more (`network`). `revalidate`: a file every update check reads again (a store's index and\n * its sig, `ghostly-revoke.json`), kept by the browser and asked again with its ETag every time, so an unchanged one is\n * an empty 304 and never a copy the host was not asked about. Anything else is not kept by the browser (a bundle is\n * kept in file storage, a peek is a range).\n */\nexport type AppFetcher = (url: string, options: { maxBytes: number; peek?: boolean; revalidate?: boolean; signal?: AbortSignal }) => Promise<Uint8Array>;\n\nexport function boundedAppFetch(options: { fetcher?: typeof fetch; online?: () => boolean; timeoutMs?: number; idleMs?: number; totalMs?: number } = {}): AppFetcher {\n return async (url, { maxBytes, peek = false, revalidate = false, signal: stopped }) => {\n if (!isAppFetchUrl(url)) throw new AppFetchError(\"host\", \"Apps are read only from raw.githubusercontent.com, or from cdn.jsdelivr.net at a commit, over HTTPS\");\n if (options.online && !options.online()) throw new AppFetchError(\"offline\", \"Offline\");\n if (stopped?.aborted) throw new AppFetchError(\"network\", \"The read was stopped\");\n const fetcher = options.fetcher ?? globalThis.fetch.bind(globalThis);\n // One signal for the request and its body: the host has `timeoutMs` to answer, then the body `idleMs` between two\n // bytes, the whole read `totalMs`. A read still arriving goes on; one cut by the clock is `slow`, not `network`.\n const controller = new AbortController();\n const cut = () => { controller.abort(new DOMException(\"The read took too long\", \"TimeoutError\")); };\n const stop = () => { controller.abort(new DOMException(\"The read was stopped\", \"AbortError\")); };\n stopped?.addEventListener(\"abort\", stop);\n const total = setTimeout(cut, options.totalMs ?? APP_FETCH_LIMITS.totalMs);\n let idle = setTimeout(cut, options.timeoutMs ?? APP_FETCH_LIMITS.timeoutMs);\n const heard = () => { clearTimeout(idle); idle = setTimeout(cut, options.idleMs ?? APP_FETCH_LIMITS.idleMs); };\n const failure = (error: unknown) => stopped?.aborted ? new AppFetchError(\"network\", \"The read was stopped\")\n : controller.signal.aborted ? new AppFetchError(\"slow\", \"That took too long on this connection\")\n : new AppFetchError(\"network\", error instanceof Error ? error.message : String(error));\n const { signal } = controller;\n let response: Response;\n try {\n response = await fetcher(url, {\n signal,\n credentials: \"omit\", referrerPolicy: \"no-referrer\", cache: revalidate && !peek ? \"no-cache\" : \"no-store\", redirect: \"error\",\n ...(peek && { headers: { range: `bytes=0-${maxBytes - 1}` } }),\n });\n } catch (error) {\n clearTimeout(total); clearTimeout(idle); stopped?.removeEventListener(\"abort\", stop);\n throw failure(error);\n }\n heard();\n const parts: Uint8Array[] = [];\n let length = 0;\n try {\n // A redirect a fetcher followed after all (one that ignores `redirect`) still lands only on a host of the list.\n if (response.url && response.url !== url && !isAppFetchUrl(response.url)) throw new AppFetchError(\"host\", \"The host sent the request elsewhere\");\n if (!response.ok) {\n await response.body?.cancel().catch(() => {});\n throw new AppFetchError(\"status\", `The host answered ${response.status}`, response.status);\n }\n if (!peek && Number(response.headers.get(\"content-length\")) > maxBytes) {\n await response.body?.cancel().catch(() => {});\n throw new AppFetchError(\"too-large\", \"Too large\");\n }\n const reader = response.body?.getReader();\n if (reader) {\n // A body the signal does not reach (a fetcher of its own) is let go all the same: its pending read ends.\n const letGo = () => { reader.cancel().catch(() => {}); };\n signal.addEventListener(\"abort\", letGo);\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (signal.aborted) throw failure(signal.reason);\n if (done) break;\n heard();\n if (length + value.length > maxBytes) {\n if (!peek) throw new AppFetchError(\"too-large\", \"Too large\");\n parts.push(value.subarray(0, maxBytes - length));\n length = maxBytes;\n break;\n }\n parts.push(value);\n length += value.length;\n }\n } catch (error) {\n if (error instanceof AppFetchError) throw error;\n throw failure(error);\n } finally {\n signal.removeEventListener(\"abort\", letGo);\n await reader.cancel().catch(() => {});\n }\n }\n } finally { clearTimeout(total); clearTimeout(idle); stopped?.removeEventListener(\"abort\", stop); }\n const bytes = new Uint8Array(length);\n let at = 0;\n for (const part of parts) { bytes.set(part, at); at += part.length; }\n return bytes;\n };\n}\n\nconst NAME = /^[A-Za-z0-9_.-]+$/;\n\n/**\n * The URL a pasted address reads `file` from (WISP 1200 § Paste a URL), or null when it is not one this client reads:\n * - `https://github.com/<owner>/<repo>`, or `/tree/<ref>`: `raw.githubusercontent.com/<owner>/<repo>/<ref or HEAD>/<file>`,\n * with no request to `github.com` or `api.github.com`;\n * - a file as GitHub shows it, `https://github.com/<owner>/<repo>/blob/<ref>/<path>` (or `/raw/`), naming a `.ghostlyapp`\n * or `.json` file: `raw.githubusercontent.com/<owner>/<repo>/<ref>/<path>`, again with no request to `github.com`;\n * - a URL of the list that names a file (`….ghostlyapp`, `….json`): itself;\n * - a URL of the list that names a folder: `<file>` in it.\n */\nexport function appPasteUrl(input: string, file: \"app.ghostlyapp\" | \"ghostly-store.json\"): string | null {\n let url: URL;\n try { url = new URL(input.trim()); } catch { return null; }\n if (url.protocol !== \"https:\" || url.username || url.password || url.port) return null;\n const host = url.hostname.toLowerCase();\n if (host === \"github.com\" || host === \"www.github.com\") {\n const parts = url.pathname.split(\"/\").filter(Boolean);\n if (parts.length < 2) return null;\n const owner = parts[0]!, repo = parts[1]!.replace(/\\.git$/, \"\");\n if (!NAME.test(owner) || !NAME.test(repo)) return null;\n let ref = \"HEAD\";\n if (parts.length > 2) {\n const rest = parts.slice(3);\n if (!rest.length || !rest.every((p) => NAME.test(p) && p !== \".\" && p !== \"..\")) return null;\n if (parts[2] === \"blob\" || parts[2] === \"raw\") {\n // `<ref>/<path>`: raw.githubusercontent.com takes the two joined the same way github.com does.\n if (rest.length < 2 || !/\\.(ghostlyapp|json)$/.test(rest[rest.length - 1]!)) return null;\n const raw = `https://raw.githubusercontent.com/${owner}/${repo}/${rest.join(\"/\")}`;\n return isAppFetchUrl(raw) ? raw : null;\n }\n if (parts[2] !== \"tree\") return null;\n ref = rest.join(\"/\");\n }\n const raw = `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/${file}`;\n return isAppFetchUrl(raw) ? raw : null;\n }\n const last = url.pathname.split(\"/\").pop() ?? \"\";\n const named = /\\.(ghostlyapp|json)$/.test(last) ? url.href : new URL(`${url.pathname.replace(/\\/?$/, \"/\")}${file}`, url).href;\n return isAppFetchUrl(named) ? named : null;\n}\n\n/** A page of github.com (any scheme): a link `appPasteUrl` could not read is still GitHub, and is answered as such. */\nexport function isGitHubPage(input: string): boolean {\n try {\n const host = new URL(input.trim()).hostname.toLowerCase();\n return host === \"github.com\" || host === \"www.github.com\";\n } catch { return false; }\n}\n\n/** A file beside another (`ghostly-store.sig` beside the index, `ghostly-revoke.json` beside a bundle). */\nexport function besideUrl(url: string, name: string): string {\n const target = new URL(url);\n target.search = \"\";\n target.hash = \"\";\n return new URL(name, target).href;\n}\n"],"mappings":";;;;;;;AAmBA,SAAgB,WAAW,MAA0B;CACnD,IAAI,KAAK,WAAW,IAAI,MAAM,IAAI,MAAM,+BAA+B;CAEvE,OAAO;EAAE,WADS,QAAQ,aAAa,IAC9B;EAAW,MAAM,OAAO,UAAU,KAAK,OAAO,IAAI;CAAE;AAC/D;;;;;AAMA,SAAgB,gBAAgB,YAAuB,WAA+B;CACpF,IAAI,UAAU,WAAW,IAAI,MAAM,IAAI,MAAM,mCAAmC;CAChF,OAAO;EACL;EACA,MAAM,OAAO,UAAU,IAAI,WAAW,MAAM,OAAO,OAAO,KAAK,EAAE,MAAM,UAAU,GAAG,YAAY,IAAI,WAAW,KAAK,CAAC,CAAC;CACxH;AACF;;AChBA,IAAa,mBAAmB;;CAE9B,YAAY;;CAEZ,eAAe;CACf,MAAM;CACN,aAAa;CACb,OAAO;CACP,SAAS;;CAET,OAAO;CACP,QAAQ;CACR,MAAM;CACN,MAAM;CACN,SAAS;CACT,SAAS;AACX;AAEA,IAAa,kBAAkB,CAAC,WAAW,SAAS;AAmCpD,IAAM,YAAY,MAA+C,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AACxH,IAAM,UAAU,GAAY,QAA6B,OAAO,MAAM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,MAAM,MAAM,qCAAqC,MAAM,GAAG,KAAK,GAAG,KAAK,KAAK,GAAG;IAC/E,OAAO,cAAc,GAAG,IAAI,MAAM;GACpC;GACA,IAAI,MAAM,OAAO,QAAQ,OAAO;GAChC,MAAM,KAAK,KAAK,GAAG;EACrB;EACA,MAAM,MAAM,qCAAqC,MAAM,GAAG,KAAK,GAAG,IAAI,GAAG;EACzE,OAAO,cAAc,GAAG,IAAI,MAAM;CACpC;CACA,MAAM,OAAO,IAAI,SAAS,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;CAC9C,MAAM,QAAQ,uBAAuB,KAAK,IAAI,IAAI,IAAI,OAAO,IAAI,IAAI,GAAG,IAAI,SAAS,QAAQ,QAAQ,GAAG,IAAI,QAAQ,GAAG,CAAC,CAAC;CACzH,OAAO,cAAc,KAAK,IAAI,QAAQ;AACxC;;AAGA,SAAgB,aAAa,OAAwB;CACnD,IAAI;EACF,MAAM,OAAO,IAAI,IAAI,MAAM,KAAK,CAAC,CAAC,CAAC,SAAS,YAAY;EACxD,OAAO,SAAS,gBAAgB,SAAS;CAC3C,QAAQ;EAAE,OAAO;CAAO;AAC1B;;AAGA,SAAgB,UAAU,KAAa,MAAsB;CAC3D,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,OAAO,SAAS;CAChB,OAAO,OAAO;CACd,OAAO,IAAI,IAAI,MAAM,MAAM,CAAC,CAAC;AAC/B"}
|
|
1
|
+
{"version":3,"file":"appFetch-Ca9DNQQ2.js","names":[],"sources":["../../../core/src/signer.ts","../../../core/src/appStore.ts","../../../core/src/appUpdates.ts","../../../browser/src/engine/appFetch.ts"],"sourcesContent":["import { ed25519 } from \"@noble/curves/ed25519.js\";\nimport { sign } from \"./identity\";\n\n/*\n * A signer (WISP 06 § Terms): an Ed25519 key that signs without the caller holding its seed. The device signing key\n * is non-extractable where WebCrypto offers Ed25519, so the app has no bytes to sign with; where it does not, the key\n * is a stored seed. Both are this one interface, and so is a chat's participation seed when a session is given one.\n *\n * Signing is asynchronous because WebCrypto is. The public key is known at once: a session puts it in its offer\n * before it signs anything.\n */\nexport interface Signer {\n /** The Ed25519 public key, 32 bytes. */\n readonly publicKey: Uint8Array;\n /** The 64-byte signature of `bytes`. */\n sign(bytes: Uint8Array): Promise<Uint8Array>;\n}\n\n/** A seed held by the app, as every key of a profile is today. */\nexport function seedSigner(seed: Uint8Array): Signer {\n if (seed.length !== 32) throw new Error(\"Seed must be exactly 32 bytes\");\n const publicKey = ed25519.getPublicKey(seed);\n return { publicKey, sign: async (bytes) => sign(bytes, seed) };\n}\n\n/**\n * A WebCrypto Ed25519 private key, non-extractable or not, with its raw public key. The app never sees the private\n * bytes: `crypto.subtle` signs.\n */\nexport function webCryptoSigner(privateKey: CryptoKey, publicKey: Uint8Array): Signer {\n if (publicKey.length !== 32) throw new Error(\"An Ed25519 public key is 32 bytes\");\n return {\n publicKey,\n sign: async (bytes) => new Uint8Array(await crypto.subtle.sign({ name: \"Ed25519\" }, privateKey, new Uint8Array(bytes))),\n };\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { toBase64Url, toZ32 } from \"./bytes\";\nimport { canonicalJsonBytes, readCanonicalJson, type JsonValue } from \"./canonicalJson\";\nimport { findAppForbiddenKey, isAppUrl } from \"./appBundle\";\nimport {\n APP_PREFIXES, isAppHash, isAppKey, isAppLine, isAppRef, readAppRevocationShape, readAppSignature, signAppObject, verifyAppRevocation, verifyAppSignature,\n type AppRevocationsChecked, type AppSignature, type SignedAppRevocation,\n} from \"./appStatements\";\nimport type { Signer } from \"./signer\";\n\n/*\n * A store index (WISP 1200 · Stores): `ghostly-store.json`, canonical JSON, signed by the store key under\n * `ghostly-store/1` in `ghostly-store.sig` beside it (the same statement as a bundle's). It lists apps by reference and\n * digest, the versions it removed, and publishers' revocations copied verbatim. Times are Unix seconds.\n *\n * A store lists and ranks; it never changes what installs: the bundle a listing points at is checked on its own, and\n * its icon and description come from the bundle. `listing.json` in a store's repository is one entry of `apps`.\n */\n\nexport const APP_STORE_LIMITS = {\n /** The index's bytes, uncompressed. */\n indexBytes: 16 * 1024 * 1024,\n /** How far ahead `expires` may be. */\n expiresAheadS: 90 * 24 * 60 * 60,\n name: 40,\n description: 2000,\n title: 40,\n tagline: 80,\n /** `category`, `developer`, `submitter`. */\n label: 40,\n reason: 200,\n urls: 4,\n apps: 4096,\n removed: 4096,\n revoked: 4096,\n} as const;\n\nexport const APP_STORE_KINDS = [\"curated\", \"indexed\"] as const;\nexport type AppStoreKind = typeof APP_STORE_KINDS[number];\n\nexport interface AppListing {\n ref: string;\n sequence: number;\n digest: string;\n urls: string[];\n title: string;\n tagline: string;\n category?: string;\n developer?: string;\n submitter?: string;\n repo?: string;\n support?: string;\n}\nexport interface AppRemoval { ref: string; digest: string; reason: string; at: number }\nexport interface AppStoreIndex {\n ghostlyStore: 1;\n key: string;\n name: string;\n description?: string;\n kind: AppStoreKind;\n sequence: number;\n expires: number;\n apps: AppListing[];\n removed: AppRemoval[];\n revoked: SignedAppRevocation[];\n}\n\nexport type AppStoreRefusal =\n | \"too-large\" | \"not-json\" | \"not-canonical\" | \"unsupported-format\" | \"unknown-key\" | \"missing-key\" | \"bad-field\"\n | \"duplicate-app\" | \"bad-signature-statement\" | \"signature-key\" | \"bad-signature\" | \"store-key\" | \"expires-too-far\"\n | \"bad-revocation\";\n\nconst isObject = (v: unknown): v is Record<string, JsonValue> => typeof v === \"object\" && v !== null && !Array.isArray(v);\nconst isText = (v: unknown, max: number): v is string => typeof v === \"string\" && [...v].length <= max && !/[^\\P{Cc}\\n]/u.test(v);\nconst isCount = (v: unknown, min: number): v is number => typeof v === \"number\" && Number.isSafeInteger(v) && v >= min;\n\ntype Check = { ok: true } | { ok: false; reason: AppStoreRefusal; detail?: string };\nconst fine: Check = { ok: true };\n\n/**\n * How a check treats a key it does not know. A reader (`readAppStore`, the client) ignores it, so a later format can\n * add an optional key without a client refusing the whole signed index; the signature still covers the bytes as they\n * are, unknown keys included. A writer (`signAppStore`, the CLI, a store's check of a `listing.json` through\n * `readAppListing`) passes `strict` and refuses it, so a misspelt key is caught before anything is signed. Required\n * keys, their types and their bounds hold in both, and `APP_FORBIDDEN_KEYS` are refused in both, at any level.\n */\nexport interface AppFormatOptions { strict?: boolean }\n\nfunction keysOf(value: Record<string, unknown>, required: readonly string[], optional: readonly string[], options: AppFormatOptions = {}): Check {\n // `__proto__` and its kin are refused in both modes, at any level (`findAppForbiddenKey`): a reader keeps what it ignores.\n const forbidden = findAppForbiddenKey(value);\n if (forbidden !== undefined) return { ok: false, reason: \"unknown-key\", detail: forbidden };\n for (const k of Object.keys(value)) {\n if (options.strict && !required.includes(k) && !optional.includes(k)) return { ok: false, reason: \"unknown-key\", detail: k };\n }\n for (const k of required) if (!(k in value)) return { ok: false, reason: \"missing-key\", detail: k };\n return fine;\n}\n\nconst LISTING_REQUIRED = [\"ref\", \"sequence\", \"digest\", \"urls\", \"title\", \"tagline\"] as const;\nconst LISTING_OPTIONAL = [\"category\", \"developer\", \"submitter\", \"repo\", \"support\"] as const;\n\n/** Checks one entry of `apps`, which is also the whole of a `listing.json`. An unknown key is ignored unless `strict`. */\nexport function checkAppListing(value: unknown, options: AppFormatOptions = {}): Check {\n if (!isObject(value)) return { ok: false, reason: \"bad-field\", detail: \"A listing is not an object\" };\n const keys = keysOf(value, LISTING_REQUIRED, LISTING_OPTIONAL, options);\n if (!keys.ok) return keys;\n const bad = (field: string): Check => ({ ok: false, reason: \"bad-field\", detail: `apps: ${field}` });\n if (!isAppRef(value.ref)) return bad(\"ref\");\n if (!isCount(value.sequence, 1)) return bad(\"sequence\");\n if (!isAppHash(value.digest)) return bad(\"digest\");\n const urls = value.urls;\n if (!Array.isArray(urls) || urls.length < 1 || urls.length > APP_STORE_LIMITS.urls || !urls.every(isAppUrl)) return bad(\"urls\");\n if (!isAppLine(value.title, APP_STORE_LIMITS.title, 1)) return bad(\"title\");\n if (!isAppLine(value.tagline, APP_STORE_LIMITS.tagline, 1)) return bad(\"tagline\");\n for (const k of [\"category\", \"developer\", \"submitter\"] as const) if (value[k] !== undefined && !isAppLine(value[k], APP_STORE_LIMITS.label, 1)) return bad(k);\n for (const k of [\"repo\", \"support\"] as const) if (value[k] !== undefined && !isAppUrl(value[k])) return bad(k);\n return fine;\n}\n\n/**\n * The first object key `text` writes twice in one object, as JSON.parse reads it (`\"title\"` is `title`), or null.\n * `text` is JSON that JSON.parse already took: one pass, each string read to its closing quote.\n */\nexport function repeatedJsonKey(text: string): string | null {\n /** Each open object's keys so far; null for an array. */\n const open: (Set<string> | null)[] = [];\n let keyNext = false;\n for (let i = 0; i < text.length; i++) {\n const c = text[i];\n if (c === \"\\\"\") {\n let end = i + 1;\n while (text[end] !== \"\\\"\") end += text[end] === \"\\\\\" ? 2 : 1;\n const keys = open[open.length - 1];\n if (keys && keyNext) {\n const key = JSON.parse(text.slice(i, end + 1)) as string;\n if (keys.has(key)) return key;\n keys.add(key);\n keyNext = false;\n }\n i = end;\n } else if (c === \"{\") { open.push(new Set()); keyNext = true; }\n else if (c === \"[\") open.push(null);\n else if (c === \"}\" || c === \"]\") open.pop();\n else if (c === \",\") keyNext = open[open.length - 1] !== null;\n }\n return null;\n}\n\n/**\n * Reads a `listing.json`: JSON holding exactly one listing (written by hand in release 1.2, so not required canonical).\n * A store reads it, as a writer: strict by default, so a misspelt key is refused before the owner signs the index (the\n * client never reads a `listing.json`, only the signed index). `{ strict: false }` reads it as a client reads an index\n * entry, ignoring a later key.\n */\nexport function readAppListing(text: string, options: AppFormatOptions = { strict: true }): { ok: true; listing: AppListing } | { ok: false; reason: AppStoreRefusal; detail?: string } {\n let value: unknown;\n try { value = JSON.parse(text); } catch (error) { return { ok: false, reason: \"not-json\", detail: String(error) }; }\n // JSON.parse keeps a key's last value, where a person reading the file sees the first: strict, both are refused.\n const twice = options.strict ? repeatedJsonKey(text) : null;\n if (twice !== null) return { ok: false, reason: \"not-json\", detail: `${JSON.stringify(twice)} is written twice` };\n const checked = checkAppListing(value, options);\n return checked.ok ? { ok: true, listing: value as AppListing } : checked;\n}\n\nfunction checkRemoval(value: unknown, options: AppFormatOptions): Check {\n if (!isObject(value)) return { ok: false, reason: \"bad-field\", detail: \"A removal is not an object\" };\n const keys = keysOf(value, [\"ref\", \"digest\", \"reason\", \"at\"], [], options);\n if (!keys.ok) return keys;\n if (!isAppRef(value.ref) || !isAppHash(value.digest) || !isAppLine(value.reason, APP_STORE_LIMITS.reason, 1) || !isCount(value.at, 0)) {\n return { ok: false, reason: \"bad-field\", detail: \"removed: not {ref, digest, reason, at}\" };\n }\n return fine;\n}\n\nconst STORE_REQUIRED = [\"ghostlyStore\", \"key\", \"name\", \"kind\", \"sequence\", \"expires\", \"apps\", \"removed\", \"revoked\"] as const;\n\n/** Runs a check written in steps to its end, in one go. */\nfunction inOneRun<T>(steps: Generator<void, T>): T {\n for (;;) {\n const step = steps.next();\n if (step.done) return step.value;\n }\n}\n\n/**\n * Checks an index's fields and bounds, and every revocation it carries (one that does not verify refuses the index:\n * the store copied it, so a broken one is the store's fault). The signature and `expires` are `readAppStore`'s. An\n * unknown key of the index, a listing or a removal is ignored unless `strict`; a revocation is its publisher's signed\n * statement and keeps its exact keys. With `checked`, a revocation it holds is not checked again.\n */\nexport function checkAppStoreIndex(value: unknown, options: AppFormatOptions = {}, checked?: AppRevocationsChecked): Check {\n const fields = inOneRun(checkAppStoreFieldsSteps(value, options));\n return fields.ok ? inOneRun(checkAppStoreRevocationsSteps(value as unknown as AppStoreIndex, checked)) : fields;\n}\n\n/**\n * The first half of `checkAppStoreIndex`: the fields and bounds, and the shape of every revocation, with no signature\n * checked. A step after each listing, removal and revocation (see `readAppStoreSteps`).\n */\nfunction* checkAppStoreFieldsSteps(value: unknown, options: AppFormatOptions = {}): Generator<void, Check> {\n if (!isObject(value)) return { ok: false, reason: \"bad-field\", detail: \"The index is not an object\" };\n if (value.ghostlyStore !== undefined && value.ghostlyStore !== 1) return { ok: false, reason: \"unsupported-format\", detail: \"ghostlyStore is not 1\" };\n const keys = keysOf(value, STORE_REQUIRED, [\"description\"], options);\n if (!keys.ok) return keys;\n const bad = (field: string): Check => ({ ok: false, reason: \"bad-field\", detail: field });\n if (!isAppKey(value.key)) return bad(\"key\");\n if (!isAppLine(value.name, APP_STORE_LIMITS.name, 1)) return bad(\"name\");\n if (value.description !== undefined && !isText(value.description, APP_STORE_LIMITS.description)) return bad(\"description\");\n if (!(APP_STORE_KINDS as readonly unknown[]).includes(value.kind)) return bad(\"kind\");\n if (!isCount(value.sequence, 1)) return bad(\"sequence\");\n if (!isCount(value.expires, 0)) return bad(\"expires\");\n const { apps, removed, revoked } = value;\n if (!Array.isArray(apps) || apps.length > APP_STORE_LIMITS.apps) return bad(\"apps\");\n const refs = new Set<string>();\n for (const listing of apps) {\n const checked = checkAppListing(listing, options);\n if (!checked.ok) return checked;\n const ref = (listing as { ref: string }).ref;\n if (refs.has(ref)) return { ok: false, reason: \"duplicate-app\", detail: ref };\n refs.add(ref);\n yield;\n }\n if (!Array.isArray(removed) || removed.length > APP_STORE_LIMITS.removed) return bad(\"removed\");\n for (const entry of removed) { const checked = checkRemoval(entry, options); if (!checked.ok) return checked; yield; }\n if (!Array.isArray(revoked) || revoked.length > APP_STORE_LIMITS.revoked) return bad(\"revoked\");\n for (const entry of revoked) {\n const read = readAppRevocationShape(entry);\n if (!read.ok) return { ok: false, reason: \"bad-revocation\", detail: read.detail ?? read.reason };\n yield;\n }\n return fine;\n}\n\n/** The second half: the signature of each revocation of an index whose fields hold, one step each. */\nfunction* checkAppStoreRevocationsSteps(index: AppStoreIndex, checked?: AppRevocationsChecked): Generator<void, Check> {\n for (const revocation of index.revoked) {\n const verified = verifyAppRevocation(revocation, checked);\n if (!verified.ok) return { ok: false, reason: \"bad-revocation\", detail: verified.reason };\n yield;\n }\n return fine;\n}\n\nexport interface AppStoreReading {\n index: AppStoreIndex;\n /** SHA-256 of the index's bytes, base64url: what the update rule compares at one `sequence`. */\n digest: string;\n /** Past `expires`: it still installs, and the Apps page says when the store was last updated. */\n expired: boolean;\n}\n\nexport type AppStoreRead = { ok: true; store: AppStoreReading } | { ok: false; reason: AppStoreRefusal; detail?: string };\n\n/**\n * Reads `ghostly-store.json` with its `ghostly-store.sig`, in this order: size, JSON, canonical bytes, fields and the\n * shape of each revocation, the signature statement, the key the reader holds for this store (when it holds one), the\n * signature, the signature of each revocation, then `expires` against `now` (seconds): more than 90 days ahead is\n * refused, past is `expired`. The index's own signature comes before its revocations': an index nobody signed costs\n * its reader one signature check, whatever it carries. A key it does not know is ignored (a later store's optional\n * field) and stays in the bytes the signature covers. With `checked`, a revocation it holds is not checked again.\n */\nexport function readAppStore(indexBytes: Uint8Array, sigBytes: Uint8Array, now: number, heldKey?: string, checked?: AppRevocationsChecked): AppStoreRead {\n return inOneRun(readAppStoreSteps(indexBytes, sigBytes, now, heldKey, checked));\n}\n\n/**\n * `readAppStore` in steps, for a reader that shares its thread (a page): it stops after each listing, removal and\n * revocation, and after each revocation's signature check, so the caller can let the thread go between two `next()`\n * and an index of 4096 revocations never holds it for seconds. With `checked`, a revocation it holds is not checked again.\n */\nexport function* readAppStoreSteps(indexBytes: Uint8Array, sigBytes: Uint8Array, now: number, heldKey?: string, checked?: AppRevocationsChecked): Generator<void, AppStoreRead> {\n if (indexBytes.length > APP_STORE_LIMITS.indexBytes) return { ok: false, reason: \"too-large\" };\n const read = readCanonicalJson(indexBytes);\n if (!read.ok) return read;\n yield;\n const fields = yield* checkAppStoreFieldsSteps(read.value);\n if (!fields.ok) return fields;\n const index = read.value as unknown as AppStoreIndex;\n const statement = readAppSignature(sigBytes);\n if (!statement.ok) return statement;\n if (heldKey !== undefined && index.key !== heldKey) return { ok: false, reason: \"store-key\", detail: \"Another key than the store's\" };\n const signed = verifyAppSignature(APP_PREFIXES.store, indexBytes, statement.signature, index.key);\n if (!signed.ok) return signed;\n yield;\n const revocations = yield* checkAppStoreRevocationsSteps(index, checked);\n if (!revocations.ok) return revocations;\n if (index.expires > now + APP_STORE_LIMITS.expiresAheadS) return { ok: false, reason: \"expires-too-far\" };\n return { ok: true, store: { index, digest: toBase64Url(sha256(indexBytes)), expired: index.expires < now } };\n}\n\n/**\n * Signs an index with the store key: its canonical bytes and the `ghostly-store.sig` bytes. Throws on a bad index, and\n * on a key this format does not define: a writer is strict, so a misspelt key is never signed. With `revocations`, a\n * revocation it holds is not checked again.\n */\nexport async function signAppStore(index: AppStoreIndex, signer: Signer, revocations?: AppRevocationsChecked): Promise<{ indexBytes: Uint8Array; sigBytes: Uint8Array; signature: AppSignature }> {\n if (index.key !== toZ32(signer.publicKey)) throw new Error(\"A store index is signed by its own key\");\n const checked = checkAppStoreIndex(JSON.parse(JSON.stringify(index)), { strict: true }, revocations);\n if (!checked.ok) throw new Error(`Not a valid store index (${checked.reason}${checked.detail ? `: ${checked.detail}` : \"\"})`);\n const { bytes, signature } = await signAppObject(APP_PREFIXES.store, index, signer);\n return { indexBytes: bytes, sigBytes: canonicalJsonBytes(signature), signature };\n}\n","import { appRefPublisher, type SignedAppRevocation } from \"./appStatements\";\nimport type { AppRemoval, AppStoreKind } from \"./appStore\";\n\n/*\n * The client's rules for updates, rollback, removals and revocations (WISP 1200 · Updates and rollback, Takedowns), as\n * pure functions over what the client holds. A client keeps, per installed app, the reference (publisher key and\n * name), the highest `sequence` it has seen and the digest of that version; per store, its key, `sequence` and the\n * digest of its index. Where a version came from never matters: the bytes are checked, not the messenger.\n */\n\n/** A version of an app, as the client holds it or a checked bundle shows it. */\nexport interface AppVersion { ref: string; sequence: number; digest: string }\n\n/**\n * What a valid package means next to the installed one:\n * - `update`: the same app with a higher `sequence`, from anywhere;\n * - `same`: the version installed;\n * - `rollback`: a lower `sequence`, never installed over a higher one;\n * - `equivocation`: the same `sequence` with another digest; the client keeps what it runs, refuses the other and marks\n * the app (\"Two different versions 7 exist\");\n * - `other-app`: another reference (another publisher key or another name), never an update of this one.\n */\nexport type AppUpdateDecision = \"update\" | \"same\" | \"rollback\" | \"equivocation\" | \"other-app\";\n\nexport function appUpdateDecision(installed: AppVersion, candidate: AppVersion): AppUpdateDecision {\n if (installed.ref !== candidate.ref) return \"other-app\";\n if (candidate.sequence > installed.sequence) return \"update\";\n if (candidate.sequence < installed.sequence) return \"rollback\";\n return candidate.digest === installed.digest ? \"same\" : \"equivocation\";\n}\n\n/** The permissions an update adds: when there is any, the update waits for the person, who sees only these. */\nexport function addedAppPermissions(granted: readonly string[], requested: readonly string[]): string[] {\n return requested.filter((p) => !granted.includes(p));\n}\n\n/**\n * What to do with a newer package: install it (the permissions it keeps or drops apply by themselves) or ask about the\n * permissions it adds. Anything but `update` from `appUpdateDecision` is not installed.\n */\nexport type AppUpdatePlan =\n | { action: \"install\" }\n | { action: \"ask\"; added: string[] }\n | { action: \"refuse\"; decision: Exclude<AppUpdateDecision, \"update\"> };\n\nexport function planAppUpdate(installed: AppVersion & { permissions: readonly string[] }, candidate: AppVersion & { permissions: readonly string[] }): AppUpdatePlan {\n const decision = appUpdateDecision(installed, candidate);\n if (decision !== \"update\") return { action: \"refuse\", decision };\n const added = addedAppPermissions(installed.permissions, candidate.permissions);\n return added.length ? { action: \"ask\", added } : { action: \"install\" };\n}\n\n/**\n * The revocation that stops a version, or null: one signed by the app's own publisher (a reader verified it) that names\n * its digest, or reaches its `sequence` with `upTo`.\n */\nexport function appRevocationFor(version: AppVersion, revocations: readonly SignedAppRevocation[]): SignedAppRevocation | null {\n const publisher = appRefPublisher(version.ref);\n for (const r of revocations) {\n const s = r.statement;\n if (s.app !== version.ref || r.signature.key !== publisher) continue;\n if (\"digests\" in s ? s.digests.includes(version.digest) : version.sequence <= s.upTo) return r;\n }\n return null;\n}\n\n/** A store the person added, as the run check needs it. */\nexport interface AppStoreView { key: string; name: string; kind: AppStoreKind; removed: readonly AppRemoval[]; revoked: readonly SignedAppRevocation[] }\n\n/**\n * The check before Install is enabled, at every update check and before a run:\n * - `revoked`: its publisher revoked it; it stops, with no \"Run anyway\";\n * - `removed`: a store the person added removed this digest; it stops and the person decides (Remove, Keep it stopped,\n * or, behind Details, Run anyway);\n * - `ok`.\n * Revocations come from the app's sources and from every store's `revoked`; a store the person did not add has no say.\n */\nexport type AppRunCheck =\n | { status: \"ok\" }\n | { status: \"revoked\"; revocation: SignedAppRevocation }\n | { status: \"removed\"; by: { store: string; name: string; reason: string; at: number }[] };\n\nexport function checkAppBeforeRun(version: AppVersion, stores: readonly AppStoreView[], revocations: readonly SignedAppRevocation[] = []): AppRunCheck {\n for (const list of [revocations, ...stores.map((s) => s.revoked)]) {\n const revocation = appRevocationFor(version, indexed(list, (r) => r.statement.app).get(version.ref) ?? []);\n if (revocation) return { status: \"revoked\", revocation };\n }\n const by = stores.flatMap((s) => (indexed(s.removed, (r) => `${r.ref} ${r.digest}`).get(`${version.ref} ${version.digest}`) ?? [])\n .map((r) => ({ store: s.key, name: s.name, reason: r.reason, at: r.at })));\n return by.length ? { status: \"removed\", by } : { status: \"ok\" };\n}\n\n/*\n * A list's entries by key, in the list's order, made once per list: a store's `revoked` and `removed` reach 4096 entries\n * each (`APP_STORE_LIMITS`), and an app's every storage call, frame and read lane answer is checked against them. The\n * lists are never changed in place (a new index is a new list); one whose length changed is read again all the same.\n */\nconst indexes = new WeakMap<readonly object[], { length: number; byKey: Map<string, unknown[]> }>();\n\nfunction indexed<T extends object>(list: readonly T[], key: (entry: T) => string): Map<string, T[]> {\n const held = indexes.get(list);\n if (held && held.length === list.length) return held.byKey as Map<string, T[]>;\n const byKey = new Map<string, T[]>();\n for (const entry of list) {\n const k = key(entry);\n const same = byKey.get(k);\n if (same) same.push(entry);\n else byKey.set(k, [entry]);\n }\n indexes.set(list, { length: list.length, byKey });\n return byKey;\n}\n\n/** A store index as the client holds it. */\nexport interface AppStoreVersion { key: string; sequence: number; digest: string }\n\n/**\n * What a newly read index means next to the one held: `new` (none held), `update`, `same`, `rollback` (a lower\n * `sequence`, refused), `equivocation` (the same `sequence`, other bytes: refused, the held one kept) or `other-key`\n * (another store: a store is its key).\n */\nexport type AppStoreDecision = \"new\" | \"update\" | \"same\" | \"rollback\" | \"equivocation\" | \"other-key\";\n\nexport function appStoreDecision(held: AppStoreVersion | null, read: AppStoreVersion): AppStoreDecision {\n if (!held) return \"new\";\n if (held.key !== read.key) return \"other-key\";\n if (read.sequence > held.sequence) return \"update\";\n if (read.sequence < held.sequence) return \"rollback\";\n return read.digest === held.digest ? \"same\" : \"equivocation\";\n}\n","import { isAppUrl } from \"@ghostly/core\";\n\n/*\n * Where mini-apps and stores are read from (WISP 1200 § Stores, § Apps sent in a chat): in phase 1 only two hosts,\n * `raw.githubusercontent.com` and `cdn.jsdelivr.net` pinned to a full commit, both readable from a page (CORS `*`).\n * HTTPS only, no user or password, no port, no redirect (one would walk out of the list), no cookies, no referrer, and a\n * cap on the bytes read while the body streams in. Every read of the apps feature goes through `boundedAppFetch`.\n */\n\n/** The hosts phase 1 reads from. A jsDelivr URL must also name a 40-character commit (`isAppUrl`). */\nexport const APP_FETCH_HOSTS = [\"raw.githubusercontent.com\", \"cdn.jsdelivr.net\"] as const;\n\nexport const APP_FETCH_LIMITS = {\n /**\n * A store index as read (WISP 1200 § Stores, Privacy): 4 MiB in phase 1, under the format's 16 MiB. Counted on the body\n * as it arrives, after the browser undid any compression, since a page never sees the compressed size.\n */\n storeIndexBytes: 4 * 1024 * 1024,\n /** A store's signature statement, `ghostly-store.sig` (canonical, at most 1 KiB). */\n sigBytes: 1024,\n /** `ghostly-revoke.json`: at most 4096 signed revocations. */\n revocationsBytes: 16 * 1024 * 1024,\n /** How long the host has to answer (the response's headers). */\n timeoutMs: 30_000,\n /** How long the body may go without a byte: a read still arriving is never cut by the clock alone. */\n idleMs: 30_000,\n /** A whole read at most: the 16 MiB cap at about 224 kbit/s. */\n totalMs: 10 * 60_000,\n} as const;\n\n/** A URL this client may read an app, a store or a revocation list from. */\nexport function isAppFetchUrl(value: unknown): value is string {\n if (!isAppUrl(value)) return false;\n const url = new URL(value);\n return url.port === \"\" && (APP_FETCH_HOSTS as readonly string[]).includes(url.hostname.toLowerCase());\n}\n\n/** `slow`: the host did not answer in time, went silent, or the read ran past its whole budget. */\nexport type AppFetchErrorCode = \"host\" | \"offline\" | \"status\" | \"too-large\" | \"network\" | \"slow\";\n\nexport class AppFetchError extends Error {\n constructor(readonly code: AppFetchErrorCode, message: string, readonly status?: number) {\n // Its code first, as every error of the apps calls (`<code>: words`).\n super(`${code}: ${message}`);\n this.name = \"AppFetchError\";\n }\n}\n\n/**\n * Reads a URL of the list: its bytes, at most `maxBytes`. With `peek`, the first `maxBytes` bytes and no more, the rest\n * left unread (a bundle's manifest, to see whether it is newer before reading all of it). `signal` stops a read whose\n * bytes nobody will use any more (`network`). `revalidate`: a file every update check reads again (a store's index and\n * its sig, `ghostly-revoke.json`), kept by the browser and asked again with its ETag every time, so an unchanged one is\n * an empty 304 and never a copy the host was not asked about. Anything else is not kept by the browser (a bundle is\n * kept in file storage, a peek is a range).\n */\nexport type AppFetcher = (url: string, options: { maxBytes: number; peek?: boolean; revalidate?: boolean; signal?: AbortSignal }) => Promise<Uint8Array>;\n\nexport function boundedAppFetch(options: { fetcher?: typeof fetch; online?: () => boolean; timeoutMs?: number; idleMs?: number; totalMs?: number } = {}): AppFetcher {\n return async (url, { maxBytes, peek = false, revalidate = false, signal: stopped }) => {\n if (!isAppFetchUrl(url)) throw new AppFetchError(\"host\", \"Apps are read only from raw.githubusercontent.com, or from cdn.jsdelivr.net at a commit, over HTTPS\");\n if (options.online && !options.online()) throw new AppFetchError(\"offline\", \"Offline\");\n if (stopped?.aborted) throw new AppFetchError(\"network\", \"The read was stopped\");\n const fetcher = options.fetcher ?? globalThis.fetch.bind(globalThis);\n // One signal for the request and its body: the host has `timeoutMs` to answer, then the body `idleMs` between two\n // bytes, the whole read `totalMs`. A read still arriving goes on; one cut by the clock is `slow`, not `network`.\n const controller = new AbortController();\n const cut = () => { controller.abort(new DOMException(\"The read took too long\", \"TimeoutError\")); };\n const stop = () => { controller.abort(new DOMException(\"The read was stopped\", \"AbortError\")); };\n stopped?.addEventListener(\"abort\", stop);\n const total = setTimeout(cut, options.totalMs ?? APP_FETCH_LIMITS.totalMs);\n let idle = setTimeout(cut, options.timeoutMs ?? APP_FETCH_LIMITS.timeoutMs);\n const heard = () => { clearTimeout(idle); idle = setTimeout(cut, options.idleMs ?? APP_FETCH_LIMITS.idleMs); };\n const failure = (error: unknown) => stopped?.aborted ? new AppFetchError(\"network\", \"The read was stopped\")\n : controller.signal.aborted ? new AppFetchError(\"slow\", \"That took too long on this connection\")\n : new AppFetchError(\"network\", error instanceof Error ? error.message : String(error));\n const { signal } = controller;\n let response: Response;\n try {\n response = await fetcher(url, {\n signal,\n credentials: \"omit\", referrerPolicy: \"no-referrer\", cache: revalidate && !peek ? \"no-cache\" : \"no-store\", redirect: \"error\",\n ...(peek && { headers: { range: `bytes=0-${maxBytes - 1}` } }),\n });\n } catch (error) {\n clearTimeout(total); clearTimeout(idle); stopped?.removeEventListener(\"abort\", stop);\n throw failure(error);\n }\n heard();\n const parts: Uint8Array[] = [];\n let length = 0;\n try {\n // A redirect a fetcher followed after all (one that ignores `redirect`) still lands only on a host of the list.\n if (response.url && response.url !== url && !isAppFetchUrl(response.url)) throw new AppFetchError(\"host\", \"The host sent the request elsewhere\");\n if (!response.ok) {\n await response.body?.cancel().catch(() => {});\n throw new AppFetchError(\"status\", `The host answered ${response.status}`, response.status);\n }\n if (!peek && Number(response.headers.get(\"content-length\")) > maxBytes) {\n await response.body?.cancel().catch(() => {});\n throw new AppFetchError(\"too-large\", \"Too large\");\n }\n const reader = response.body?.getReader();\n if (reader) {\n // A body the signal does not reach (a fetcher of its own) is let go all the same: its pending read ends.\n const letGo = () => { reader.cancel().catch(() => {}); };\n signal.addEventListener(\"abort\", letGo);\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (signal.aborted) throw failure(signal.reason);\n if (done) break;\n heard();\n if (length + value.length > maxBytes) {\n if (!peek) throw new AppFetchError(\"too-large\", \"Too large\");\n parts.push(value.subarray(0, maxBytes - length));\n length = maxBytes;\n break;\n }\n parts.push(value);\n length += value.length;\n }\n } catch (error) {\n if (error instanceof AppFetchError) throw error;\n throw failure(error);\n } finally {\n signal.removeEventListener(\"abort\", letGo);\n await reader.cancel().catch(() => {});\n }\n }\n } finally { clearTimeout(total); clearTimeout(idle); stopped?.removeEventListener(\"abort\", stop); }\n const bytes = new Uint8Array(length);\n let at = 0;\n for (const part of parts) { bytes.set(part, at); at += part.length; }\n return bytes;\n };\n}\n\nconst NAME = /^[A-Za-z0-9_.-]+$/;\n\n/**\n * The URL a pasted address reads `file` from (WISP 1200 § Paste a URL), or null when it is not one this client reads:\n * - `https://github.com/<owner>/<repo>`, or `/tree/<ref>`: `raw.githubusercontent.com/<owner>/<repo>/<ref or HEAD>/<file>`,\n * with no request to `github.com` or `api.github.com`;\n * - a file as GitHub shows it, `https://github.com/<owner>/<repo>/blob/<ref>/<path>` (or `/raw/`), naming a `.ghostlyapp`\n * or `.json` file: `raw.githubusercontent.com/<owner>/<repo>/<ref>/<path>`, again with no request to `github.com`;\n * - a URL of the list that names a file (`….ghostlyapp`, `….json`): itself;\n * - a URL of the list that names a folder: `<file>` in it.\n */\nexport function appPasteUrl(input: string, file: \"app.ghostlyapp\" | \"ghostly-store.json\"): string | null {\n let url: URL;\n try { url = new URL(input.trim()); } catch { return null; }\n if (url.protocol !== \"https:\" || url.username || url.password || url.port) return null;\n const host = url.hostname.toLowerCase();\n if (host === \"github.com\" || host === \"www.github.com\") {\n const parts = url.pathname.split(\"/\").filter(Boolean);\n if (parts.length < 2) return null;\n const owner = parts[0]!, repo = parts[1]!.replace(/\\.git$/, \"\");\n if (!NAME.test(owner) || !NAME.test(repo)) return null;\n let ref = \"HEAD\";\n if (parts.length > 2) {\n const rest = parts.slice(3);\n if (!rest.length || !rest.every((p) => NAME.test(p) && p !== \".\" && p !== \"..\")) return null;\n if (parts[2] === \"blob\" || parts[2] === \"raw\") {\n // `<ref>/<path>`: raw.githubusercontent.com takes the two joined the same way github.com does.\n if (rest.length < 2 || !/\\.(ghostlyapp|json)$/.test(rest[rest.length - 1]!)) return null;\n const raw = `https://raw.githubusercontent.com/${owner}/${repo}/${rest.join(\"/\")}`;\n return isAppFetchUrl(raw) ? raw : null;\n }\n if (parts[2] !== \"tree\") return null;\n ref = rest.join(\"/\");\n }\n const raw = `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/${file}`;\n return isAppFetchUrl(raw) ? raw : null;\n }\n const last = url.pathname.split(\"/\").pop() ?? \"\";\n const named = /\\.(ghostlyapp|json)$/.test(last) ? url.href : new URL(`${url.pathname.replace(/\\/?$/, \"/\")}${file}`, url).href;\n return isAppFetchUrl(named) ? named : null;\n}\n\n/** A page of github.com (any scheme): a link `appPasteUrl` could not read is still GitHub, and is answered as such. */\nexport function isGitHubPage(input: string): boolean {\n try {\n const host = new URL(input.trim()).hostname.toLowerCase();\n return host === \"github.com\" || host === \"www.github.com\";\n } catch { return false; }\n}\n\n/** A file beside another (`ghostly-store.sig` beside the index, `ghostly-revoke.json` beside a bundle). */\nexport function besideUrl(url: string, name: string): string {\n const target = new URL(url);\n target.search = \"\";\n target.hash = \"\";\n return new URL(name, target).href;\n}\n"],"mappings":";;;;;;;AAmBA,SAAgB,WAAW,MAA0B;CACnD,IAAI,KAAK,WAAW,IAAI,MAAM,IAAI,MAAM,+BAA+B;CAEvE,OAAO;EAAE,WADS,QAAQ,aAAa,IAC9B;EAAW,MAAM,OAAO,UAAU,KAAK,OAAO,IAAI;CAAE;AAC/D;;;;;AAMA,SAAgB,gBAAgB,YAAuB,WAA+B;CACpF,IAAI,UAAU,WAAW,IAAI,MAAM,IAAI,MAAM,mCAAmC;CAChF,OAAO;EACL;EACA,MAAM,OAAO,UAAU,IAAI,WAAW,MAAM,OAAO,OAAO,KAAK,EAAE,MAAM,UAAU,GAAG,YAAY,IAAI,WAAW,KAAK,CAAC,CAAC;CACxH;AACF;;AChBA,IAAa,mBAAmB;;CAE9B,YAAY;;CAEZ,eAAe;CACf,MAAM;CACN,aAAa;CACb,OAA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ex, s as isAppFetchUrl, t as APP_FETCH_HOSTS, u as appRevocationFor, x as seedSigner, y as repeatedJsonKey } from "./appFetch-
|
|
1
|
+
import { Ba as isAppLine, Ca as assembleAppBundle, Ea as isAppUrl, Ja as signAppRevocation, Ka as setAppSignatureFastPath, La as checkAppRevokeStatement, Ma as APP_STATEMENT_LIMITS, Na as appFingerprint, Oa as readAppBundle, Pa as appRef, Ra as isAppHash, Wa as readAppRevocations, eo as canonicalJson, ja as APP_PREFIXES, qa as signAppObject, to as canonicalJsonBytes, va as APP_BUNDLE_LIMITS, wa as checkAppManifest } from "./groupMeta-CeZpqVVC.js";
|
|
2
|
+
import { _ as readAppStore, b as signAppStore, d as appStoreDecision, g as checkAppStoreIndex, s as isAppFetchUrl, t as APP_FETCH_HOSTS, u as appRevocationFor, x as seedSigner, y as repeatedJsonKey } from "./appFetch-Ca9DNQQ2.js";
|
|
3
3
|
import { i as fromBase64Url, l as toBase64Url, u as toZ32 } from "./bytes-C1DNGY18.js";
|
|
4
|
-
import { i as localFileError, t as CliError } from "./errors-
|
|
5
|
-
import {
|
|
6
|
-
import { t as guardText } from "./secretGuard-
|
|
7
|
-
import { S as userPath } from "./profiles-
|
|
4
|
+
import { i as localFileError, o as shownValue, t as CliError } from "./errors-JVJsO8Iu.js";
|
|
5
|
+
import { W as jsonOut } from "./apiKit-CPTFJHA7.js";
|
|
6
|
+
import { t as guardText } from "./secretGuard-oz_3hBfW.js";
|
|
7
|
+
import { S as userPath } from "./profiles-BH1bH9aE.js";
|
|
8
8
|
import { closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
|
|
9
9
|
import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
|
|
10
10
|
import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, verify } from "node:crypto";
|
|
@@ -485,9 +485,10 @@ async function verifyApp(source) {
|
|
|
485
485
|
}
|
|
486
486
|
/**
|
|
487
487
|
* The revocations of a `ghostly-revoke.json`, a URL or a file, as a client reads it. None there, one that does not
|
|
488
|
-
* answer, or one a client would not read, revokes nothing.
|
|
488
|
+
* answer, or one a client would not read, revokes nothing. A revocation `checked` holds is not verified again: one
|
|
489
|
+
* repeated in a file, or in the files beside the URL and its sources, is checked once.
|
|
489
490
|
*/
|
|
490
|
-
async function revocationsIn(file, isUrl) {
|
|
491
|
+
async function revocationsIn(file, isUrl, checked) {
|
|
491
492
|
let bytes;
|
|
492
493
|
try {
|
|
493
494
|
if (isUrl) bytes = await fetchBundle(file);
|
|
@@ -496,7 +497,7 @@ async function revocationsIn(file, isUrl) {
|
|
|
496
497
|
} catch {
|
|
497
498
|
return [];
|
|
498
499
|
}
|
|
499
|
-
const read = readAppRevocations(bytes);
|
|
500
|
+
const read = readAppRevocations(bytes, checked);
|
|
500
501
|
return read.ok ? read.revocations : [];
|
|
501
502
|
}
|
|
502
503
|
/** The `ghostly-revoke.json` beside a bundle URL, its query and fragment left out; none for what is not a URL. */
|
|
@@ -528,7 +529,8 @@ async function checkedBundle(source) {
|
|
|
528
529
|
digest: read.bundle.digest
|
|
529
530
|
};
|
|
530
531
|
const files = isUrl ? new Set([source, ...(m.sources ?? []).filter(isAppFetchUrl)].flatMap(besideUrl)) : [join(dirname(userPath(source)), APP_REVOKE_FILE)];
|
|
531
|
-
const
|
|
532
|
+
const checked = /* @__PURE__ */ new Set();
|
|
533
|
+
const lists = await Promise.all([...files].map((file) => revocationsIn(file, isUrl, checked)));
|
|
532
534
|
for (const [i, file] of [...files].entries()) {
|
|
533
535
|
const revocation = appRevocationFor(version, lists[i]);
|
|
534
536
|
if (revocation) throw refused(`${source} is a version its publisher revoked in ${file}: a client stops it`, {
|
|
@@ -583,8 +585,8 @@ async function initApp(dirArg, what = {}) {
|
|
|
583
585
|
}]
|
|
584
586
|
}, { strict: true });
|
|
585
587
|
if (!checked.ok) {
|
|
586
|
-
if (checked.detail === "name is not valid") throw new CliError("usage", what.name === void 0 ? `The folder's name gives no app name (${JSON.stringify(basename(dir))}): give --name, a lowercase letter then up to 31 lowercase letters, digits or hyphens: ${usage}` : `--name is a lowercase letter then up to 31 lowercase letters, digits or hyphens, not ${
|
|
587
|
-
if (checked.detail === "title is not valid") throw new CliError("usage", `--title is one line of 1 to ${APP_BUNDLE_LIMITS.title} characters, not ${
|
|
588
|
+
if (checked.detail === "name is not valid") throw new CliError("usage", what.name === void 0 ? `The folder's name gives no app name (${JSON.stringify(basename(dir))}): give --name, a lowercase letter then up to 31 lowercase letters, digits or hyphens: ${usage}` : `--name is a lowercase letter then up to 31 lowercase letters, digits or hyphens, not ${shownValue(what.name)}`);
|
|
589
|
+
if (checked.detail === "title is not valid") throw new CliError("usage", `--title is one line of 1 to ${APP_BUNDLE_LIMITS.title} characters, not ${shownValue(title)}`);
|
|
588
590
|
throw refused("The template makes no valid manifest", checked);
|
|
589
591
|
}
|
|
590
592
|
if (existsSync(dir) && !statSync(dir).isDirectory()) throw new CliError("bad_request", `${dir} is a file: name a folder for the app`);
|
|
@@ -752,7 +754,7 @@ async function publishApp(dirArg, keyArg, outArg, sequenceArg) {
|
|
|
752
754
|
else if (previous) throw new CliError("not_found", `No key file ${keyPath}: ${out} is signed by ${appFingerprint(previous.publisher)}, and only that key publishes its next version`);
|
|
753
755
|
else key = makeKey("publisher");
|
|
754
756
|
if (previous && previous.publisher !== key.key) throw refused(`${out} is ${appRef(previous.publisher, previous.name)}, signed by another key (${appFingerprint(previous.publisher)}): a version of an app is signed by its own key`, { reason: "other-app" }, { publisher: previous.publisher });
|
|
755
|
-
if (previous && previous.name !== draft.name) throw refused(`${out} is the app ${
|
|
757
|
+
if (previous && previous.name !== draft.name) throw refused(`${out} is the app ${shownValue(previous.name)}, not ${shownValue(draft.name)}: name another --out for another app`, { reason: "other-app" });
|
|
756
758
|
if (sequenceArg !== void 0 && previous && sequenceArg <= previous.sequence) throw refused(`--sequence ${sequenceArg} is not higher than the ${previous.sequence} of ${out}: every client refuses a lower one, and the same one with other content is equivocation`, { reason: sequenceArg < previous.sequence ? "rollback" : "equivocation" }, { previous: previous.sequence });
|
|
757
759
|
const sequence = sequenceArg ?? Math.max(previous ? previous.sequence + 1 : 1, draft.sequence ?? 1);
|
|
758
760
|
const lists = [.../* @__PURE__ */ new Set([join(dir, APP_REVOKE_FILE), join(dirname(out), APP_REVOKE_FILE)])];
|
|
@@ -1015,4 +1017,4 @@ async function signStore(indexArg, keyArg, outArg, now = Math.floor(Date.now() /
|
|
|
1015
1017
|
}
|
|
1016
1018
|
export { STORE_SIG_FILE as a, publishApp as c, verifyApp as d, writeWhole as f, STORE_INDEX_FILE as i, revokeApp as l, APP_REVOKE_FILE as n, checkedBundle as o, nativePublicKey as p, APP_SOURCE as r, initApp as s, APP_BUNDLE_FILE as t, signStore as u };
|
|
1017
1019
|
|
|
1018
|
-
//# sourceMappingURL=apps-
|
|
1020
|
+
//# sourceMappingURL=apps-gXpGFPiv.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"apps-gXpGFPiv.js","names":[],"sources":["../../src/appTemplate.ts","../../src/nativeEd25519.ts","../../src/apps.ts"],"sourcesContent":["/*\n * What `ghostly app init` writes (WISP 1200, Apps · Publishing): the smallest app that does something with a contact.\n * Three files, each whole in this module, so the CLI's one built file carries them: the manifest as a publisher writes\n * it, a page that says hello to the same app on the contact's side, and a README with the way from here to a store.\n */\n\nexport interface AppTemplate { name: string; title: string }\n\nconst html = (text: string) => text.replace(/[&<>\"]/g, (c) => ({ \"&\": \"&\", \"<\": \"<\", \">\": \">\", '\"': \""\" })[c]!);\n\n/** `ghostly-app.json`: the manifest without `publisher`, `sequence` and `files`, which `app publish` writes. */\nexport function templateManifest({ name, title }: AppTemplate): Record<string, unknown> {\n return {\n name,\n version: \"0.1.0\",\n kind: \"mini-app\",\n title,\n tagline: \"Say hello to a contact\",\n description: \"Open it in a chat and your contact gets a card to join. Each side can then say hello to the other.\",\n entry: \"index.html\",\n permissions: [\"chat\"],\n view: \"chat\",\n runtime: { host: \">=1.2\", clients: [\"web\", \"desktop\"] },\n license: \"MIT\",\n };\n}\n\n/**\n * `index.html`: the whole app in one file, as the sandbox needs it (no network, so nothing is loaded from elsewhere).\n * Its script is plain JavaScript typed with JSDoc against `@ghostlytools/sdk/app`, so it runs as written and still type\n * checks (test/appInit.test.ts does). The title is the only thing put into it, as text. Its type imports are in single\n * quotes: they are text of the page, not imports of the CLI's own build (test/packageDeps.test.ts reads those).\n */\nexport function templatePage({ title }: AppTemplate): string {\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${html(title)}</title>\n<style>\n :root { color-scheme: light dark; --bg: #ffffff; --fg: #16181d; --muted: #5b6270; --line: #d9dde3; --accent: #2f6fed; }\n :root[data-theme=\"dark\"] { --bg: #16181d; --fg: #f2f4f7; --muted: #a3abb8; --line: #343a45; --accent: #7aa5ff; }\n body { margin: 0; padding: 20px; background: var(--bg); color: var(--fg); font: 16px/1.4 system-ui, sans-serif; }\n h1 { margin: 0 0 4px; font-size: 20px; }\n #status { margin: 0 0 16px; color: var(--muted); }\n button { font: inherit; padding: 8px 16px; border: 1px solid var(--accent); border-radius: 8px; background: var(--accent); color: var(--bg); }\n button:disabled { opacity: 0.5; }\n ul { margin: 16px 0 0; padding: 0; list-style: none; }\n li { padding: 8px 0; border-top: 1px solid var(--line); }\n</style>\n</head>\n<body>\n<h1>${html(title)}</h1>\n<p id=\"status\" role=\"status\">Starting</p>\n<button id=\"hello\" type=\"button\" disabled>Say hello</button>\n<ul id=\"log\" aria-label=\"Messages\"></ul>\n<script type=\"module\">\n// The types of the API come from the SDK (npm install --save-dev --prefix .. @ghostlytools/sdk); nothing of it runs here.\n/** @typedef {import('@ghostlytools/sdk/app').MiniAppApi} MiniAppApi */\n/** @typedef {import('@ghostlytools/sdk/app').MiniAppJson} MiniAppJson */\n\n/** The longest text shown from a contact's frame. */\nconst MAX_TEXT = 200;\n\nconst status = /** @type {HTMLElement} */ (document.getElementById(\"status\"));\nconst button = /** @type {HTMLButtonElement} */ (document.getElementById(\"hello\"));\nconst log = /** @type {HTMLElement} */ (document.getElementById(\"log\"));\n\n/** @param {string} text */\nfunction show(text) {\n const line = document.createElement(\"li\");\n line.textContent = text;\n log.append(line);\n}\n\n/**\n * What the contact's app sent, when it is a hello. A frame comes from another device: read only what this app sends,\n * and never put it in the page as HTML.\n * @param {MiniAppJson} data\n * @returns {string | null}\n */\nfunction helloOf(data) {\n if (!data || typeof data !== \"object\" || Array.isArray(data) || data.type !== \"hello\") return null;\n return typeof data.text === \"string\" && data.text.length <= MAX_TEXT ? data.text : null;\n}\n\n/**\n * Why a send was refused, in words. The code is the rejection's message (MINI_APP_ERROR_CODES in the SDK); a later\n * client may add one.\n * @param {unknown} error\n */\nfunction refusal(error) {\n switch (error instanceof Error ? error.message : \"\") {\n case \"offline\": return \"Not sent: you are not both online\";\n case \"peer-closed\": case \"not-open\": return \"Not sent: your contact has not opened this app\";\n case \"not-allowed\": return \"Open this app in a chat to say hello\";\n default: return \"Not sent\";\n }\n}\n\n/** @param {MiniAppApi} ghostly */\nasync function start(ghostly) {\n // Listen before anything is awaited, so no frame is missed.\n ghostly.chat.on(\"message\", (data) => {\n const text = helloOf(data);\n if (text !== null) show(\"Your contact: \" + text);\n });\n ghostly.chat.on(\"peer\", (peer) => {\n status.textContent = peer.open ? \"Your contact has this app open\" : \"Waiting for your contact to open this app\";\n });\n\n const context = await ghostly.context();\n const dark = context.theme ? context.theme === \"dark\" : matchMedia(\"(prefers-color-scheme: dark)\").matches;\n document.documentElement.dataset.theme = dark ? \"dark\" : \"light\";\n status.textContent = !context.inChat ? \"Open this app in a chat to say hello\"\n : context.peer ? \"Your contact has this app open\" : \"Waiting for your contact to open this app\";\n\n button.disabled = false;\n button.addEventListener(\"click\", async () => {\n try {\n await ghostly.chat.send({ type: \"hello\", text: \"Hello!\" });\n show(\"You: Hello!\");\n } catch (error) {\n show(refusal(error));\n }\n });\n}\n\n/** Ghostly's runner gives the app \\`window.ghostly\\`; a browser tab has none. */\nconst ghostly = /** @type {{ ghostly?: MiniAppApi }} */ (window).ghostly;\nif (ghostly) void start(ghostly);\nelse status.textContent = \"This page is a Ghostly app: publish it and open it in Ghostly\";\n</script>\n</body>\n</html>\n`;\n}\n\n/** `README.md`: what the folder holds and the way from it to a store. */\nexport function templateReadme({ name, title }: AppTemplate): string {\n return `# ${title}\n\nA [Ghostly](https://github.com/MiguelMedeiros/ghostly) app, started with \\`ghostly app init\\`. Opened in a 1:1 chat, it\ngives your contact a card to join, and each side can say hello to the other.\n\nA Ghostly app ([WISP 1200](https://github.com/MiguelMedeiros/ghostly/blob/dev/docs/wisps/1200-marketplace.md)) is a\npage that runs in the client's sandbox. It has no network, and talks to Ghostly only through \\`window.ghostly\\`:\nframes of at most 32 KiB to the same app on the contact's side (\\`chat.send\\`, \\`chat.on\\`), storage per app and per\nchat, and the files of its own bundle. Apps run in Ghostly from release 1.2.\n\n| File | What it is |\n|---|---|\n| \\`ghostly-app.json\\` | The manifest, without \\`publisher\\`, \\`sequence\\` and \\`files\\`: \\`ghostly app publish\\` writes those |\n| \\`index.html\\` | The app, whole: styles and script inline |\n| \\`README.md\\` | This file |\n\n## Write it\n\n\\`index.html\\` is plain JavaScript, typed with JSDoc against \\`@ghostlytools/sdk/app\\`: \\`MiniAppApi\\` is\n\\`window.ghostly\\`, and the same module has the limits (\\`MINI_APP_LIMITS\\`) and the codes a refused call rejects with\n(\\`MINI_APP_ERROR_CODES\\`). For the types in your editor, install it in the folder above this one, where your editor\nstill finds it: \\`ghostly app publish\\` takes every file of this folder, so \\`node_modules\\` and \\`package.json\\` stay\nout of it.\n\n\\`\\`\\`sh\nnpm install --save-dev --prefix .. @ghostlytools/sdk\n\\`\\`\\`\n\n- What a contact's app sends is untrusted: check its shape, bound its size, and show it as text, never as HTML.\n- \\`\"view\": \"chat\"\\` runs the app inside a chat with one contact. \\`\"full\"\\` is a full-screen app opened from the Apps page.\n- \\`permissions\\` lists what the person is asked for: \\`chat\\` (frames to the contact's app), \\`name\\` (the person's\n display name) and \\`internet\\`. Adding one later makes every install ask before it updates.\n\n## Build\n\nThere is nothing to build yet: the page is the app. Once it grows into several source files, or TypeScript, build it\ninto one self-contained \\`index.html\\` (scripts, styles and images inline) and put that file and \\`ghostly-app.json\\`\nalone in a folder of their own, which is the folder you publish.\n[ghostly-chess](https://github.com/MiguelMedeiros/ghostly-chess) does it with Vite and a small\n\\`scripts/stage.mjs\\`. \\`ghostly app publish\\` takes every file of the folder it is given but dot files, this README\nincluded, so do not run it on a repository with sources, \\`node_modules\\` or anything private in it.\n\n## Publish\n\n\\`\\`\\`sh\nghostly app publish . --key ~/ghostly-keys/${name}-publisher.key\nghostly app verify app.ghostlyapp\n\\`\\`\\`\n\n\\`publish\\` signs the folder into \\`app.ghostlyapp\\`. The first run makes the publisher key at the path you name:\n\n- Keep it **outside this folder** and its repository (\\`publish\\` refuses a key inside it), and never commit it.\n- Back it up. An app is updated only with the key that signed it; a lost key means a new app.\n\n\\`verify\\` checks the bundle as Ghostly will and prints its \\`ref\\` (\\`<publisher key>/${name}\\`), \\`sequence\\` and\n\\`digest\\`. For the next version, raise \\`version\\` in \\`ghostly-app.json\\` and publish again: the sequence goes up\nby one by itself.\n\n## Try it\n\nCommit \\`app.ghostlyapp\\` to a public GitHub repository, then in Ghostly open Apps, choose Add, and paste its URL\n(\\`https://raw.githubusercontent.com/<owner>/<repo>/HEAD/app.ghostlyapp\\`). Set \\`sources\\` in \\`ghostly-app.json\\`\nto that URL, in a list, so installs made from it find your updates. Open the app from a chat's + menu; your contact\ngets a card to install and open it.\n\n## List it in a store\n\nA store is a signed list of apps. The official one is a Git repository,\n[ghostly-store](https://github.com/MiguelMedeiros/ghostly-store), and apps enter it by pull request:\n\n1. Commit \\`app.ghostlyapp\\` to your public repository and note that commit.\n2. Add \\`apps/${name}.<first 16 characters of your publisher key>/listing.json\\` with the \\`ref\\`, \\`sequence\\`\n and \\`digest\\` that \\`ghostly app verify\\` printed. Its \\`urls\\` start with a jsDelivr URL pinned to the full commit\n (\\`https://cdn.jsdelivr.net/gh/<owner>/<repo>@<40-character commit>/app.ghostlyapp\\`).\n3. Open the pull request. Its check verifies the bundle; a maintainer reviews the app and the owner signs the index.\n\nThe store's [CONTRIBUTING](https://github.com/MiguelMedeiros/ghostly-store/blob/main/CONTRIBUTING.md) has the rules.\nAn app installed from a store updates only to the version that store lists, so each new version is a pull request too.\n\n## If something goes wrong\n\nIf a version is harmful, \\`ghostly app revoke . --key <your key> --up-to <sequence>\\` writes \\`ghostly-revoke.json\\`;\npublish it beside \\`app.ghostlyapp\\` and Ghostly stops those versions.\n`;\n}\n","import { createPrivateKey, createPublicKey, verify, type KeyObject } from \"node:crypto\";\nimport type { AppSignatureFastPath, PublicKeyFastPath } from \"@ghostly/core\";\n\n/*\n * Node's Ed25519 (OpenSSL's): a signature in tens of microseconds, where the core's portable check takes most of a\n * millisecond, so a list of 4096 revocations is checked in a fraction of a second. OpenSSL verifies as RFC 8032 writes it\n * without the cofactor and compares R byte for byte, which is what the core's fast path asks (see AppSignatureFastPath).\n */\n\n/** SubjectPublicKeyInfo of an Ed25519 key (RFC 8410), before its 32 bytes. */\nconst SPKI_PREFIX = Buffer.from(\"302a300506032b6570032100\", \"hex\");\n/** PKCS #8 of an Ed25519 private key (RFC 8410), before its 32-byte seed. */\nconst PKCS8_PREFIX = Buffer.from(\"302e020100300506032b657004220420\", \"hex\");\n/** The key objects of the keys seen lately: a list repeats its publishers. */\nconst keys = new Map<string, KeyObject>();\n\nexport const nativeEd25519: AppSignatureFastPath = (signature, message, publicKey) => {\n const id = Buffer.from(publicKey).toString(\"hex\");\n let key = keys.get(id);\n if (!key) {\n key = createPublicKey({ key: Buffer.concat([SPKI_PREFIX, publicKey]), format: \"der\", type: \"spki\" });\n if (keys.size >= 256) keys.clear();\n keys.set(id, key);\n }\n return verify(null, message, key, signature);\n};\n\n/**\n * A seed's public key by Node's Ed25519: ~0.08 ms, where noble's takes ~0.3 ms in a fresh process. A one-shot command\n * derives two for each chat of the profile at its start (its own seed and its participation seed): 400 at 200 chats.\n */\nexport const nativePublicKey: PublicKeyFastPath = (seed) =>\n createPublicKey(createPrivateKey({ key: Buffer.concat([PKCS8_PREFIX, seed]), format: \"der\", type: \"pkcs8\" })).export({ format: \"der\", type: \"spki\" }).subarray(SPKI_PREFIX.length);\n","import { createHash, createPrivateKey, generateKeyPairSync } from \"node:crypto\";\nimport { closeSync, existsSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, join, relative, sep } from \"node:path\";\nimport {\n APP_BUNDLE_LIMITS, APP_PREFIXES, appFingerprint, appRef, appRevocationFor, appStoreDecision, assembleAppBundle, canonicalJson, canonicalJsonBytes,\n APP_STATEMENT_LIMITS, checkAppManifest, checkAppRevokeStatement, checkAppStoreIndex, fromBase64Url, isAppHash, isAppLine, isAppUrl, readAppBundle,\n readAppRevocations, readAppStore, repeatedJsonKey, seedSigner, setAppSignatureFastPath, signAppObject, signAppRevocation, signAppStore, toBase64Url, toZ32, type AppBundle,\n type AppManifest, type AppRevokeStatement, type AppStoreIndex, type AppStoreReading, type SignedAppRevocation, type Signer,\n} from \"@ghostly/core\";\nimport { APP_FETCH_HOSTS, isAppFetchUrl } from \"@ghostly/browser/engine/appFetch\";\nimport { templateManifest, templatePage, templateReadme } from \"./appTemplate\";\nimport { CliError, localFileError, shownValue } from \"./errors\";\nimport { jsonOut } from \"./jsonOut\";\nimport { guardText } from \"./secretGuard\";\nimport { nativeEd25519 } from \"./nativeEd25519\";\nimport { userPath } from \"./profiles\";\n\n/*\n * The publisher tools of WISP 1200 (Apps · Publishing): `app init` writes a folder to start from, `app publish` bundles\n * and signs a folder, `app verify` checks a bundle as a client would, `store sign` signs a store index. They run here, on files: no profile, no daemon, no\n * network but the one read `app verify` makes of a URL.\n *\n * Keys. A publisher key and a store key are Ed25519 keys of their own, never a profile's (WISP 1200 · Publisher\n * identity). Each lives in a file the command names with `--key`: a PKCS #8 PEM block (what `openssl genpkey -algorithm\n * ed25519` writes, so secret scanners know it for a private key), after one line that says which kind it is. The file\n * is made owner-only (0600) when a command makes it, and refused when anyone else may read it. A key is never printed:\n * only its public key and fingerprint are.\n */\n\nexport const APP_SOURCE = \"ghostly-app.json\";\nexport const APP_BUNDLE_FILE = \"app.ghostlyapp\";\nexport const APP_REVOKE_FILE = \"ghostly-revoke.json\";\nexport const STORE_INDEX_FILE = \"ghostly-store.json\";\nexport const STORE_SIG_FILE = \"ghostly-store.sig\";\n\n// Every signature the publisher tools check (bundles, revocation lists, store indexes) goes through Node's Ed25519 first.\nsetAppSignatureFastPath(nativeEd25519);\n\n/** How long `app verify` waits for a URL, its redirects included, and how many redirects it follows (each checked as the first). */\nconst FETCH_TIMEOUT_MS = 60_000;\nconst MAX_REDIRECTS = 5;\n\n// ---------- keys ----------\n\nexport type KeyKind = \"publisher\" | \"store\";\n\nconst KEY_HEADER: Record<KeyKind, string> = {\n publisher: \"Ghostly publisher key (WISP 1200). Secret: never share or commit it. Back it up: an app signed with it is updated only with it.\",\n store: \"Ghostly store key (WISP 1200). Secret: keep it offline, never share or commit it. Back it up: a store is its key.\",\n};\nconst PEM = /-----BEGIN PRIVATE KEY-----\\r?\\n([A-Za-z0-9+/=\\r\\n]+)-----END PRIVATE KEY-----/;\n\n/** `pem`: a key made by this run, written to its file by `saveKey` only once every check passed. */\nexport interface LoadedKey { signer: Signer; key: string; created: boolean; pem?: string }\n\n/** Refuses a key file that is not a plain file of this user's, or that anyone else may read or write. */\nfunction checkKeyFile(path: string): void {\n const info = statSync(path);\n if (!info.isFile()) throw new CliError(\"bad_request\", `${path} is not a file: --key names a key file`);\n if (process.platform === \"win32\") return;\n if (process.getuid && info.uid !== process.getuid()) throw new CliError(\"refused\", `${path} is not this user's: a key file must be yours alone`);\n if ((info.mode & 0o077) !== 0) {\n throw new CliError(\"refused\", `${path} may be read by others (mode ${(info.mode & 0o777).toString(8)}): run chmod 600 ${path}, and think whether the key was seen`);\n }\n}\n\n/** Reads a key file: the PEM block, an Ed25519 key, and the kind its first line names (when it names one). */\nfunction readKey(path: string, kind: KeyKind): LoadedKey {\n checkKeyFile(path);\n const text = readFileSync(path, \"utf8\");\n const other: KeyKind = kind === \"publisher\" ? \"store\" : \"publisher\";\n if (text.startsWith(`Ghostly ${other} key`)) {\n throw new CliError(\"refused\", `${path} is a ${other} key: ${kind === \"publisher\" ? \"a store key never signs an app or its revocations\" : \"a publisher key never signs a store index\"} (WISP 1200 · Stores)`);\n }\n const block = PEM.exec(text);\n let seed: Uint8Array | undefined;\n if (block) {\n try {\n const key = createPrivateKey(block[0]);\n const d = key.asymmetricKeyType === \"ed25519\" ? key.export({ format: \"jwk\" }).d : undefined;\n if (d) seed = fromBase64Url(d);\n } catch { /* said below, without the file's text */ }\n }\n if (!seed || seed.length !== 32) throw new CliError(\"bad_request\", `${path} holds no Ed25519 private key (a PEM \"PRIVATE KEY\" block, as openssl genpkey -algorithm ed25519 writes)`);\n const signer = seedSigner(seed);\n return { signer, key: toZ32(signer.publicKey), created: false };\n}\n\n/**\n * Makes a key in memory: its file is written by `saveKey`, right before the bundle or index it signs. A run refused\n * after this step leaves no key file, which the next run would read as an existing key and never say to back up.\n */\nfunction makeKey(kind: KeyKind): LoadedKey {\n const { privateKey } = generateKeyPairSync(\"ed25519\");\n const signer = seedSigner(fromBase64Url(privateKey.export({ format: \"jwk\" }).d!));\n return { signer, key: toZ32(signer.publicKey), created: true, pem: `${KEY_HEADER[kind]}\\n${privateKey.export({ type: \"pkcs8\", format: \"pem\" }) as string}` };\n}\n\n/** Writes a key this run made: owner-only from the start, never over a file that is there. */\nfunction saveKey(path: string, key: LoadedKey): void {\n if (!key.pem) return;\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 });\n const fd = openSync(path, \"wx\", 0o600);\n try { writeSync(fd, key.pem); } finally { closeSync(fd); }\n}\n\n/**\n * Saves the key, then writes what it signs: the key first, so nothing it signed is ever on disk without it. A write\n * that fails (a folder it may not write) takes back the key this run made, which nothing signed by it needs: kept,\n * the next run read it as an existing key and never said to back it up.\n */\nfunction saveKeyThen(path: string, key: LoadedKey, write: () => void): void {\n saveKey(path, key);\n try { write(); } catch (error) {\n if (key.pem) rmSync(path, { force: true });\n throw error;\n }\n}\n\n/** What the person is told on stderr when a key was made: where, which, and to back it up. Never the key. */\nfunction madeKeyNote(path: string, kind: KeyKind, key: string): string {\n return kind === \"publisher\"\n ? `new publisher key written to ${path}; back it up (${appFingerprint(key)}: an app is updated only with the key that signed it, and phase 1 has no recovery)`\n : `new store key written to ${path}; back it up and keep it offline (${appFingerprint(key)}: a store is its key)`;\n}\n\n// ---------- reading bundles ----------\n\nconst refused = (what: string, reading: { reason: string; detail?: string }, extra: Record<string, unknown> = {}) =>\n new CliError(\"refused\", `${what} (${reading.reason}${reading.detail ? `: ${reading.detail}` : \"\"})`, { reason: reading.reason, ...(reading.detail ? { detail: reading.detail } : {}), ...extra });\n\n/**\n * Refuses JSON that writes a key twice in one object, as `readAppListing` does: JSON.parse keeps the last value, where a\n * person reading the file sees the first, so what is signed is not what was read. `text` is JSON that JSON.parse took.\n */\nfunction refuseRepeatedKey(path: string, text: string): void {\n const twice = repeatedJsonKey(text);\n if (twice !== null) throw refused(`${path} writes a key twice`, { reason: \"not-json\", detail: `${JSON.stringify(twice)} is written twice` });\n}\n\n/** A bundle file's bytes: its size is checked before it is read, so a huge file is refused unread. */\nfunction readBundleFile(path: string): Uint8Array {\n const info = statSync(path);\n if (info.isDirectory()) throw new CliError(\"bad_request\", `${path} is a folder: name a .ghostlyapp file`);\n if (info.size > APP_BUNDLE_LIMITS.bundleBytes) throw refused(`${path} is not a valid bundle`, { reason: \"too-large\", detail: `${info.size} bytes` });\n return new Uint8Array(readFileSync(path));\n}\n\n/**\n * A bundle at an https URL, as a client fetches one: `https:` only, no user or password, jsDelivr only at a full\n * commit (WISP 1200 · Manifest, \"Every URL\"); every redirect is held to the same rule, and the download stops past\n * 16 MiB. A redirect stays on the URL's own host and port or goes to a host a client reads from (isAppFetchUrl): never\n * a host or port of the server's choosing on this machine's network.\n */\nasync function fetchBundle(url: string): Promise<Uint8Array> {\n // One wait for the URL, its redirects and its body together: a host that redirects just before a wait runs out\n // never earns another.\n const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS);\n let at = url;\n for (let hop = 0; ; hop++) {\n if (!isAppUrl(at)) {\n throw new CliError(hop ? \"refused\" : \"usage\", hop\n ? `${url} redirects to ${at}, which a client does not read (https only, no user or password, jsDelivr only at a full commit)`\n : `Not a URL a client reads: https only, at most ${APP_BUNDLE_LIMITS.url} characters, no user or password, and jsDelivr only as https://cdn.jsdelivr.net/gh/<owner>/<repo>@<40-hex commit>/<path>`);\n }\n if (hop && new URL(at).host !== new URL(url).host && !isAppFetchUrl(at)) {\n throw new CliError(\"refused\", `${url} redirects to ${at}, on another host: a redirect stays on ${new URL(url).host} or goes to ${APP_FETCH_HOSTS.join(\" or \")}`);\n }\n let response: Response;\n try {\n response = await fetch(at, { redirect: \"manual\", signal });\n } catch (error) {\n if (error instanceof Error && error.name === \"TimeoutError\") throw new CliError(\"timeout\", `${at} did not answer in ${FETCH_TIMEOUT_MS / 1000} s`);\n throw new CliError(\"unavailable\", `Could not read ${at}: ${error instanceof Error ? error.message : String(error)}`);\n }\n if (response.status >= 300 && response.status < 400 && response.headers.get(\"location\")) {\n await response.body?.cancel();\n if (hop >= MAX_REDIRECTS) throw new CliError(\"refused\", `${url} redirects more than ${MAX_REDIRECTS} times`);\n at = new URL(response.headers.get(\"location\")!, at).href;\n continue;\n }\n if (response.status === 404 || response.status === 410) { await response.body?.cancel(); throw new CliError(\"not_found\", `${at} answered ${response.status}`); }\n if (!response.ok || !response.body) { await response.body?.cancel(); throw new CliError(\"unavailable\", `${at} answered ${response.status}`); }\n const limit = APP_BUNDLE_LIMITS.bundleBytes;\n const tooLarge = (bytes: number | string) => refused(`${url} is not a valid bundle`, { reason: \"too-large\", detail: `${bytes} bytes` });\n const length = Number(response.headers.get(\"content-length\"));\n if (Number.isFinite(length) && length > limit) { await response.body.cancel(); throw tooLarge(length); }\n const chunks: Uint8Array[] = [];\n let total = 0;\n const reader = response.body.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.length;\n if (total > limit) { await reader.cancel(); throw tooLarge(`more than ${limit}`); }\n chunks.push(value);\n }\n } catch (error) {\n if (error instanceof CliError) throw error;\n if (error instanceof Error && error.name === \"TimeoutError\") throw new CliError(\"timeout\", `${at} did not finish in ${FETCH_TIMEOUT_MS / 1000} s`);\n throw new CliError(\"unavailable\", `Could not read ${at}: ${error instanceof Error ? error.message : String(error)}`);\n }\n const out = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) { out.set(chunk, offset); offset += chunk.length; }\n return out;\n }\n}\n\n/** What a checked bundle is, as `app verify` and `app publish` print it. */\nfunction described(bundle: AppBundle, bytes: Uint8Array) {\n const m = bundle.manifest;\n return {\n ref: appRef(m.publisher, m.name), publisher: m.publisher, fingerprint: appFingerprint(m.publisher), name: m.name,\n title: m.title, version: m.version, sequence: m.sequence, digest: bundle.digest, bytes: bytes.length,\n sha256: toBase64Url(createHash(\"sha256\").update(bytes).digest()),\n };\n}\n\n/** `app verify <bundle|url>`: every check a client makes before it stores a bundle (WISP 1200 · Reading a bundle). */\nexport async function verifyApp(source: string): Promise<Record<string, unknown>> {\n const { bundle, bytes } = await checkedBundle(source);\n return { valid: true, ...described(bundle, bytes), manifest: bundle.manifest };\n}\n\n/**\n * The revocations of a `ghostly-revoke.json`, a URL or a file, as a client reads it. None there, one that does not\n * answer, or one a client would not read, revokes nothing. A revocation `checked` holds is not verified again: one\n * repeated in a file, or in the files beside the URL and its sources, is checked once.\n */\nasync function revocationsIn(file: string, isUrl: boolean, checked?: Set<string>): Promise<SignedAppRevocation[]> {\n let bytes: Uint8Array;\n try {\n if (isUrl) bytes = await fetchBundle(file);\n else if (!existsSync(file)) return [];\n else bytes = readBundleFile(file);\n } catch { return []; }\n const read = readAppRevocations(bytes, checked);\n return read.ok ? read.revocations : [];\n}\n\n/** The `ghostly-revoke.json` beside a bundle URL, its query and fragment left out; none for what is not a URL. */\nfunction besideUrl(url: string): string[] {\n try {\n const at = new URL(url);\n at.search = \"\";\n at.hash = \"\";\n return [new URL(APP_REVOKE_FILE, at).href];\n } catch { return []; }\n}\n\n/**\n * A bundle from a file or an https URL, with every check of `app verify`; `url` when it came from one. A version its\n * publisher revoked is refused, as a client stops it, with no \"Run anyway\": in the `ghostly-revoke.json` beside it and,\n * for a URL, beside each of the manifest's `sources` too (WISP 1200 · Revocation: a client reads them there, where a\n * publisher revokes a version a store's pinned URL still holds). A file is checked offline: beside it only.\n */\nexport async function checkedBundle(source: string): Promise<{ bundle: AppBundle; bytes: Uint8Array; url?: string }> {\n const isUrl = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(source);\n const bytes = isUrl ? await fetchBundle(source) : readBundleFile(userPath(source));\n const read = readAppBundle(bytes);\n if (!read.ok) throw refused(`${source} is not a valid bundle`, read);\n const m = read.bundle.manifest;\n const version = { ref: appRef(m.publisher, m.name), sequence: m.sequence, digest: read.bundle.digest };\n // The `sources` are the publisher's words: beside them only on the hosts a client reads from (isAppFetchUrl), never a\n // host or port of the publisher's choosing on this machine's network.\n const files = isUrl\n ? new Set([source, ...(m.sources ?? []).filter(isAppFetchUrl)].flatMap(besideUrl))\n : [join(dirname(userPath(source)), APP_REVOKE_FILE)];\n // Read together: one host that does not answer holds the check for one wait, not one per file after it. Each\n // revocation's signature is checked once across them all (at most 9 files of 4096).\n const checked = new Set<string>();\n const lists = await Promise.all([...files].map((file) => revocationsIn(file, isUrl, checked)));\n for (const [i, file] of [...files].entries()) {\n const revocation = appRevocationFor(version, lists[i]!);\n if (revocation) {\n throw refused(`${source} is a version its publisher revoked in ${file}: a client stops it`, { reason: \"revoked\", ...(revocation.statement.reason !== undefined && { detail: revocation.statement.reason }) }, { file });\n }\n }\n return { bundle: read.bundle, bytes, ...(isUrl && { url: source }) };\n}\n\n// ---------- starting an app ----------\n\n/** A folder's name as an app's: lower case, anything else a hyphen (`My App` is `my-app`). */\nconst nameFrom = (folder: string) => folder.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\");\n/** An app's name as a title: `my-app` is `My app`. */\nconst titleFrom = (name: string) => (name[0]!.toUpperCase() + name.slice(1)).replace(/-/g, \" \");\n/**\n * A path as one word of a POSIX shell line: as typed when it is plain, else single-quoted (`My App` is `'My App'`).\n * None for a path the JSON answer would print other than it is (a `\"`, a backslash, a control) or holding a `'`, whose\n * quoting takes a backslash: a line copied from the answer would be another command.\n */\nconst shellWord = (word: string) => /^[\\w@%+=:,./~-]+$/.test(word) ? word : word.includes(\"'\") || jsonOut(word) !== `\"${word}\"` ? null : `'${word}'`;\n\n/**\n * `app init <dir> [--name <name>] [--title <title>] [--force]`: a small working app in `<dir>` (made when missing),\n * which `app publish <dir>` signs as it is: `ghostly-app.json`, an `index.html` that says hello to the contact, and a\n * README with the way to a store (./appTemplate.ts). The name is `--name`, else the folder's; the title `--title`, else\n * the name's. Nothing is written when one of the three files is there, unless `--force`, which replaces those three only.\n */\nexport async function initApp(dirArg: string, what: { name?: string; title?: string; force?: boolean } = {}): Promise<Record<string, unknown>> {\n const usage = \"ghostly app init <dir> [--name <name>] [--title <title>] [--force]\";\n const dir = userPath(dirArg);\n const name = what.name ?? nameFrom(basename(dir));\n const title = what.title ?? (name ? titleFrom(name) : \"\");\n const page = templatePage({ name, title });\n // Checked as publish will check it, under a key of zeros and the page's own entry: what is written always publishes.\n const pageBytes = new TextEncoder().encode(page);\n const checked = checkAppManifest({\n ...templateManifest({ name, title }), ghostlyApp: 1, publisher: toZ32(new Uint8Array(32)), sequence: 1,\n files: [{ path: \"index.html\", size: pageBytes.length, sha256: toBase64Url(createHash(\"sha256\").update(pageBytes).digest()) }],\n }, { strict: true });\n if (!checked.ok) {\n if (checked.detail === \"name is not valid\") {\n throw new CliError(\"usage\", what.name === undefined\n ? `The folder's name gives no app name (${JSON.stringify(basename(dir))}): give --name, a lowercase letter then up to 31 lowercase letters, digits or hyphens: ${usage}`\n : `--name is a lowercase letter then up to 31 lowercase letters, digits or hyphens, not ${shownValue(what.name)}`);\n }\n if (checked.detail === \"title is not valid\") throw new CliError(\"usage\", `--title is one line of 1 to ${APP_BUNDLE_LIMITS.title} characters, not ${shownValue(title)}`);\n throw refused(\"The template makes no valid manifest\", checked);\n }\n\n if (existsSync(dir) && !statSync(dir).isDirectory()) throw new CliError(\"bad_request\", `${dir} is a file: name a folder for the app`);\n const files: [string, string][] = [\n [APP_SOURCE, `${JSON.stringify(templateManifest({ name, title }), null, 2)}\\n`],\n [\"index.html\", page],\n [\"README.md\", templateReadme({ name, title })],\n ];\n const held = files.map(([path]) => path).filter((path) => existsSync(join(dir, path)));\n if (held.length && !what.force) {\n throw refused(`${dir} already holds ${held.join(\", \")}: nothing was written (--force replaces ${held.length > 1 ? \"them\" : \"it\"})`, { reason: \"exists\" }, { files: held });\n }\n mkdirSync(dir, { recursive: true });\n for (const [path, text] of files) writeWhole(join(dir, path), new TextEncoder().encode(text));\n // A line to paste: a folder with a space or a `$` stays one word, the folder given; one the answer cannot print as it\n // is (a quote, a backslash) is left to the person, named in `dir`.\n const typed = shellWord(dirArg);\n return {\n dir, name, title, files: files.map(([path]) => path), ...(held.length ? { replaced: held } : {}),\n next: typed === null ? \"ghostly app publish <the folder> --key <a key file outside it>\" : `ghostly app publish ${typed} --key <a key file outside ${typed}>`,\n };\n}\n\n// ---------- publishing ----------\n\n/** Every file of the folder, as the bundle names it; dot files and folders are left out and listed. */\nfunction collectFiles(dir: string, leaveOut: Set<string>): { files: { path: string; full: string; size: number }[]; skipped: string[] } {\n const files: { path: string; full: string; size: number }[] = [];\n const skipped: string[] = [];\n let bytes = 0;\n const walk = (folder: string) => {\n // Read as bytes: a name that is not UTF-8 comes back from a string read with U+FFFD in it, a path no file has.\n const names = readdirSync(folder, { encoding: \"buffer\" }).map((raw) => ({ raw, name: raw.toString(\"utf8\") }));\n for (const { raw, name } of names.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {\n const full = join(folder, name);\n const path = relative(dir, full).split(sep).join(\"/\");\n if (leaveOut.has(full)) continue;\n if (name.startsWith(\".\")) { skipped.push(path); continue; }\n if (!Buffer.from(name, \"utf8\").equals(raw)) throw refused(`${dir} holds a name that is not UTF-8, which no bundle path may be: rename it`, { reason: \"bad-path\", detail: path });\n const info = lstatSync(full);\n if (info.isSymbolicLink()) throw new CliError(\"bad_request\", `${path} is a link: a bundle holds the folder's own files (copy it in, or remove it)`);\n if (info.isDirectory()) { walk(full); continue; }\n if (!info.isFile()) throw new CliError(\"bad_request\", `${path} is not a file`);\n files.push({ path, full, size: info.size });\n bytes += info.size;\n if (files.length > APP_BUNDLE_LIMITS.files) throw refused(`${dir} holds more files than a bundle may`, { reason: \"too-many-files\", detail: `more than ${APP_BUNDLE_LIMITS.files}` });\n if (bytes > APP_BUNDLE_LIMITS.bundleBytes) throw refused(`${dir} holds more than a bundle may`, { reason: \"too-large\", detail: `more than ${APP_BUNDLE_LIMITS.bundleBytes} bytes of files` });\n }\n };\n walk(dir);\n // The manifest lists every path in code-unit order, across folders: `lib-extra.js` before `lib/x.js`, which the walk\n // reaches first (`-` and `.` sort before `/`).\n files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n return { files, skipped };\n}\n\n/**\n * A private key in a file: a PEM private key block with its body (PKCS #8, OpenSSH, RSA, EC, encrypted, the traditional\n * encrypted one's \"Proc-Type: 4,ENCRYPTED\" headers included), an OpenPGP \"PRIVATE KEY BLOCK\" (its \"Version: GnuPG\n * v2.4.5\" headers included), or a Ghostly key file's first line. A library that only names the block's header in its\n * code does not match. The body stops at the next \"-----\": a file of headers with no end is read once, not once per\n * header to the end of the file.\n */\nconst PRIVATE_KEY = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY( BLOCK)?-----\\r?\\n(?:[A-Za-z0-9+/=\\r\\n :,.]|-(?!----)){40,}-----END [A-Z0-9 ]*PRIVATE KEY( BLOCK)?-----|^Ghostly (publisher|store) key \\(WISP 1200\\)/;\n\n/** Whether `path` is `dir` or anything under it (a name like `..k.key` is under it: only a `..` segment leaves). */\nconst isUnder = (dir: string, path: string) => { const rel = relative(dir, path); return rel !== \"..\" && !rel.startsWith(`..${sep}`) && !isAbsolute(rel); };\n/** `path` with its symlinks followed, as far as it exists (the rest, not made yet, kept as written). */\nfunction realPath(path: string): string {\n try { return realpathSync(path); } catch {\n const parent = dirname(path);\n return parent === path ? path : join(realPath(parent), basename(path));\n }\n}\n/** {@link isUnder} as written or through a symlink: another name for the folder (or for the file) is the same place. */\nconst isInside = (dir: string, path: string) => isUnder(dir, path) || isUnder(realPath(dir), realPath(path));\n\n/** Fields of `ghostly-app.json` the command writes itself. */\nconst WRITTEN = [\"publisher\", \"files\"] as const;\n\nfunction readSource(path: string): Record<string, unknown> {\n if (!existsSync(path)) throw new CliError(\"not_found\", `No ${APP_SOURCE} in ${dirname(path)}: it holds the manifest's fields (name, version, title, tagline, entry, permissions, runtime, license, ...) but publisher, sequence and files, which publish writes`);\n let text: string, value: unknown;\n try { text = readFileSync(path, \"utf8\"); value = JSON.parse(text); } catch (error) { throw new CliError(\"bad_request\", `${path} is not JSON: ${error instanceof Error ? error.message : String(error)}`); }\n refuseRepeatedKey(path, text);\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new CliError(\"bad_request\", `${path} is not a JSON object`);\n const draft = value as Record<string, unknown>;\n const written = WRITTEN.filter((k) => k in draft);\n if (written.length) throw new CliError(\"bad_request\", `${path} has ${written.join(\" and \")}: publish writes ${written.length > 1 ? \"them\" : \"it\"} from the key and the folder's files`);\n if (draft.ghostlyApp !== undefined && draft.ghostlyApp !== 1) throw refused(`${path} is not a manifest this release makes`, { reason: \"unsupported-format\", detail: \"ghostlyApp is not 1\" });\n if (draft.sequence !== undefined && !(Number.isSafeInteger(draft.sequence) && (draft.sequence as number) >= 1)) {\n throw new CliError(\"bad_request\", `${path}: sequence is a whole number from 1 (or leave it out: publish raises it by itself)`);\n }\n return draft;\n}\n\n/**\n * Writes a file whole or not at all: a reader never sees half a bundle (and a dot file left by a crash is never bundled).\n * The temporary file is always a new one (\"wx\"): a file or link already at its name is removed, never written through.\n */\nexport function writeWhole(path: string, bytes: Uint8Array): void {\n const tmp = join(dirname(path), `.${basename(path)}.${process.pid}.tmp`);\n rmSync(tmp, { force: true });\n writeFileSync(tmp, bytes, { mode: 0o644, flag: \"wx\" });\n renameSync(tmp, path);\n}\n\n/**\n * `app publish <dir> --key <file> [--out <file>] [--sequence n]`:`<dir>/ghostly-app.json` (the manifest without `publisher`,\n * `sequence` and `files`) and every other file in `<dir>` (but its bundles and revocations) become one signed bundle, by default `<dir>/app.ghostlyapp`.\n * The sequence is `--sequence` (higher than the bundle already at `--out`'s), else one more than that bundle's (or\n * the source's `sequence`, if higher, else 1). The\n * key file is made when it is missing and no earlier bundle is there to update.\n */\nexport async function publishApp(dirArg: string, keyArg: string, outArg?: string, sequenceArg?: number): Promise<Record<string, unknown>> {\n if (sequenceArg !== undefined && !(Number.isSafeInteger(sequenceArg) && sequenceArg >= 1)) throw new CliError(\"usage\", `--sequence takes a whole number from 1, not ${sequenceArg}`);\n const dir = userPath(dirArg);\n if (!statSync(dir).isDirectory()) throw new CliError(\"bad_request\", `${dir} is not a folder`);\n const keyPath = userPath(keyArg);\n // Every file of the folder is published, and the folder is often the repository the bundle is committed to.\n if (isInside(dir, keyPath)) {\n throw refused(`${keyPath} is inside ${dir}, which is published: keep the publisher key outside the app's folder (and its repository)`, { reason: \"private-key\" });\n }\n const out = userPath(outArg ?? join(dir, APP_BUNDLE_FILE));\n const sourcePath = join(dir, APP_SOURCE);\n const draft = readSource(sourcePath);\n\n // The version this one follows: the bundle already at the output, which only its own key may follow.\n let previous: AppManifest | null = null;\n if (existsSync(out)) {\n const read = readAppBundle(readBundleFile(out));\n if (!read.ok) throw refused(`${out} is there and is not a valid bundle: move it away, or name another --out`, read);\n previous = read.bundle.manifest;\n }\n\n let key: LoadedKey;\n if (existsSync(keyPath)) key = readKey(keyPath, \"publisher\");\n else if (previous) {\n throw new CliError(\"not_found\", `No key file ${keyPath}: ${out} is signed by ${appFingerprint(previous.publisher)}, and only that key publishes its next version`);\n } else key = makeKey(\"publisher\");\n\n if (previous && previous.publisher !== key.key) {\n throw refused(`${out} is ${appRef(previous.publisher, previous.name)}, signed by another key (${appFingerprint(previous.publisher)}): a version of an app is signed by its own key`, { reason: \"other-app\" }, { publisher: previous.publisher });\n }\n if (previous && previous.name !== draft.name) {\n throw refused(`${out} is the app ${shownValue(previous.name)}, not ${shownValue(draft.name)}: name another --out for another app`, { reason: \"other-app\" });\n }\n\n if (sequenceArg !== undefined && previous && sequenceArg <= previous.sequence) {\n throw refused(`--sequence ${sequenceArg} is not higher than the ${previous.sequence} of ${out}: every client refuses a lower one, and the same one with other content is equivocation`, { reason: sequenceArg < previous.sequence ? \"rollback\" : \"equivocation\" }, { previous: previous.sequence });\n }\n const sequence = sequenceArg ?? Math.max(previous ? previous.sequence + 1 : 1, (draft.sequence as number | undefined) ?? 1);\n // The bundle at the folder's default name is this command's own output too: published into another --out, the\n // version an earlier publish left there went into the new bundle as one of its files.\n // The folder's revocations and those beside the output (where `app revoke --bundle` writes them), one list when the same.\n const lists = [...new Set([join(dir, APP_REVOKE_FILE), join(dirname(out), APP_REVOKE_FILE)])];\n const { files, skipped } = collectFiles(dir, new Set([sourcePath, out, join(dir, APP_BUNDLE_FILE), ...lists]));\n const contents = files.map((f) => ({ path: f.path, bytes: new Uint8Array(readFileSync(f.full)) }));\n // A bundle is public: a private key found in the folder (an old key, a store key, any PEM) stops the publish.\n const keyFile = contents.find((f) => PRIVATE_KEY.test(Buffer.from(f.bytes).toString(\"latin1\")));\n if (keyFile) throw refused(`${keyFile.path} in ${dir} holds a private key, and a bundle is public: move it out of the app's folder`, { reason: \"private-key\", detail: keyFile.path });\n const manifest = {\n ...draft,\n ghostlyApp: 1,\n publisher: key.key,\n sequence,\n files: contents.map((f) => ({ path: f.path, size: f.bytes.length, sha256: toBase64Url(createHash(\"sha256\").update(f.bytes).digest()) })),\n };\n const checked = checkAppManifest(JSON.parse(JSON.stringify(manifest)), { strict: true });\n if (!checked.ok) {\n // A field missing from the source, said where it goes (\"kind in ghostly-app.json\"), not as a missing --key; the\n // JSON detail stays the field's name.\n const said = checked.reason === \"missing-key\" ? { ...checked, detail: `${checked.detail} in ${APP_SOURCE}` } : checked;\n throw refused(`${sourcePath} and the folder's files make no valid manifest`, said, checked.detail ? { detail: checked.detail } : {});\n }\n\n const { bytes: manifestBytes, signature } = await signAppObject(APP_PREFIXES.app, checked.manifest, key.signer);\n const bundle = assembleAppBundle(manifestBytes, canonicalJsonBytes(signature), contents.map((f) => f.bytes));\n // Read back as a client would (the icon's header, the bundle's size): what is written is never a bundle it refuses.\n const read = readAppBundle(bundle);\n if (!read.ok) throw refused(\"The bundle made is not valid\", read);\n // Nor one those revocations already stop: every client that reads them would refuse it, for good.\n const ref = appRef(key.key, checked.manifest.name);\n const held = lists.flatMap((path) => {\n if (!existsSync(path)) return [];\n const revocations = readAppRevocations(new Uint8Array(readFileSync(path)));\n return revocations.ok ? revocations.revocations.map((r) => ({ path, r })) : [];\n });\n const stopping = held.find(({ r }) => appRevocationFor({ ref, sequence, digest: read.bundle.digest }, [r]));\n if (stopping) {\n const clear = Math.max(sequence, ...held.map(({ r }) => r.statement.app === ref && \"upTo\" in r.statement ? r.statement.upTo : 0)) + 1;\n throw refused(`${stopping.path} already revokes version ${sequence} of ${ref}, and every client that reads it would stop it: give --sequence ${clear}`, { reason: \"revoked\" }, { sequence: clear });\n }\n saveKeyThen(keyPath, key, () => {\n mkdirSync(dirname(out), { recursive: true });\n writeWhole(out, bundle);\n });\n\n return {\n ...described(read.bundle, bundle),\n previous: previous?.sequence ?? null,\n out,\n files: contents.map((f) => f.path),\n ...(skipped.length ? { skipped } : {}),\n keyCreated: key.created,\n ...(key.created ? { warning: madeKeyNote(keyPath, \"publisher\", key.key) } : {}),\n };\n}\n\n// ---------- revocations ----------\n\n/**\n * `app revoke <dir> --key <file> (--digest <digest>... | --up-to <sequence>) [--reason <text>] [--bundle <file>]`: a\n * `ghostly-revoke/1` statement (WISP 1200 · Publisher keys, Revocation) for the app whose bundle is `<dir>/app.ghostlyapp`\n * (or `--bundle`), signed by that app's publisher key and added to the `ghostly-revoke.json` beside that bundle, which\n * stays canonical.\n * The key is never made here: only the key that signed the app may revoke its versions.\n */\nexport async function revokeApp(dirArg: string, keyArg: string, what: { digests?: string[]; upTo?: number; reason?: string; bundle?: string; force?: boolean }): Promise<Record<string, unknown>> {\n const dir = userPath(dirArg);\n const bundlePath = userPath(what.bundle ?? join(dir, APP_BUNDLE_FILE));\n // Beside the bundle, where clients, app verify and app serve read it: a list left in <dir> beside a bundle published\n // from elsewhere stops nothing.\n const listPath = join(dirname(bundlePath), APP_REVOKE_FILE);\n const usage = \"ghostly app revoke <dir> --key <file> (--digest <digest>... | --up-to <sequence>) [--reason <text>] [--bundle <file>] [--force]\";\n // Sorted, so the same digests in another order are the same statement, signed and compared once.\n const digests = [...(what.digests ?? [])].sort();\n if ((digests.length > 0) === (what.upTo !== undefined)) throw new CliError(\"usage\", `Give --digest (again for each) or --up-to, one of the two: ${usage}`);\n if (what.upTo !== undefined && !(Number.isSafeInteger(what.upTo) && what.upTo >= 1)) throw new CliError(\"usage\", `--up-to takes a sequence, a whole number from 1, not ${what.upTo}`);\n // Checked here as the statement's checker checks them, so a bad value is a usage error naming its option.\n for (const [i, digest] of digests.entries()) {\n if (!isAppHash(digest)) throw new CliError(\"usage\", `--digest ${JSON.stringify(digest)} is not a bundle digest (43 base64url characters, as app verify prints it)`);\n if (digests.indexOf(digest) !== i) throw new CliError(\"usage\", `--digest ${digest} is given twice`);\n }\n if (digests.length > APP_STATEMENT_LIMITS.revokeDigests) throw new CliError(\"usage\", `--digest is given at most ${APP_STATEMENT_LIMITS.revokeDigests} times in one revocation, not ${digests.length}`);\n // An empty reason is refused as an empty --title is: every client shows it, and it would say nothing.\n if (what.reason !== undefined && !isAppLine(what.reason, APP_STATEMENT_LIMITS.reason, 1)) {\n const length = [...what.reason].length;\n throw new CliError(\"usage\", `--reason is one line of 1 to ${APP_STATEMENT_LIMITS.reason} characters, not ${length > APP_STATEMENT_LIMITS.reason ? `${length} characters` : JSON.stringify(what.reason)}`);\n }\n // The list is published beside the bundle and every client shows the reason (docs/CLI.md § Safety).\n guardText(what.reason, what.force === true, \"reason\", \"revoke\");\n\n if (!existsSync(bundlePath)) throw new CliError(\"not_found\", `No bundle ${bundlePath}: a revocation names the app of the bundle in <dir> (or --bundle)`);\n const read = readAppBundle(readBundleFile(bundlePath));\n if (!read.ok) throw refused(`${bundlePath} is not a valid bundle`, read);\n const manifest = read.bundle.manifest;\n const ref = appRef(manifest.publisher, manifest.name);\n // Clients keep a revocation for good: past the newest version (a typo, 30 for 3), it stops versions not made yet.\n // --force lifts it, so it asks for a confirmation, as every refusal --force lifts does.\n if (what.upTo !== undefined && what.upTo > manifest.sequence && !what.force) {\n throw new CliError(\"confirm\", `--up-to ${what.upTo} is past ${bundlePath}'s version, ${manifest.sequence}: it would also stop versions ${manifest.sequence + 1} to ${what.upTo} before they exist, for good. Give --up-to ${manifest.sequence}, or --force if versions up to ${what.upTo} were published from elsewhere`);\n }\n\n const keyPath = userPath(keyArg);\n if (!existsSync(keyPath)) throw new CliError(\"not_found\", `No key file ${keyPath}: only the key that signed ${ref} (${appFingerprint(manifest.publisher)}) revokes its versions`);\n const key = readKey(keyPath, \"publisher\");\n if (key.key !== manifest.publisher) {\n throw refused(`${keyPath} is not the publisher key of ${ref} (${appFingerprint(manifest.publisher)}): a revocation by any other key is refused by every client`, { reason: \"signature-key\" });\n }\n\n const statement = (digests.length\n ? { ghostlyRevoke: 1, app: ref, digests }\n : { ghostlyRevoke: 1, app: ref, upTo: what.upTo }) as AppRevokeStatement;\n if (what.reason !== undefined) statement.reason = what.reason;\n const problem = checkAppRevokeStatement(statement);\n if (problem) throw refused(\"Not a revocation a client reads\", { reason: \"bad-revocation\", detail: problem });\n\n // Each revocation's signature is checked once: the held list's are not checked again when the new list is read back.\n const checked = new Set<string>();\n let list: SignedAppRevocation[] = [];\n if (existsSync(listPath)) {\n const held = readAppRevocations(new Uint8Array(readFileSync(listPath)), checked);\n if (!held.ok) throw refused(`${listPath} is there and is not a valid ghostly-revoke.json: fix or move it first`, held);\n list = held.revocations;\n }\n const signed = await signAppRevocation(statement, key.signer);\n // A held list made before the digests were sorted may hold them in another order: compared sorted too.\n const sorted = (s: AppRevokeStatement) => canonicalJson(\"digests\" in s ? { ...s, digests: [...s.digests].sort() } : s);\n const same = list.some((r) => sorted(r.statement) === sorted(signed.statement));\n if (!same) {\n if (list.length >= APP_STATEMENT_LIMITS.revocations) throw refused(`${listPath} holds ${list.length} revocations already`, { reason: \"bad-revocation\", detail: `at most ${APP_STATEMENT_LIMITS.revocations}` });\n list = [...list, signed];\n const bytes = canonicalJsonBytes(list);\n const check = readAppRevocations(bytes, checked);\n if (!check.ok) throw refused(\"The revocation list made is not valid\", check);\n writeWhole(listPath, bytes);\n }\n const covers = digests.length\n ? { digests, current: digests.includes(read.bundle.digest) }\n : { upTo: what.upTo, current: manifest.sequence <= what.upTo! };\n return { app: ref, ...covers, ...(what.reason !== undefined ? { reason: what.reason } : {}), added: !same, revocations: list.length, file: listPath };\n}\n\n// ---------- store indexes ----------\n\n/**\n * `store sign <index> --key <file> [--out <dir>]`: a store index written by hand (any JSON layout; `key` may be left\n * out and is then the signing key's) becomes `ghostly-store.json`, canonical, and `ghostly-store.sig`, in `--out` or\n * beside the index. It is read back as a client reads it (`expires` at most 90 days ahead), and refused when the index\n * already there has a higher `sequence`, or the same one with other content, or is signed by another key (another\n * store is another `--out`), or when a `ghostly-store.json` or `.sig` there does not read as a signed index. The key is\n * made only when neither is there, and never read or made inside the output folder, which is published.\n */\nexport async function signStore(indexArg: string, keyArg: string, outArg?: string, now = Math.floor(Date.now() / 1000)): Promise<Record<string, unknown>> {\n const indexPath = userPath(indexArg);\n const keyPath = userPath(keyArg);\n const outDir = userPath(outArg ?? dirname(indexPath));\n let text: string, value: unknown;\n try { text = readFileSync(indexPath, \"utf8\"); value = JSON.parse(text); } catch (error) {\n if (error instanceof SyntaxError) throw new CliError(\"bad_request\", `${indexPath} is not JSON: ${error.message}`);\n throw localFileError(error, indexPath) ?? error;\n }\n refuseRepeatedKey(indexPath, text);\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new CliError(\"bad_request\", `${indexPath} is not a JSON object`);\n const index = value as Record<string, unknown>;\n // The folder is published (a repository served raw): a store key there signs any index for every client of the store.\n if (isInside(outDir, keyPath)) {\n throw refused(`${keyPath} is inside ${outDir}, which is published: keep the store key outside the store's folder (and its repository)`, { reason: \"private-key\" });\n }\n\n // The index this one follows, when the folder holds a signed one: a store is its key, so only that key signs over it.\n const indexOut = join(outDir, STORE_INDEX_FILE), sigOut = join(outDir, STORE_SIG_FILE);\n // Each revocation's signature is checked once, though the held index, the new one and its read-back all carry it.\n const checked = new Set<string>();\n let held: AppStoreReading | null = null;\n // A pair there that does not read as a signed index (one of the two missing, or damaged) is not written over, as\n // `app publish` does not write over a bundle it cannot read: its sequence and key are not known, so neither is a rollback.\n let unread: CliError | null = null;\n const heldIndex = existsSync(indexOut) ? new Uint8Array(readFileSync(indexOut)) : null;\n const heldSig = existsSync(sigOut) ? new Uint8Array(readFileSync(sigOut)) : null;\n if (heldIndex || heldSig) {\n const read = !heldIndex ? { ok: false as const, reason: \"missing-file\", detail: `no ${STORE_INDEX_FILE}` }\n : !heldSig ? { ok: false as const, reason: \"bad-signature-statement\", detail: `no ${STORE_SIG_FILE}` }\n : readAppStore(heldIndex, heldSig, now, undefined, checked);\n if (read.ok) held = read.store;\n else unread = refused(`${heldIndex ? indexOut : sigOut} is there and is not a signed store index: move ${STORE_INDEX_FILE} and ${STORE_SIG_FILE} away, or name another --out`, read);\n }\n\n let key: LoadedKey;\n if (existsSync(keyPath)) key = readKey(keyPath, \"store\");\n else if (index.key !== undefined) throw new CliError(\"not_found\", `No key file ${keyPath}: the index names the store key ${typeof index.key === \"string\" ? appFingerprint(index.key) : JSON.stringify(index.key)}`);\n else if (unread) throw unread;\n else if (held) throw new CliError(\"not_found\", `No key file ${keyPath}: ${indexOut} is signed by ${appFingerprint(held.index.key)}, and only that key signs its next index`);\n else key = makeKey(\"store\");\n if (index.key !== undefined && index.key !== key.key) {\n throw refused(`${indexPath} names another store key than ${keyPath}'s (${appFingerprint(key.key)})`, { reason: \"store-key\" });\n }\n if (held && held.index.key !== key.key) {\n throw refused(`${indexOut} is signed by another store key (${appFingerprint(held.index.key)}) than ${keyPath}'s (${appFingerprint(key.key)}): a store is its key; sign with that key, or give another --out for another store`, { reason: \"store-key\" }, { held: held.index.key });\n }\n index.key = key.key;\n\n const valid = checkAppStoreIndex(index, { strict: true }, checked);\n if (!valid.ok) throw refused(`${indexPath} is not a valid store index`, valid);\n const { indexBytes, sigBytes } = await signAppStore(index as unknown as AppStoreIndex, key.signer, checked);\n const read = readAppStore(indexBytes, sigBytes, now, key.key, checked);\n if (!read.ok) throw refused(`${indexPath} would be refused by a client`, read);\n const store = read.store;\n // Unless the signature there is this one's bytes (Ed25519 is deterministic): a run stopped between the signature's\n // rename and the index's, signed again. Not the index's bytes: a held index edited in place is this one's bytes too,\n // and its own signature is the only trace of the sequence it held.\n if (unread && !(heldSig && Buffer.from(heldSig).equals(sigBytes))) throw unread;\n\n let previous: number | null = null;\n if (held) {\n previous = held.index.sequence;\n const decision = appStoreDecision(\n { key: key.key, sequence: held.index.sequence, digest: held.digest },\n { key: key.key, sequence: store.index.sequence, digest: store.digest },\n );\n if (decision === \"rollback\" || decision === \"equivocation\") {\n throw refused(`${indexOut} already holds sequence ${held.index.sequence} of this store: ${decision === \"rollback\" ? \"a lower one is refused by every client\" : \"the same one with other content is refused as equivocation\"}; raise sequence`, { reason: decision }, { held: held.index.sequence });\n }\n }\n\n // The signature first, so a run stopped before the index leaves what a run again tells apart (above); once it is\n // written the key stays: the signature names it, and a run again signs with it.\n saveKeyThen(keyPath, key, () => {\n mkdirSync(outDir, { recursive: true });\n writeWhole(sigOut, sigBytes);\n });\n writeWhole(indexOut, indexBytes);\n const notes = [\n ...(key.created ? [madeKeyNote(keyPath, \"store\", key.key)] : []),\n ...(store.expired ? [`expires (${new Date(store.index.expires * 1000).toISOString()}) is past: clients still install from it and say the store was not updated since then`] : []),\n ];\n return {\n key: key.key, fingerprint: appFingerprint(key.key), name: store.index.name, kind: store.index.kind,\n sequence: store.index.sequence, previous, expires: store.index.expires, expired: store.expired,\n apps: store.index.apps.length, removed: store.index.removed.length, revoked: store.index.revoked.length,\n digest: store.digest, index: indexOut, sig: sigOut, keyCreated: key.created,\n ...(notes.length ? { warning: notes.join(\"; \") } : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;AAQA,IAAM,QAAQ,SAAiB,KAAK,QAAQ,YAAY,OAAO;CAAE,KAAK;CAAS,KAAK;CAAQ,KAAK;CAAQ,MAAK;AAAS,EAAA,CAAG,EAAG;;AAG7H,SAAgB,iBAAiB,EAAE,MAAM,SAA+C;CACtF,OAAO;EACL;EACA,SAAS;EACT,MAAM;EACN;EACA,SAAS;EACT,aAAa;EACb,OAAO;EACP,aAAa,CAAC,MAAM;EACpB,MAAM;EACN,SAAS;GAAE,MAAM;GAAS,SAAS,CAAC,OAAO,SAAS;EAAE;EACtD,SAAS;CACX;AACF;;;;;;;AAQA,SAAgB,aAAa,EAAE,SAA8B;CAC3D,OAAO;;;;;SAKA,KAAK,KAAK,EAAE;;;;;;;;;;;;;;MAcf,KAAK,KAAK,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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S,EAAE,SAAS,MAAM,KAAK,IAAI,EAAE,IAAI,CAAC;CACtD;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export { s as initApp, c as publishApp, l as revokeApp, u as signStore, d as verifyApp } from "./apps-
|
|
1
|
+
export { s as initApp, c as publishApp, l as revokeApp, u as signStore, d as verifyApp } from "./apps-gXpGFPiv.js";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { f as assertWholeSats, h as validatePaymentTarget, u as arkAddressPrefix } from "./paymentIntent-
|
|
1
|
+
import { f as assertWholeSats, h as validatePaymentTarget, u as arkAddressPrefix } from "./paymentIntent-Cr3uZa_0.js";
|
|
2
2
|
import { ArkAddress, EsploraProvider, IndexedDBContractRepository, IndexedDBWalletRepository, MnemonicIdentity, RestArkProvider, RestIndexerProvider, Transaction, Wallet, assertAllowedSighashTypes, assertSubmittedArkTxid, canRecoverOnchain, isVtxoSpent, matchServerCheckpoints, verifyTapscriptSignatures } from "@arkade-os/sdk";
|
|
3
3
|
import { tapLeafHash } from "@scure/btc-signer/payment.js";
|
|
4
4
|
// ../browser/src/engine/paymentAdapters/arkade.ts
|
|
@@ -365,4 +365,4 @@ var ArkadeAdapter = class ArkadeAdapter {
|
|
|
365
365
|
};
|
|
366
366
|
export { ARK_NETWORKS, ArkadeAdapter };
|
|
367
367
|
|
|
368
|
-
//# sourceMappingURL=arkade-
|
|
368
|
+
//# sourceMappingURL=arkade-B6UNf5HI.js.map
|