diff --git a/.env b/.env index f63e6164..35c1182f 100644 --- a/.env +++ b/.env @@ -1,3 +1,4 @@ -ATPROTO_CLIENT_ID=https://cimd-service.fly.dev/clients/bafyreiafqw2fao73uzdvg7rzvvcq7d4z5fvjhqc5qcqo6yzqq3p5dh6j2y +ATPROTO_PUBLIC_CLIENT_ID=https://cimd-service.fly.dev/clients/bafyreiafqw2fao73uzdvg7rzvvcq7d4z5fvjhqc5qcqo6yzqq3p5dh6j2y +ATPROTO_SPACE_CLIENT_ID=https://cimd-service.fly.dev/clients/bafyreibxk62vlgqlo45yhimfqmom47korhoxssmc3p7bnhod56ik7z5rka ROCKSKY_ATPROTO_CLIENT_ID=https://cimd-service.fly.dev/clients/bafyreihmrs2hsh5fp535lbidz4yt3f63pyh42d6gwpchf3vrr2kxie3cpu # DISABLE_AUTOMATIC_TRACKS_PROCESSING=t diff --git a/deno.jsonc b/deno.jsonc index 773a6b55..fd5198e3 100644 --- a/deno.jsonc +++ b/deno.jsonc @@ -58,6 +58,10 @@ "butterchurn": "npm:butterchurn@3.0.0-beta.5", "butterchurn-presets": "npm:butterchurn-presets@3.0.0-beta.4", + // @atproto spaces alpha + "@atproto/api": "npm:@atproto/api@0.0.0-spaces-alpha-20260818163953", + "@atproto/oauth-client-browser": "npm:@atproto/oauth-client-browser@0.0.0-spaces-alpha-20260818163953", + // music-metadata "@tokenizer/http": "npm:@tokenizer/http@^0.9.2", "@tokenizer/range": "npm:@tokenizer/range@^0.13.1", @@ -186,6 +190,7 @@ "./components/output/polymorphic/indexed-db/element.js": "./src/components/output/polymorphic/indexed-db/element.js", "./components/output/polymorphic/indexed-db/worker.js": "./src/components/output/polymorphic/indexed-db/worker.js", "./components/output/raw/atproto-passkey/element.js": "./src/components/output/raw/atproto-passkey/element.js", + "./components/output/raw/atproto-space/element.js": "./src/components/output/raw/atproto-space/element.js", "./components/supplement/last.fm/element.js": "./src/components/supplement/last.fm/element.js", "./components/supplement/listenbrainz/element.js": "./src/components/supplement/listenbrainz/element.js", "./components/supplement/rocksky/element.js": "./src/components/supplement/rocksky/element.js", @@ -198,6 +203,7 @@ "./components/transformer/output/bytes/dasl-sync/element.js": "./src/components/transformer/output/bytes/dasl-sync/element.js", "./components/transformer/output/bytes/json/element.js": "./src/components/transformer/output/bytes/json/element.js", "./components/transformer/output/raw/atproto-sync/element.js": "./src/components/transformer/output/raw/atproto-sync/element.js", + "./components/transformer/output/raw/atproto-space-sync/element.js": "./src/components/transformer/output/raw/atproto-space-sync/element.js", "./components/transformer/output/refiner/default/element.js": "./src/components/transformer/output/refiner/default/element.js", "./components/transformer/output/refiner/initial-contents/element.js": "./src/components/transformer/output/refiner/initial-contents/element.js", "./components/transformer/output/refiner/passkey-encryption/element.js": "./src/components/transformer/output/refiner/passkey-encryption/element.js", @@ -234,6 +240,7 @@ "./components/output/bytes/dropbox/types.d.ts": "./specs/components/output/bytes/dropbox/types.d.ts", "./components/output/polymorphic/indexed-db/types.d.ts": "./specs/components/output/polymorphic/indexed-db/types.d.ts", "./components/output/raw/atproto-passkey/types.d.ts": "./specs/components/output/raw/atproto-passkey/types.d.ts", + "./components/output/raw/atproto-space/types.d.ts": "./specs/components/output/raw/atproto-space/types.d.ts", "./components/output/types.d.ts": "./specs/components/output/types.d.ts", "./components/supplement/types.d.ts": "./specs/components/supplement/types.d.ts", "./components/transformer/output/bytes/automerge/types.d.ts": "./specs/components/transformer/output/bytes/automerge/types.d.ts", diff --git a/lexicons/atproto/permissions.json b/lexicons/atproto/permissions.json new file mode 100644 index 00000000..0c368ae9 --- /dev/null +++ b/lexicons/atproto/permissions.json @@ -0,0 +1,28 @@ +{ + "lexicon": 1, + "id": "sh.diffuse.atproto.permissions", + "defs": { + "main": { + "type": "permission-set", + "title": "Diffuse", + "detail": "Store and sync your Diffuse library in a private space", + "permissions": [ + { + "type": "permission", + "resource": "space", + "spaceType": "sh.diffuse.atproto.space", + "authority": "self", + "skey": "self", + "collection": [ + "sh.diffuse.output.facet", + "sh.diffuse.output.playlistItemBundle", + "sh.diffuse.output.setting", + "sh.diffuse.output.trackBundle" + ], + "action": ["read", "create", "update", "delete"], + "manage": ["create", "update", "delete"] + } + ] + } + } +} diff --git a/lexicons/atproto/space.json b/lexicons/atproto/space.json new file mode 100644 index 00000000..7fdefca0 --- /dev/null +++ b/lexicons/atproto/space.json @@ -0,0 +1,18 @@ +{ + "lexicon": 1, + "id": "sh.diffuse.atproto.space", + "defs": { + "main": { + "type": "space", + "key": "literal:self", + "name": "Diffuse Library", + "description": "The user's personal Diffuse library, stored in a permissioned AT Protocol space.", + "collections": [ + "sh.diffuse.output.facet", + "sh.diffuse.output.playlistItemBundle", + "sh.diffuse.output.setting", + "sh.diffuse.output.trackBundle" + ] + } + } +} diff --git a/specs/components/output/raw/atproto-space/SPEC.md b/specs/components/output/raw/atproto-space/SPEC.md new file mode 100644 index 00000000..74091e7c --- /dev/null +++ b/specs/components/output/raw/atproto-space/SPEC.md @@ -0,0 +1,19 @@ +# AT Protocol space raw output + +This element implements the output element interface using a permissioned AT +Protocol data space (`sh.diffuse.atproto.space`). + +## Requirements + +- The four definition lexicons (`facet`, `playlistItemBundle`, `setting`, + `trackBundle`) are used as the schema for each output type, stored as records + in a *personal* space (authority = the user's own DID, key `self`). +- Authentication uses OAuth with a `space:` scope; the browser OAuth client is + `@atproto/oauth-client-browser`. +- No passkey encryption is applied: space data is access-controlled rather than + public, so records are not assembled and rebroadcast by a relay. +- Unlike the public AT Protocol output there is no firehose/relay. Reading uses + the space sync methods (`com.atproto.space.listRecords`, `listRepoOps`, + `getRepo`) directly from the user's PDS. +- Tracks/playlist items are stored as CBOR blob bundles, as in the public + output, to keep the number of records (and PDS rate-limit pressure) low. diff --git a/specs/components/output/raw/atproto-space/types.d.ts b/specs/components/output/raw/atproto-space/types.d.ts new file mode 100644 index 00000000..097cc63a --- /dev/null +++ b/specs/components/output/raw/atproto-space/types.d.ts @@ -0,0 +1,13 @@ +import type { SignalReader } from "~/common/signal.d.ts"; +import type { OutputElement } from "@specs/components/output/types.d.ts"; + +export type ATProtoSpaceOutputElement = + & OutputElement + & { + did: SignalReader; + handle: SignalReader; + + login(handle: string): Promise; + logout(): Promise; + whenRestored(): Promise; + }; diff --git a/src/_data/facets.json b/src/_data/facets.json index 8dc28e8f..3332269e 100644 --- a/src/_data/facets.json +++ b/src/_data/facets.json @@ -84,6 +84,13 @@ "category": "Data", "desc": "Use your AT Protocol account for user-data storage. Your data will be stored as public records, but sensitive data can be encrypted using a passkey." }, + { + "url": "facets/connect/atproto-space/index.html", + "title": "Connect / Atmosphere (Space)", + "category": "Data", + "incomplete": true, + "desc": "Use your AT Protocol account for user-data storage. Your data is stored in your own repo and is not broadcast publicly." + }, { "url": "facets/connect/dropbox/index.html", "title": "Connect / Dropbox", @@ -328,4 +335,4 @@ "incomplete": true, "desc": "Manage where your user-data is stored. See which storage method is active, switch between methods, and migrate data between them." } -] \ No newline at end of file +] diff --git a/src/common/facets/utils.js b/src/common/facets/utils.js index 4952e415..e52da8cd 100644 --- a/src/common/facets/utils.js +++ b/src/common/facets/utils.js @@ -8,6 +8,14 @@ import { STARTING_SET_DISABLED, TYPE } from "./constants.js"; import facetsData from "~/_data/facets.json" with { type: "json" }; +// A single, fixed creation timestamp (today's date) shared by all starting +// set / base facets. It's a constant string (not computed at runtime), so +// seeded facets keep an identical timestamp across calls, devices and days +// — if it changed, the dasl-sync merge would see a perpetually-newer copy and +// never converge. Using UTC midnight keeps the value timezone-independent. Any +// real edit writes a strictly-newer `updatedAt`, so it always wins. +const SEED_TIMESTAMP = "2026-08-23T00:00:00.000Z"; + /** * @import {Facet} from "~/definitions/types.d.ts" */ @@ -30,6 +38,7 @@ import facetsData from "~/_data/facets.json" with { type: "json" }; * if (facets.some((f) => !f.id)) throw new Error("every facet needs an id"); * ``` */ + export function buildFacets(uris) { return facetsData.flatMap((facet) => { if (!uris.includes(facet.url)) return []; @@ -37,11 +46,13 @@ export function buildFacets(uris) { return [{ $type: TYPE, id: uriToRkey("diffuse://" + facet.url), + createdAt: SEED_TIMESTAMP, description: facet.desc, enabled: STARTING_SET_DISABLED.includes(facet.url) ? false : true, kind: facet.kind === "prelude" ? "prelude" : "interactive", name: facet.title, tags: facet.tags?.length ? facet.tags : undefined, + updatedAt: SEED_TIMESTAMP, uri: "diffuse://" + facet.url, }]; }); diff --git a/src/components/output/raw/atproto-passkey/oauth.js b/src/components/output/raw/atproto-passkey/oauth.js index fdbe6e14..15476156 100644 --- a/src/components/output/raw/atproto-passkey/oauth.js +++ b/src/components/output/raw/atproto-passkey/oauth.js @@ -48,7 +48,7 @@ const client_id = isLocalDev ? `http://localhost/?redirect_uri=${encodeURIComponent(redirect_uri)}&scope=${ encodeURIComponent(SCOPE) }` - : /** @type {any} */ (import.meta).env?.ATPROTO_CLIENT_ID ?? + : /** @type {any} */ (import.meta).env?.ATPROTO_PUBLIC_CLIENT_ID ?? "https://elements.diffuse.sh/latest/components/output/raw/atproto-passkey/oauth-client-metadata.json"; const OAUTH_CONFIG = { diff --git a/src/components/output/raw/atproto-space/element.js b/src/components/output/raw/atproto-space/element.js new file mode 100644 index 00000000..0b367316 --- /dev/null +++ b/src/components/output/raw/atproto-space/element.js @@ -0,0 +1,547 @@ +import { Agent } from "@atproto/api"; +import { decode, encode } from "@atcute/cbor"; +import { xxh32r } from "xxh32/dist/raw.js"; + +import { computed, signal } from "~/common/signal.js"; +import { BroadcastedOutputElement, outputManager } from "../../common.js"; +import { defineElement } from "~/common/element.js"; + +import { login, logout, restoreOrFinalize } from "./oauth.js"; + +/** + * @import {OutputManager} from "@specs/components/output/types.d.ts" + * @import {ATProtoSpaceOutputElement} from "@specs/components/output/raw/atproto-space/types.d.ts" + * @import {OAuthSession} from "@atproto/oauth-client" + */ + +const SPACE_TYPE = "sh.diffuse.atproto.space"; +const SPACE_KEY = "self"; + +//////////////////////////////////////////// +// ELEMENT +//////////////////////////////////////////// + +/** + * Raw output backed by an AT Protocol permissioned data space, storing the + * user's Diffuse data in their own (`authority=self`) space. + * + * @implements {ATProtoSpaceOutputElement} + */ +class ATProtoSpaceOutput extends BroadcastedOutputElement { + static NAME = "diffuse/output/raw/atproto-space"; + + #manager; + + /** @type {PromiseWithResolvers} */ + #restoreSettled = Promise.withResolvers(); + + /** @type {Agent | null} */ + #agent = null; + + /** @type {OAuthSession | null} */ + #session = null; + + #writing = 0; + + /** @type {Array<{ fn: () => Promise, resolve: () => void, reject: (err: unknown) => void }>} */ + #writeQueue = []; + #writeDraining = false; + /** @type {Map} */ + #writeCancels = new Map(); + + #did = signal(/** @type {string | null} */ (null)); + #handle = signal(/** @type {string | null} */ (null)); + + did = this.#did.get; + handle = this.#handle.get; + + ready = computed(() => this.#did.value !== null && this.#agent !== null); + + constructor() { + super(); + + /** @type {OutputManager} */ + this.#manager = outputManager({ + init: async () => { + await this.#restoreSettled.promise; + return true; + }, + facets: this.#recordCollection("sh.diffuse.output.facet"), + playlistItems: this.#blobCollection( + "sh.diffuse.output.playlistItemBundle", + { groupBy: "playlist" }, + ), + settings: this.#recordCollection("sh.diffuse.output.setting"), + tracks: this.#blobCollection("sh.diffuse.output.trackBundle", { + groupBy: "scheme", + keyOf: (item) => { + const uri = String( + /** @type {Record} */ (item)["uri"] ?? "", + ); + const colon = uri.indexOf(":"); + return colon > 0 ? uri.substring(0, colon) : undefined; + }, + }), + }); + + this.facets = this.#manager.facets; + this.playlistItems = this.#manager.playlistItems; + this.settings = this.#manager.settings; + this.tracks = this.#manager.tracks; + } + + // LIFECYCLE + + /** @override */ + connectedCallback() { + this.replicateSavedData(this.#manager); + + super.connectedCallback(); + + this.#tryRestore(); + } + + // AUTH + + /** + * Initiate the OAuth flow with a `space:` scope. + * + * @param {string} handle + */ + async login(handle) { + const session = await login(handle); + this.#setSession(session); + } + + /** @returns {Promise} */ + whenRestored() { + return this.#restoreSettled.promise; + } + + async logout() { + if (this.#session) { + await logout(this.#session); + this.#session = null; + this.#agent = null; + this.#did.value = null; + this.#handle.value = null; + } + } + + async #tryRestore() { + await this.whenConnected(); + + try { + const session = await restoreOrFinalize(); + if (session) this.#setSession(session); + } finally { + this.#restoreSettled.resolve(); + } + } + + /** + * @param {OAuthSession} session + */ + #setSession(session) { + // The OAuth session's DPoP-bound fetch handler plugs directly into the + // generated client; every request is authenticated with the access token. + this.#agent = new Agent((url, init) => session.fetchHandler(url, init)); + this.#session = session; + this.#did.value = session.did; + this.#ensureSpace(); + } + + // SPACE + + #spaceUri() { + const did = this.#did.value; + if (!did) return null; + return `at://${did}/space/${SPACE_TYPE}/${SPACE_KEY}`; + } + + /** + * Ensure the personal space exists, creating it on first use. + * + * Existence is probed with `getSpace` (scoped to our own space, needing only + * `read_self`) rather than `listSpaces` (which needs `authority=*`) or an + * unconditional `createSpace` (which 400s with `SpaceAlreadyExists` on every + * subsequent page load). + */ + async #ensureSpace() { + const agent = this.#agent; + const space = this.#spaceUri(); + if (!agent || !space) return; + + try { + await agent.com.atproto.simplespace.getSpace({ space }); + return; // already exists + } catch (err) { + const code = err && typeof err === "object" + ? /** @type {{ error?: string }} */ (err).error + : undefined; + if (code !== "SpaceNotFound") throw err; + } + + await agent.com.atproto.simplespace.createSpace({ + type: SPACE_TYPE, + skey: SPACE_KEY, + policy: { $type: "com.atproto.simplespace.defs#memberListPolicy" }, + appAccess: { $type: "com.atproto.simplespace.defs#open" }, + }); + } + + // RECORDS + + /** + * Returns `{ empty, get, put }` for a small record collection (facets, settings). + * + * @param {string} nsid + */ + #recordCollection(nsid) { + /** @type {Map> | null} */ + let lastKnown = null; + + return { + empty: () => [], + get: async () => { + const records = await this.#listRecords(nsid); + lastKnown = new Map( + /** @type {Array>} */ (records).map((r) => [ + String(r["id"]), + r, + ]), + ); + return records; + }, + put: async (/** @type {unknown[]} */ data) => { + const nsidTyped = /** @type {`${string}.${string}.${string}`} */ (nsid); + + /** @type {Map>} */ + const desired = new Map( + /** @type {Array<{ id: string }>} */ (data).map((r) => [ + r.id, + /** @type {Record} */ ({ $type: nsidTyped, ...r }), + ]), + ); + + const known = lastKnown ?? new Map(); + + /** @type {Array<[string, Record]>} */ + const upserts = []; + for (const [id, record] of desired) { + const existing = known.get(id); + if (existing && JSON.stringify(existing) === JSON.stringify(record)) { + continue; + } + upserts.push([id, record]); + } + + /** @type {Array<{ $type: "com.atproto.space.applyWrites#delete", collection: string, rkey: string }>} */ + const deletes = []; + for (const id of known.keys()) { + if (!desired.has(id)) { + deletes.push({ + $type: "com.atproto.space.applyWrites#delete", + collection: nsidTyped, + rkey: id, + }); + } + } + + if (upserts.length === 0 && deletes.length === 0) return; + + const newKnown = new Map(known); + for (const [id, record] of upserts) newKnown.set(id, record); + for (const { rkey } of deletes) newKnown.delete(rkey); + + const prior = this.#writeCancels.get(nsid); + if (prior) prior.cancelled = true; + const token = { cancelled: false }; + this.#writeCancels.set(nsid, token); + + await this.#enqueueWrite(async () => { + if (token.cancelled) return; + const agent = this.#agent; + const did = this.#did.value; + const space = this.#spaceUri(); + if (!agent || !did || !space) return; + this.#writing++; + try { + for (const [rkey, record] of upserts) { + await agent.com.atproto.space.putRecord({ + space, + repo: did, + collection: nsidTyped, + rkey, + record, + }); + } + for (let i = 0; i < deletes.length; i += 100) { + await agent.com.atproto.space.applyWrites({ + space, + repo: did, + writes: deletes.slice(i, i + 100), + }); + } + lastKnown = newKnown; + } finally { + this.#writing--; + if (this.#writeCancels.get(nsid) === token) { + this.#writeCancels.delete(nsid); + } + } + }); + }, + }; + } + + /** + * Returns `{ empty, get, put }` for a collection stored as CBOR blobs. + * + * @param {string} nsid + * @param {{ groupBy: string, keyOf?: (item: unknown) => string | undefined }} options + */ + #blobCollection(nsid, { groupBy, keyOf } = /** @type {any} */ ({})) { + /** @type {Map} */ + let lastHashes = new Map(); + /** @type {Map} */ + let lastBlobs = new Map(); + + return { + empty: () => /** @type {unknown[]} */ ([]), + get: async () => { + const bundles = await this.#listRecords(nsid); + /** @type {unknown[]} */ + const items = []; + /** @type {Map} */ + const newHashes = new Map(); + /** @type {Map} */ + const newBlobs = new Map(); + + for (const bundle of bundles) { + if (!bundle.data?.ref?.$link) continue; + + const key = /** @type {Record} */ (bundle)[groupBy]; + if (typeof key !== "string") continue; + + const bytes = await this.#fetchBlob(bundle.data.ref.$link); + const groupItems = /** @type {unknown[]} */ (decode(bytes)); + if (!Array.isArray(groupItems)) continue; + + items.push(...groupItems); + newHashes.set(key, xxh32r(encode(groupItems)).toString(16)); + newBlobs.set(key, bundle.data); + } + + lastHashes = newHashes; + lastBlobs = newBlobs; + return items; + }, + put: async (/** @type {unknown[]} */ data) => { + const nsidTyped = /** @type {`${string}.${string}.${string}`} */ (nsid); + + const extractKey = keyOf ?? + ((/** @type {unknown} */ item) => + /** @type {string | undefined} */ ( + /** @type {Record} */ (item)[groupBy] + )); + + /** @type {Map} */ + const groups = new Map(); + for (const item of data) { + const key = extractKey(item); + if (typeof key !== "string") continue; + const group = groups.get(key) ?? []; + if (!groups.has(key)) groups.set(key, group); + group.push(item); + } + + const newHashes = new Map(lastHashes); + const newBlobs = new Map(lastBlobs); + + /** @type {Array<{ rkey: string, value: unknown }>} */ + const upserts = []; + + for (const [key, groupItems] of groups) { + const bytes = encode(groupItems); + const hash = xxh32r(bytes).toString(16); + + if (lastHashes.get(key) === hash && lastBlobs.has(key)) continue; + + const blob = await this.#uploadBlob(bytes); + if (!blob) continue; + + const rkey = xxh32r(encode(key)).toString(16); + const value = { + $type: nsidTyped, + id: rkey, + [groupBy]: key, + data: blob, + }; + upserts.push({ rkey, value }); + newHashes.set(key, hash); + newBlobs.set(key, blob); + } + + /** @type {Array<{ $type: "com.atproto.space.applyWrites#delete", collection: string, rkey: string }>} */ + const deletes = []; + for (const key of lastHashes.keys()) { + if (!groups.has(key)) { + const rkey = xxh32r(encode(key)).toString(16); + deletes.push({ + $type: "com.atproto.space.applyWrites#delete", + collection: nsidTyped, + rkey, + }); + newHashes.delete(key); + newBlobs.delete(key); + } + } + + if (upserts.length === 0 && deletes.length === 0) return; + + await this.#enqueueWrite(async () => { + const agent = this.#agent; + const did = this.#did.value; + const space = this.#spaceUri(); + if (!agent || !did || !space) return; + this.#writing++; + try { + for (const { rkey, value } of upserts) { + await agent.com.atproto.space.putRecord({ + space, + repo: did, + collection: nsidTyped, + rkey, + record: /** @type {Record} */ (value), + }); + } + for (let i = 0; i < deletes.length; i += 100) { + await agent.com.atproto.space.applyWrites({ + space, + repo: did, + writes: deletes.slice(i, i + 100), + }); + } + } finally { + this.#writing--; + } + }); + + lastHashes = newHashes; + lastBlobs = newBlobs; + }, + }; + } + + // HELPERS + + /** + * List the record values in a collection from the user's space. + * + * @template T + * @param {string} collection + * @returns {Promise} + */ + async #listRecords(collection) { + const agent = this.#agent; + const did = this.#did.value; + const space = this.#spaceUri(); + if (!agent || !did || !space) return /** @type {T[]} */ ([]); + + /** @type {T[]} */ + const records = []; + /** @type {string | undefined} */ + let cursor; + do { + const { data } = await agent.com.atproto.space.listRecords({ + space, + repo: did, + collection, + limit: 100, + cursor, + }); + for (const record of data.records) { + if (record.value !== undefined) { + records.push(/** @type {T} */ (record.value)); + } + } + cursor = data.cursor; + } while (cursor); + return records; + } + + /** + * @param {Uint8Array} bytes + * @returns {Promise} + */ + async #uploadBlob(bytes) { + const agent = this.#agent; + if (!agent) return undefined; + const { data } = await agent.com.atproto.repo.uploadBlob(bytes, { + encoding: "application/octet-stream", + }); + return data.blob; + } + + /** + * @param {string} cid + * @returns {Promise} + */ + async #fetchBlob(cid) { + const agent = this.#agent; + const did = this.#did.value; + const space = this.#spaceUri(); + if (!agent || !did || !space) return new Uint8Array(); + const { data } = await agent.com.atproto.space.getBlob({ + space, + repo: did, + cid, + }); + return data; + } + + // WRITE QUEUE + + /** + * @param {() => Promise} fn + * @returns {Promise} + */ + #enqueueWrite(fn) { + return new Promise((resolve, reject) => { + this.#writeQueue.push({ fn, resolve, reject }); + this.#drainWrites(); + }); + } + + async #drainWrites() { + if (this.#writeDraining) return; + this.#writeDraining = true; + + while (this.#writeQueue.length > 0) { + const { fn, resolve, reject } = + /** @type {{ fn: () => Promise, resolve: () => void, reject: (err: unknown) => void }} */ ( + this.#writeQueue.shift() + ); + try { + await fn(); + resolve(); + } catch (err) { + reject(err); + } + } + + this.#writeDraining = false; + } +} + +export default ATProtoSpaceOutput; + +//////////////////////////////////////////// +// REGISTER +//////////////////////////////////////////// + +export const CLASS = ATProtoSpaceOutput; +export const NAME = "dor-atproto-space"; + +defineElement(NAME, ATProtoSpaceOutput); diff --git a/src/components/output/raw/atproto-space/oauth-client-metadata.json b/src/components/output/raw/atproto-space/oauth-client-metadata.json new file mode 100644 index 00000000..7ea9b731 --- /dev/null +++ b/src/components/output/raw/atproto-space/oauth-client-metadata.json @@ -0,0 +1,12 @@ +{ + "client_id": "https://elements.diffuse.sh/latest/components/output/raw/atproto-space/oauth-client-metadata.json", + "client_name": "Diffuse", + "client_uri": "https://elements.diffuse.sh", + "redirect_uris": ["https://elements.diffuse.sh/oauth/callback"], + "scope": "atproto space:*?authority=self&skey=self&collection=*&action=read&action=create&action=update&action=delete&manage=create blob:application/octet-stream", + "grant_types": ["authorization_code", "refresh_token"], + "response_types": ["code"], + "token_endpoint_auth_method": "none", + "application_type": "web", + "dpop_bound_access_tokens": true +} diff --git a/src/components/output/raw/atproto-space/oauth.js b/src/components/output/raw/atproto-space/oauth.js new file mode 100644 index 00000000..1b055dbd --- /dev/null +++ b/src/components/output/raw/atproto-space/oauth.js @@ -0,0 +1,87 @@ +import { BrowserOAuthClient } from "@atproto/oauth-client-browser"; + +import metadata from "./oauth-client-metadata.json" with { + type: "json", +}; + +/** + * @import {OAuthSession} from "@atproto/oauth-client" + */ + +const SCOPE = metadata.scope; + +// Local development uses a loopback client id so the redirect lands back on the +// current origin (including the dev-server port). The loopback client id must +// carry the redirect target in its query string and have no path; the scope is +// passed later at sign-in. Otherwise prefer the per-component client id (e.g. +// the cimd-service development client) provided via the environment, falling +// back to the published client metadata. +const isLocalDev = location.origin.startsWith("http://127.0.0.1"); + +const redirect_uri = location.origin + location.pathname + location.search; + +const CLIENT_ID = isLocalDev + ? `http://localhost/?redirect_uri=${encodeURIComponent(redirect_uri)}&scope=${ + encodeURIComponent(SCOPE) + }` + : /** @type {any} */ (import.meta).env?.ATPROTO_SPACE_CLIENT_ID ?? + metadata.client_id; + +/** @type {Promise | null} */ +let clientPromise = null; + +/** + * Lazily create the browser OAuth client, configured with the space-aware + * client metadata. The client persists its session (DPoP keys, token set) in + * IndexedDB keyed by `client_id`. + */ +function client() { + // `load` derives the client metadata (including the default scope) from the + // published `client_id`, so no metadata is supplied here. A handle resolver + // is required so the client can resolve handles to DIDs; it mirrors the URL + // used by the other AT Protocol outputs. + clientPromise ??= BrowserOAuthClient.load({ + clientId: CLIENT_ID, + handleResolver: "https://public.api.bsky.app", + }); + + return clientPromise; +} + +// LOGIN +// ===== + +/** + * Initiate the OAuth authorization flow for a given handle. + * + * @param {string} handle + * @returns {Promise} + */ +export function login(handle) { + return client().then((c) => c.signIn(handle, { scope: SCOPE })); +} + +// SESSION RESTORE / CALLBACK +// ========================== + +/** + * Attempt to restore an existing session or finalize an OAuth callback. + * + * @returns {Promise} + */ +export async function restoreOrFinalize() { + const result = await (await client()).init(); + return result?.session ?? null; +} + +// LOGOUT +// ====== + +/** + * Sign out and revoke the current session. + * + * @param {OAuthSession} session + */ +export async function logout(session) { + await session.signOut(); +} diff --git a/src/components/transformer/output/bytes/dasl-sync/element.js b/src/components/transformer/output/bytes/dasl-sync/element.js index 6a0f0cd8..bd1ba5f3 100644 --- a/src/components/transformer/output/bytes/dasl-sync/element.js +++ b/src/components/transformer/output/bytes/dasl-sync/element.js @@ -57,9 +57,10 @@ class DaslBytesSyncOutputTransformer extends OutputTransformer { ); const isReady = signal(false); - const merging = signal({ isBusy: false, lastCID: "" }, { - compare: diff, - }); + const merging = signal( + { isBusy: false, lastCID: "", lastRemoteCID: "" }, + { compare: diff }, + ); this.effect(() => { if (!isReady.value) return; @@ -101,18 +102,42 @@ class DaslBytesSyncOutputTransformer extends OutputTransformer { } else if ( rs === "loaded" && this.hasDiverged({ local: l, remote: r }) ) { + // If we've already reconciled this exact (local, remote) pair and it + // made no progress (e.g. the remote write failed, or the merge + // resolved to the container we already hold), don't re-enter the + // merge. Re-merging here only toggles `merging`'s busy flag, which + // re-runs this effect and spins the reactive sync loop, freezing the + // page. Wait until local or remote actually changes before trying + // again. + const prev = merging.value; + if (prev.lastCID === (l.cid ?? "") && + prev.lastRemoteCID === (r.cid ?? "")) { + return; + } + // Async merge this.isLeader().then((isLeader) => { if (!isLeader) return; - merging.value = { isBusy: true, lastCID: merging.value.lastCID }; + merging.value = { + isBusy: true, + lastCID: prev.lastCID, + lastRemoteCID: prev.lastRemoteCID, + }; this.merge(l, r).then(async (c) => { + /** + * Remote cid after the (possible) push. Stays at the pre-merge + * remote cid when there's nothing to push or the push fails, so + * the effect-level guard above knows this reconcile was already + * attempted and won't retry it in a loop. + */ + let resolvedRemoteCID = r.cid ?? ""; + let reconciledCID = c.cid ?? ""; + try { container.value = c; - if (c.cid === merging.value.lastCID) return; - const bytes = this.save(c); if (c.cid !== l.cid) { @@ -121,13 +146,28 @@ class DaslBytesSyncOutputTransformer extends OutputTransformer { if (remote.ready() && rs === "loaded" && c.cid !== r.cid) { await saveRemote(bytes); + resolvedRemoteCID = c.cid ?? ""; } + } catch (err) { + console.error("Merge failed:", err); } finally { - merging.value = { isBusy: false, lastCID: c.cid ?? "" }; + merging.value = { + isBusy: false, + lastCID: reconciledCID, + lastRemoteCID: resolvedRemoteCID, + }; } }).catch((err) => { + // Merge() itself rejected (before producing a reconciled + // container). Reset the busy flag so the effect isn't stuck, and + // record the exact (local, remote) pair we attempted so a + // persistent failure is skipped rather than spinning forever. console.error("Merge failed:", err); - merging.value = { isBusy: false, lastCID: merging.value.lastCID }; + merging.value = { + isBusy: false, + lastCID: l.cid ?? "", + lastRemoteCID: r.cid ?? "", + }; }); }); } else { @@ -358,7 +398,18 @@ class DaslBytesSyncOutputTransformer extends OutputTransformer { continue; } - const isANewerThanB = itemA.updatedAt && itemB.updatedAt + const hasAUpdatedAt = Boolean(itemA.updatedAt); + const hasBUpdatedAt = Boolean(itemB.updatedAt); + + // The side that carries an `updatedAt` is the one that was edited, so + // it should win over a pristine copy that never recorded a change (e.g. + // a legacy seeded/starting-set facet persisted before it gained a + // timestamp). Only when both carry one do we compare clocks. + const isANewerThanB = (hasAUpdatedAt && !hasBUpdatedAt) + ? true + : (!hasAUpdatedAt && hasBUpdatedAt) + ? false + : hasAUpdatedAt && hasBUpdatedAt ? compareTimestamps(itemA.updatedAt, itemB.updatedAt) > 0 : false; diff --git a/src/components/transformer/output/raw/atproto-space-sync/element.js b/src/components/transformer/output/raw/atproto-space-sync/element.js new file mode 100644 index 00000000..d6cd579b --- /dev/null +++ b/src/components/transformer/output/raw/atproto-space-sync/element.js @@ -0,0 +1,438 @@ +import { ifDefined } from "lit-html/directives/if-defined.js"; + +import "~/components/output/polymorphic/indexed-db/element.js"; + +import { computed, signal } from "~/common/signal.js"; +import { OutputTransformer } from "../../base.js"; +import { defineElement } from "~/common/element.js"; +import * as Output from "~/common/output.js"; + +/** + * @import {OutputElement} from "@specs/components/output/types.d.ts" + */ + +const COLLECTIONS = /** @type {const} */ ([ + "facets", + "playlistItems", + "settings", + "tracks", +]); + +const STORAGE_PREFIX = "diffuse/transformer/output/raw/atproto-space-sync"; + +/** + * Wraps an AT Protocol space output with a local IndexedDB cache and keeps the + * two in sync via union merge by record `id` (using `updatedAt` as tiebreaker). + * + * Unlike the public AT Protocol sync transformer there is no firehose or + * revision check — spaces have neither a relay nor a simple `rev`, so we + * re-sync on remote-ready and on every save. + * + * @extends {OutputTransformer} + */ +class ATProtoSpaceOutputSyncTransformer extends OutputTransformer { + static NAME = "diffuse/transformer/output/raw/atproto-space-sync"; + + #localOutput = signal( + /** @type {OutputElement | undefined} */ (undefined), + ); + + #syncing = false; + + constructor() { + super(); + + const remote = this.base(); + const local = this.#localOutput.get; + + for (const name of COLLECTIONS) { + /** @ts-ignore */ + this[name] = { + collection: computed(() => { + const l = local(); + if (!l) return { state: "loading" }; + const c = l[name].collection(); + if (c.state === "loading") return c; + if (c.state === "error") return c; + return { state: "loaded", data: c.data ?? [] }; + }), + reload: async () => { + await this.#sync(); + }, + save: async (/** @type {any} */ newData) => { + const l = local(); + if (!l) return; + + console.log("[atproto-space-sync] save", name, { + count: Array.isArray(newData) ? newData.length : newData, + remoteReady: remote.ready(), + }); + + const newIds = new Set(newData.map((/** @type {any} */ r) => r.id)); + + // Update tombstones in one pass: add for records removed from local, + // remove for records being (re-)added so fixed-ID records can be + // recreated after deletion without the tombstone blocking them. + const tombstones = this.#getTombstones(name); + let tombstonesChanged = false; + + const existing = l[name].collection(); + const existingArr = + existing.state === "loaded" && Array.isArray(existing.data) + ? existing.data + : []; + + for (const record of existingArr) { + if (!newIds.has(record.id) && !tombstones.has(record.id)) { + tombstones.add(record.id); + tombstonesChanged = true; + } + } + + for (const record of newData) { + if (tombstones.has(record.id)) { + tombstones.delete(record.id); + tombstonesChanged = true; + } + } + + if (tombstonesChanged) { + localStorage.setItem( + `${STORAGE_PREFIX}/tombstones/${name}`, + JSON.stringify([...tombstones]), + ); + } + + this.#markDirty(); + await l[name].save(newData); + + if (remote.ready()) { + // Merge with any records added remotely since the last sync so we + // don't accidentally overwrite them with our local-only view. + const remoteCol = remote[name].collection(); + const dataForRemote = + remoteCol.state === "loaded" && Array.isArray(remoteCol.data) + ? this.#mergeRecords( + name, + newData, + /** @type {typeof newData} */ (remoteCol.data), + ) + : newData; + + remote[name].save(dataForRemote).then(() => { + this.#clearDirty(); + }).catch((err) => { + console.error(err); + }); + } + }, + }; + } + + this.ready = () => true; + + // Sync when the remote output becomes ready. + this.effect(() => { + const l = local(); + if (!l) return; + + this.effect(async () => { + if (!remote.ready()) return; + if (!(await this.isLeader())) return; + this.#sync(); + }); + }); + } + + // SYNC + + /** + * @param {readonly string[]} collections + */ + async #sync(collections = COLLECTIONS) { + if (this.#syncing) return; + this.#syncing = true; + + try { + const l = this.#localOutput.get(); + const remote = this.base(); + + if (!l || !remote.ready()) return; + + /** @type {Record} */ + const lAny = l; + /** @type {Record} */ + const remoteAny = remote; + + // Fetch remote data for the affected collections. + for (const name of collections) { + await remoteAny[name].reload(); + } + + // Await the local collections to settle, rather than reading a possibly + // still-"loading" local cache as empty. + const localCollections = await Promise.all( + collections.map((name) => Output.data(lAny[name])), + ); + + const localHasData = localCollections.some( + (data) => Array.isArray(data) && data.length > 0, + ); + + // Temporary diagnostics for the empty-dashboard bug. + console.log("[atproto-space-sync] #sync", { + ready: remote.ready(), + dirty: this.#isDirty(), + localHasData, + local: Object.fromEntries( + collections.map((name, i) => [ + name, + Array.isArray(localCollections[i]) + ? localCollections[i].length + : localCollections[i], + ]), + ), + remote: Object.fromEntries( + collections.map((name) => { + const c = remoteAny[name].collection(); + return [ + name, + c.state === "loaded" && Array.isArray(c.data) + ? c.data.length + : c.state, + ]; + }), + ), + }); + + if (!localHasData && !this.#isDirty()) { + // Local is empty and clean — just pull remote. + for (const name of collections) { + const remoteCol = remoteAny[name].collection(); + if ( + remoteCol.state === "loaded" && + Array.isArray(remoteCol.data) && + remoteCol.data.length > 0 + ) { + this.#trackIds(name, remoteCol.data); + await lAny[name].save(remoteCol.data); + } + } + } else { + // Union merge. + for (const name of collections) { + const localCol = lAny[name].collection(); + const remoteCol = remoteAny[name].collection(); + + const localArr = + localCol.state === "loaded" && Array.isArray(localCol.data) + ? localCol.data + : []; + const remoteArr = + remoteCol.state === "loaded" && Array.isArray(remoteCol.data) + ? remoteCol.data + : []; + + const merged = this.#mergeRecords(name, localArr, remoteArr); + + await lAny[name].save(merged); + + if (this.#differFromRemote(merged, remoteArr)) { + await remoteAny[name].save(merged); + } + + this.#trackIds(name, merged); + } + } + + this.#clearDirty(); + } catch (err) { + console.warn("Sync failed:", err); + } finally { + this.#syncing = false; + } + } + + /** + * Union merge two record arrays by `id`. + * + * - Records only in local → keep (unless tombstoned) + * - Records only in remote → keep (unless tombstoned) + * - Records in both → pick the one with the later `updatedAt`, local wins on + * missing/equal timestamps + * - Records whose id is in the tombstone set are excluded + * + * @template {Record & { id: string }} T + * @param {string} collection + * @param {T[]} localArr + * @param {T[]} remoteArr + * @returns {T[]} + */ + #mergeRecords(collection, localArr, remoteArr) { + const tombstones = this.#getTombstones(collection); + const knownIds = this.#getKnownIds(collection); + const remoteIds = new Set(remoteArr.map((r) => r.id)); + + /** @type {Map} */ + const merged = new Map(); + + // A space has no `rev`/firehose to distinguish "remote changed" from + // "remote never written to". An empty remote is therefore ambiguous: it + // could mean the space was just created, or a write failed silently — not + // that the user deleted everything remotely. Only trust the + // "deleted remotely" heuristic when the remote actually has records to + // compare against; otherwise keep local records and let them be pushed up. + const remoteAuthoritative = remoteArr.length > 0; + + for (const record of localArr) { + if (tombstones.has(record.id)) continue; + if ( + remoteAuthoritative && + knownIds.has(record.id) && + !remoteIds.has(record.id) + ) { + continue; + } + merged.set(record.id, record); + } + + for (const record of remoteArr) { + if (tombstones.has(record.id)) continue; + + // If this id was previously known but is absent from local, it may have + // been deleted locally. Only apply this heuristic when localArr is + // non-empty; an empty localArr could mean the cache was cleared rather + // than the user deleting everything. + if ( + localArr.length > 0 && + knownIds.has(record.id) && + !merged.has(record.id) + ) { + continue; + } + + const existing = merged.get(record.id); + + if (!existing) { + merged.set(record.id, record); + } else { + const lt = existing.updatedAt; + const rt = record.updatedAt; + if (lt && rt && rt > lt) { + merged.set(record.id, record); + } + } + } + + return [...merged.values()]; + } + + /** + * @param {Array<{ id: string, updatedAt?: string }>} merged + * @param {Array<{ id: string, updatedAt?: string }>} remote + * @returns {boolean} + */ + #differFromRemote(merged, remote) { + if (merged.length !== remote.length) return true; + const remoteMap = new Map(remote.map((r) => [r.id, r.updatedAt])); + return merged.some((r) => remoteMap.get(r.id) !== r.updatedAt); + } + + // DIRTY FLAG + + #markDirty() { + localStorage.setItem(`${STORAGE_PREFIX}/dirty`, "1"); + } + + #clearDirty() { + localStorage.removeItem(`${STORAGE_PREFIX}/dirty`); + } + + /** @returns {boolean} */ + #isDirty() { + return localStorage.getItem(`${STORAGE_PREFIX}/dirty`) === "1"; + } + + // TOMBSTONES & KNOWN IDS + + /** + * @param {string} collection + * @returns {Set} + */ + #getTombstones(collection) { + const raw = localStorage.getItem( + `${STORAGE_PREFIX}/tombstones/${collection}`, + ); + return raw ? new Set(JSON.parse(raw)) : new Set(); + } + + /** + * @param {string} collection + * @returns {Set} + */ + #getKnownIds(collection) { + const raw = localStorage.getItem(`${STORAGE_PREFIX}/known/${collection}`); + return raw ? new Set(JSON.parse(raw)) : new Set(); + } + + /** + * Record all ids from a data array as known. + * + * @param {string} collection + * @param {Array<{ id: string }>} data + */ + #trackIds(collection, data) { + const known = this.#getKnownIds(collection); + for (const record of data) { + known.add(record.id); + } + localStorage.setItem( + `${STORAGE_PREFIX}/known/${collection}`, + JSON.stringify([...known]), + ); + } + + // LIFECYCLE + + /** @override */ + connectedCallback() { + if (this.hasAttribute("group")) { + this.broadcast(this.identifier, {}); + } + + super.connectedCallback(); + + /** @type {OutputElement | null} */ + const local = this.root().querySelector("dop-indexed-db"); + if (!local) throw new Error("Can't find local output"); + + customElements.whenDefined(local.localName).then(() => { + this.#localOutput.value = local; + }); + } + + // RENDER + + /** + * @param {import("~/common/element.d.ts").RenderArg} _ + */ + render({ html }) { + return html` + + `; + } +} + +export default ATProtoSpaceOutputSyncTransformer; + +//////////////////////////////////////////// +// REGISTER +//////////////////////////////////////////// + +export const CLASS = ATProtoSpaceOutputSyncTransformer; +export const NAME = "dtor-atproto-space-sync"; + +defineElement(NAME, CLASS); diff --git a/src/components/transformer/output/refiner/initial-contents/element.js b/src/components/transformer/output/refiner/initial-contents/element.js index 69286d8d..9ddd7df7 100644 --- a/src/components/transformer/output/refiner/initial-contents/element.js +++ b/src/components/transformer/output/refiner/initial-contents/element.js @@ -1,6 +1,4 @@ -import * as IDB from "idb-keyval"; - -import { batch, computed, signal, untracked } from "~/common/signal.js"; +import { computed } from "~/common/signal.js"; import { OutputTransformer } from "../../base.js"; import { defineElement } from "~/common/element.js"; @@ -11,9 +9,16 @@ import { buildFacets } from "~/common/facets/utils.js"; /** * @import {OutputManagerDeputy} from "@specs/components/output/types.d.ts" + * @import {OutputConfiguratorElement} from "@specs/components/configurator/output/types.d.ts" */ -const IDB_KEY = +// Per-output "initialized" flag. Stored in localStorage keyed by the output id +// so it is scoped per bucket/output, but deliberately kept OUT of the output's +// own data: writing into a syncing output's collections (e.g. Dropbox via +// dtob-dasl-sync) flows through its merge/sync pipeline, which is reactive +// feedback that loops and freezes the page. localStorage is local-only control +// state, so it's safe. +const STORAGE_KEY = "diffuse/transformer/output/refiner/initial-contents/initialized"; //////////////////////////////////////////// @@ -26,21 +31,17 @@ const IDB_KEY = class InitialContentsTransformer extends OutputTransformer { static NAME = "diffuse/transformer/output/refiner/initial-contents"; - #flagLoaded = signal(false); - #initialized = signal(false); - constructor() { super(); const base = this.base(); - // Load flag from IDB; gate collection() until resolved to prevent - // a flash of defaults for a user who has previously cleared their collection. - IDB.get(IDB_KEY).then((v) => { - batch(() => { - this.#initialized.value = !!v; - this.#flagLoaded.value = true; - }); + // Mark initialized the first time real (non-empty) data is observed, + // covering data arriving from another device via sync. + this.effect(() => { + const col = base.facets.collection(); + if (col.state !== "loaded" || col.data.length === 0) return; + this.#markInitialized(); }); /** @type {OutputManagerDeputy} */ @@ -48,27 +49,14 @@ class InitialContentsTransformer extends OutputTransformer { facets: { ...base.facets, collection: computed(() => { - if (!this.#flagLoaded.get()) return { state: "loading" }; - const col = base.facets.collection(); if (col.state !== "loaded") return col; if (col.data.length > 0) { - // Set the flag the first time we observe non-empty data. - // Covers data arriving from another device via sync. - // untracked read avoids a circular dependency; the write still - // notifies subscribers and queues a re-evaluation. - if (!untracked(() => this.#initialized.value)) { - this.#initialized.value = true; - IDB.set(IDB_KEY, true); // fire-and-forget - } - return { state: "loaded", data: col.data }; } - // Tracked read: keeps the computed subscribed to #initialized - // so it re-runs if save() sets it to true with an empty array. - if (this.#initialized.get()) { + if (this.#isInitialized()) { return { state: "loaded", data: col.data }; } @@ -77,14 +65,11 @@ class InitialContentsTransformer extends OutputTransformer { }), save: async (newFacets) => { - // Set the flag on any explicit save (covers the case where the - // user's first action is removing a default from the list). - if (!this.#initialized.value) { - this.#initialized.value = true; - IDB.set(IDB_KEY, true); // fire-and-forget - } - + // Persist the facets first so the resulting (non-empty) data is + // visible before the initialized flag flips, avoiding a flash of + // the empty collection while a fresh output pops its starting set. await base.facets.save(newFacets); + this.#markInitialized(); }, }, @@ -100,6 +85,53 @@ class InitialContentsTransformer extends OutputTransformer { this.tracks = manager.tracks; this.ready = manager.ready; } + + // METHODS + + /** + * The id of the currently selected output, or "local" when no custom + * output is selected (data lives in the default/local storage). + */ + #selectedId() { + const output = /** @type {OutputConfiguratorElement | undefined} */ ( + this.output.signal() + ); + return output?.selected()?.id ?? "local"; + } + + /** + * Whether the current output is initialized. + * @returns {boolean} + */ + #isInitialized() { + const id = this.#selectedId(); + try { + const map = /** @type {Record} */ ( + JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "{}") + ); + return !!map?.[id]; + } catch { + return false; + } + } + + /** + * Mark the current output as initialized by updating its flag in the + * in-memory map and persisting to localStorage. + */ + #markInitialized() { + const id = this.#selectedId(); + let map = /** @type {Record} */ ({}); + try { + map = /** @type {Record} */ ( + JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "{}") + ) ?? {}; + } catch {} + if (map[id]) return; + + map[id] = true; + localStorage.setItem(STORAGE_KEY, JSON.stringify(map)); + } } export default InitialContentsTransformer; @@ -111,4 +143,4 @@ export default InitialContentsTransformer; export const CLASS = InitialContentsTransformer; export const NAME = "dtor-initial-contents"; -defineElement(NAME, CLASS); +defineElement(NAME, CLASS); \ No newline at end of file diff --git a/src/facets/connect/atproto-passkey/index.inline.js b/src/facets/connect/atproto-passkey/index.inline.js index 34c5c305..763df98a 100644 --- a/src/facets/connect/atproto-passkey/index.inline.js +++ b/src/facets/connect/atproto-passkey/index.inline.js @@ -5,7 +5,7 @@ import { NAME as PASSKEY_NAME } from "~/components/transformer/output/refiner/pa import { effect, signal } from "~/common/signal.js"; import foundation from "~/common/foundation.js"; -import { setup } from "~/facets/connect/common.js"; +import { setup, waitForOutputOption } from "~/facets/connect/common.js"; foundation.setup({ title: "Connect Atmosphere | Diffuse" }); @@ -23,14 +23,7 @@ const outputOrchestrator = await foundation.orchestrator.output(); await customElements.whenDefined(outputOrchestrator.localName); await customElements.whenDefined(ATPROTO_PASSKEY_NAME); -const atprotoOption = (await outputOrchestrator.options()).find( - (o) => o.label === "AT Protocol", -); - -if (!atprotoOption) { - throw new Error("AT Protocol output was not enabled!"); -} - +const atprotoOption = await waitForOutputOption(outputOrchestrator, "AT Protocol"); const ATPROTO_PASSKEY_OUTPUT_ID = atprotoOption.id; const atprotoEl = /** @type {ATProtoPasskeyOutputElement | undefined} */ ( diff --git a/src/facets/connect/atproto-space/index.html b/src/facets/connect/atproto-space/index.html new file mode 100644 index 00000000..cdcd04bf --- /dev/null +++ b/src/facets/connect/atproto-space/index.html @@ -0,0 +1,12 @@ + + +
+ + diff --git a/src/facets/connect/atproto-space/index.inline.js b/src/facets/connect/atproto-space/index.inline.js new file mode 100644 index 00000000..b869bf0f --- /dev/null +++ b/src/facets/connect/atproto-space/index.inline.js @@ -0,0 +1,140 @@ +import { html, render as litRender } from "lit-html"; + +import { NAME as ATPROTO_SPACE_NAME } from "~/components/output/raw/atproto-space/element.js"; +import { effect } from "~/common/signal.js"; +import foundation from "~/common/foundation.js"; + +import { setup, waitForOutputOption } from "~/facets/connect/common.js"; + +foundation.setup({ title: "Connect Atmosphere Spaces | Diffuse" }); + +/** + * @import { ATProtoSpaceOutputElement } from "@specs/components/output/raw/atproto-space/types.d.ts" + */ + +//////////////////////////////////////////// +// SETUP +//////////////////////////////////////////// + +const outputOrchestrator = await foundation.orchestrator.output(); + +await customElements.whenDefined(outputOrchestrator.localName); +await customElements.whenDefined(ATPROTO_SPACE_NAME); + +const atprotoOption = await waitForOutputOption(outputOrchestrator, "AT Protocol Space"); +const ATPROTO_SPACE_OUTPUT_ID = atprotoOption.id; + +const atprotoEl = /** @type {ATProtoSpaceOutputElement | undefined} */ ( + outputOrchestrator.root().querySelector(ATPROTO_SPACE_NAME) +); + +//////////////////////////////////////////// +// OAUTH CALLBACK LOADING STATE +//////////////////////////////////////////// + +if (true) { + litRender( + html` +
+
+

+ + Connecting to the Atmosphere +

+
+ `, + /** @type {HTMLElement} */ (document.querySelector("main")), + ); + + await atprotoEl?.whenRestored(); +} + +// The output configurator can't find custom outputs (added by the +// output-bundle prelude) during its initial connectedCallback, so it +// re-loads the selected output via `loadSelected()` which is async. +if (outputOrchestrator.hasSelected() && !outputOrchestrator.selected()) { + await new Promise((resolve) => { + const stop = effect(() => { + if (outputOrchestrator.selected()) { + stop(); + resolve(undefined); + } + }); + }); +} + +//////////////////////////////////////////// +// UI +//////////////////////////////////////////// + +const { setItems } = setup({ + title: "Atmosphere (Space)", + hasInput: false, + + description: html` +

+ Use your AT Protocol account for user-data storage. Your data is stored in your own repo and is not broadcast publicly. +

+ `, + + formFields: html` + + `, + + onSubmit: (_mode) => connect(), + + onOutputActivate: async () => { + await outputOrchestrator.select(ATPROTO_SPACE_OUTPUT_ID); + }, +}); + +const handleInput = + /** @type {HTMLInputElement} */ (document.querySelector("#atproto-space-handle")); + +//////////////////////////////////////////// +// REACTIVE LIST +//////////////////////////////////////////// + +effect(() => { + const did = atprotoEl?.did(); + const isSelectedOutput = + outputOrchestrator.selected()?.id === ATPROTO_SPACE_OUTPUT_ID; + + setItems( + did + ? [ + { + name: did, + detail: "AT Protocol space", + isInput: false, + isOutput: true, + isSelectedOutput, + onRemove: () => disconnect(), + }, + ] + : [], + ); +}); + +//////////////////////////////////////////// +// ACTIONS +//////////////////////////////////////////// + +async function connect() { + const handle = handleInput.value?.trim(); + if (!handle) return; + + await outputOrchestrator.select(ATPROTO_SPACE_OUTPUT_ID); + await atprotoEl?.login(handle); +} + +async function disconnect() { + await outputOrchestrator.deselect(); + await atprotoEl?.logout(); +} + +//////////////////////////////////////////// +// 🚀 +//////////////////////////////////////////// + +foundation.ready(); diff --git a/src/facets/connect/common.js b/src/facets/connect/common.js index 741fd463..9d4a7734 100644 --- a/src/facets/connect/common.js +++ b/src/facets/connect/common.js @@ -9,6 +9,44 @@ import { html, nothing, render as litRender } from "lit-html"; * @typedef {{ name: string; detail: string; isInput: boolean; isOutput: boolean; isSelectedOutput: boolean; isDisabled?: boolean; onShowQR?: () => void; onRemove: () => void; onToggleDisabled?: () => void }} ConnectItem */ +/** + * @param {string} label + */ +function outputErrorMessage(label) { + return `${label} output was not enabled!`; +} + +/** + * Wait for an output option to be registered, failing after a timeout + * instead of waiting indefinitely. The option is added by the output-bundle + * prelude once it is loaded, so it may not exist yet when a connect page + * first asks for it. + * + * @param {{ waitForOption: (label: string) => Promise<{ id: string }> }} outputOrchestrator + * @param {string} label + * @param {number} [timeoutMs=30_000] + * @returns {Promise<{ id: string }>} + */ +export async function waitForOutputOption( + outputOrchestrator, + label, + timeoutMs = 30_000, +) { + let timer; + const timeout = new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error(outputErrorMessage(label))), + timeoutMs, + ); + }); + + try { + return await Promise.race([outputOrchestrator.waitForOption(label), timeout]); + } finally { + clearTimeout(timer); + } +} + /** * Sets up a connect facet UI: a card with "Add audio input" and * "Use as userdata storage" buttons, a dialog with a form, and a diff --git a/src/facets/connect/dropbox/index.inline.js b/src/facets/connect/dropbox/index.inline.js index abb19495..75f213a2 100644 --- a/src/facets/connect/dropbox/index.inline.js +++ b/src/facets/connect/dropbox/index.inline.js @@ -11,7 +11,7 @@ import { NAME as DROPBOX_OUTPUT_NAME } from "~/components/output/bytes/dropbox/e import { effect } from "~/common/signal.js"; import foundation from "~/common/foundation.js"; -import { setup } from "~/facets/connect/common.js"; +import { setup, waitForOutputOption } from "~/facets/connect/common.js"; foundation.setup({ title: "Connect Dropbox | Diffuse" }); @@ -36,14 +36,7 @@ await Promise.all([ customElements.whenDefined(sourcesOrchestrator.localName), ]); -const dropboxOption = (await outputOrchestrator.options()).find( - (o) => o.label === "Dropbox", -); - -if (!dropboxOption) { - throw new Error("Dropbox output was not enabled!"); -} - +const dropboxOption = await waitForOutputOption(outputOrchestrator, "Dropbox"); const OUTPUT_DROPBOX_ID = dropboxOption.id; /** Look up the Dropbox output element, which may not exist yet. */ diff --git a/src/facets/connect/index.inline.js b/src/facets/connect/index.inline.js index 62669465..5816faa4 100644 --- a/src/facets/connect/index.inline.js +++ b/src/facets/connect/index.inline.js @@ -11,6 +11,7 @@ const loaderHref = (path) => `l/?path=${encodeURIComponent(path)}`; /** @type {Record} */ const icons = { "facets/connect/atproto-passkey/index.html": "at", + "facets/connect/atproto-space/index.html": "at", "facets/connect/dropbox/index.html": "cloud", "facets/connect/https/index.html": "globe", "facets/connect/https-json/index.html": "list-bullets", diff --git a/src/facets/connect/s3/index.inline.js b/src/facets/connect/s3/index.inline.js index 70eab451..60153ef6 100644 --- a/src/facets/connect/s3/index.inline.js +++ b/src/facets/connect/s3/index.inline.js @@ -9,7 +9,7 @@ import { bucketId, buildURI, parseURI } from "~/components/input/s3/common.js"; import { effect } from "~/common/signal.js"; import foundation from "~/common/foundation.js"; -import { setup } from "~/facets/connect/common.js"; +import { setup, waitForOutputOption } from "~/facets/connect/common.js"; foundation.setup({ title: "Connect S3 | Diffuse" }); @@ -35,19 +35,12 @@ await Promise.all([ customElements.whenDefined(sourcesOrchestrator.localName), ]); -const s3Option = (await outputOrchestrator.options()).find( - (o) => o.label === "S3", -); - const s3El = /** @type {S3OutputElement | undefined} */ ( outputOrchestrator.root().querySelector(S3_NAME) ); -if (!s3Option) { - throw new Error("S3 output was not enabled!"); -} - -const OUTPUT_S3_ID = s3Option?.id; +const s3Option = await waitForOutputOption(outputOrchestrator, "S3"); +const OUTPUT_S3_ID = s3Option.id; //////////////////////////////////////////// // CAMERA SCAN diff --git a/src/facets/data/output-bundle/index.inline.js b/src/facets/data/output-bundle/index.inline.js index f62f3047..d3c57e8f 100644 --- a/src/facets/data/output-bundle/index.inline.js +++ b/src/facets/data/output-bundle/index.inline.js @@ -5,6 +5,9 @@ import { NAME as ATPROTO_OUTPUT_NAME } from "~/components/output/raw/atproto-pas import { NAME as ATPROTO_SYNC_NAME } from "~/components/transformer/output/raw/atproto-sync/element.js"; import { NAME as ATPROTO_PASSKEY_NAME } from "~/components/transformer/output/refiner/passkey-encryption/element.js"; +import { NAME as ATPROTO_SPACE_OUTPUT_NAME } from "~/components/output/raw/atproto-space/element.js"; +import { NAME as ATPROTO_SPACE_SYNC_NAME } from "~/components/transformer/output/raw/atproto-space-sync/element.js"; + import { NAME as S3_OUTPUT_NAME } from "~/components/output/bytes/s3/element.js"; import { NAME as DROPBOX_OUTPUT_NAME } from "~/components/output/bytes/dropbox/element.js"; import { NAME as S3_SYNC_NAME } from "~/components/transformer/output/bytes/dasl-sync/element.js"; @@ -25,6 +28,7 @@ effect(() => { if (!output) return; atprotoPasskey(output); + atprotoSpace(output); s3(output); dropbox(output); @@ -47,6 +51,8 @@ effect(() => { switch (id) { case "do-output__dc-output__atproto-passkey": return atprotoPasskeyCustomElements(); + case "do-output__dc-output__atproto-space": + return atprotoSpaceCustomElements(); case "do-output__dc-output__s3": return s3CustomElements(); case "do-output__dc-output__dropbox": @@ -103,6 +109,43 @@ export function atprotoPasskeyCustomElements() { ); } +//////////////////////////////////////////// +// AT PROTOCOL (SPACES) +//////////////////////////////////////////// + +/** + * Exposes the AT Protocol space output as a user-data storage option. + * + * Unlike the public AT Protocol output there is no firehose-based sync or + * passkey encryption. The raw space output is wrapped with a local-first sync + * transformer (IndexedDB cache + union merge) so data — including the default + * facets — is persisted and synced with the space. + * + * @param {OutputOrchestrator} output + */ +export function atprotoSpace(output) { + const out = document.createElement(ATPROTO_SPACE_OUTPUT_NAME); + out.setAttribute("group", foundation.GROUP); + out.setAttribute("id", "do-output__dor-atproto-space"); + + const sync = document.createElement(ATPROTO_SPACE_SYNC_NAME); + sync.setAttribute("group", foundation.GROUP); + sync.setAttribute("id", "do-output__dc-output__atproto-space"); + sync.setAttribute("label", "AT Protocol Space"); + sync.setAttribute("namespace", "atproto-space"); + sync.setAttribute("output-selector", "#do-output__dor-atproto-space"); + + output.append(out); + output.outputConfigurator.append(sync); +} + +export function atprotoSpaceCustomElements() { + import("~/components/output/raw/atproto-space/element.js"); + import( + "~/components/transformer/output/raw/atproto-space-sync/element.js" + ); +} + //////////////////////////////////////////// // S3 //////////////////////////////////////////// diff --git a/tasks/publish-lexicons.js b/tasks/publish-lexicons.js new file mode 100644 index 00000000..016b6c08 --- /dev/null +++ b/tasks/publish-lexicons.js @@ -0,0 +1,84 @@ +// Publishes the Diffuse lexicons (including the `sh.diffuse.atproto.space` +// space declaration) as `com.atproto.lexicon.schema` records on an atproto PDS. +// +// This mirrors the atproto reference app's lexicon-publishing step. Note that a +// `space:` scope only resolves if the PDS's lexicon authority resolves the +// `sh.diffuse.*` namespace from the target account's DID. +// +// Usage: +// deno run -A tasks/publish-lexicons.js \ +// https://spaces-alpha.host.bsky.network \ +// toko.spaces-alpha.bsky.network \ +// "" + +const LEXICON_COLLECTION = "com.atproto.lexicon.schema"; + +const [pds, handle, password] = Deno.args; + +if (!pds || !handle || !password) { + console.error( + "Usage: deno run -A tasks/publish-lexicons.js ", + ); + Deno.exit(1); +} + +/** Recursively collect lexicon JSON files under a directory. */ +async function collect(dir) { + const out = []; + + for await (const entry of Deno.readDir(dir)) { + const path = `${dir}/${entry.name}`; + + if (entry.isDirectory) { + out.push(...(await collect(path))); + } else if (entry.isFile && entry.name.endsWith(".json")) { + out.push(path); + } + } + + return out; +} + +async function xrpc(method, init) { + const res = await fetch(`${pds}/xrpc/${method}`, init); + const text = await res.text(); + + if (!res.ok) { + throw new Error(`${method} failed (${res.status}): ${text.slice(0, 400)}`); + } + + try { + return JSON.parse(text); + } catch { + return text; + } +} + +const login = await xrpc("com.atproto.server.createSession", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ identifier: handle, password }), +}); + +const accessJwt = /** @type {string} */ (login.accessJwt); +const did = /** @type {string} */ (login.did); + +for (const file of await collect("lexicons")) { + const doc = JSON.parse(await Deno.readTextFile(file)); + + await xrpc("com.atproto.repo.putRecord", { + method: "POST", + headers: { + authorization: `Bearer ${accessJwt}`, + "content-type": "application/json", + }, + body: JSON.stringify({ + repo: did, + collection: LEXICON_COLLECTION, + rkey: doc.id, + record: doc, + }), + }); + + console.log(`published: ${doc.id}`); +} diff --git a/tests/components/transformer/output/bytes/dasl-sync/test.ts b/tests/components/transformer/output/bytes/dasl-sync/test.ts index 3e76c343..28158725 100644 --- a/tests/components/transformer/output/bytes/dasl-sync/test.ts +++ b/tests/components/transformer/output/bytes/dasl-sync/test.ts @@ -329,6 +329,37 @@ describe("components/transformer/output/bytes/dasl-sync", () => { expect(result).toBe("New"); }); + it("prefers the edited side over a timestamp-less pristine copy", async () => { + // Regression: a facet that was just edited gets an `updatedAt`, but a + // pristine seeded/starting-set copy may carry none. Previously the merge + // treated the timestamp-less side as "newest" and re-applied the stale + // value, silently reverting dashboard toggles for starting-set items. + const result = await testWeb(async () => { + const { CLASS } = await import( + "~/components/transformer/output/bytes/dasl-sync/element.js" + ); + const el = new CLASS(); + const edited = { id: "a", enabled: false, updatedAt: "2024-06-01T00:00:00.000Z", name: "Edited" }; + const pristine = { id: "a", enabled: true, name: "Pristine" }; + const containerA = { + cid: "cid-a", + data: [edited], + inventory: { current: { a: "cid-edited" }, removed: [] }, + } as never; + const containerB = { + cid: "cid-b", + data: [pristine], + inventory: { current: { a: "cid-pristine" }, removed: [] }, + } as never; + const merged = await el.merge(containerA, containerB); + const first = merged.data[0] as unknown as { enabled: boolean } | undefined; + return { enabled: first?.enabled }; + }); + + // The side carrying `updatedAt` (the edit) should win. + expect(result.enabled).toBe(false); + }); + it("keeps identical items without recomputing their CIDs", async () => { const result = await testWeb(async () => { const { CLASS } = await import(