@getcirrus/spaces 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,684 @@
1
+ import { DurableObject } from "cloudflare:workers";
2
+ import { SignedCommit } from "@atproto/space";
3
+ import { Context, Hono } from "hono";
4
+ import { Keypair } from "@atproto/crypto";
5
+
6
+ //#region src/types.d.ts
7
+ /** A write prepared by the Worker: validated, CBOR-encoded, CID computed. */
8
+ type PreparedSpaceWrite = {
9
+ action: "create" | "update";
10
+ collection: string;
11
+ rkey: string;
12
+ cid: string;
13
+ bytes: Uint8Array;
14
+ /** Blob CIDs referenced by the record. */
15
+ blobCids: string[];
16
+ } | {
17
+ action: "delete";
18
+ collection: string;
19
+ rkey: string;
20
+ };
21
+ interface ApplyWritesResult {
22
+ rev: string;
23
+ /** sha256 digest of the LtHash state after the batch. */
24
+ hash: Uint8Array;
25
+ results: Array<{
26
+ action: "create" | "update" | "delete";
27
+ collection: string;
28
+ rkey: string;
29
+ cid: string | null;
30
+ }>;
31
+ }
32
+ interface SpaceMeta {
33
+ uri: string;
34
+ authority: string;
35
+ type: string;
36
+ skey: string;
37
+ isAuthority: boolean;
38
+ createdAt: string;
39
+ deletedAt: string | null;
40
+ }
41
+ type SpacePolicy = {
42
+ kind: "public";
43
+ } | {
44
+ kind: "member-list";
45
+ } | {
46
+ kind: "managing-app";
47
+ managingApp: string;
48
+ };
49
+ type SpaceAppAccess = {
50
+ kind: "open";
51
+ } | {
52
+ kind: "allowList";
53
+ allowed: string[];
54
+ };
55
+ interface SpaceConfig {
56
+ policy: SpacePolicy;
57
+ appAccess: SpaceAppAccess;
58
+ }
59
+ interface RepoState {
60
+ setHash: Uint8Array;
61
+ rev: string;
62
+ }
63
+ interface SpaceRecordRow {
64
+ collection: string;
65
+ rkey: string;
66
+ cid: string;
67
+ bytes?: Uint8Array;
68
+ }
69
+ interface OplogEntry {
70
+ rev: string;
71
+ idx: number;
72
+ collection: string;
73
+ rkey: string;
74
+ cid: string | null;
75
+ prev: string | null;
76
+ /** Current record bytes for creates/updates that are not stale. */
77
+ bytes?: Uint8Array;
78
+ }
79
+ interface NotifyItem {
80
+ service: string;
81
+ endpoint: string;
82
+ lxm: string;
83
+ body: Record<string, unknown>;
84
+ }
85
+ /**
86
+ * Host configuration for the space engine's Durable Objects. Supplied by
87
+ * the host Worker's subclass — the engine never reads env vars itself, so
88
+ * the same class can later serve a dedicated authority DID with no account
89
+ * attached.
90
+ */
91
+ interface SpaceHostConfig {
92
+ /** The DID whose permissioned repos this engine serves. */
93
+ operatorDid: string;
94
+ /** Signing keypair provider (service JWTs for notification fan-out). */
95
+ getKeypair(): Promise<Keypair>;
96
+ }
97
+ //#endregion
98
+ //#region src/space-do.d.ts
99
+
100
+ declare abstract class SpaceDurableObject<Env = unknown> extends DurableObject<Env> {
101
+ private sql;
102
+ private initialized;
103
+ private outdated;
104
+ constructor(ctx: DurableObjectState, env: Env);
105
+ /**
106
+ * Host identity and signing configuration. Implemented by the host
107
+ * Worker's subclass; see {@link SpaceHostConfig}.
108
+ */
109
+ protected abstract getHostConfig(): SpaceHostConfig | Promise<SpaceHostConfig>;
110
+ private ensureInitialized;
111
+ /**
112
+ * Gate every RPC: initialise storage and refuse when the stored schema
113
+ * belongs to a different alpha build.
114
+ */
115
+ private ensureOpen;
116
+ private readMeta;
117
+ /** Meta for an existing, non-deleted space, or throw. */
118
+ private requireLiveMeta;
119
+ rpcGetMeta(): Promise<SpaceMeta | null>;
120
+ /**
121
+ * Initialise this DO as the operator's repo in a space (either role).
122
+ * Idempotent for an existing live space with matching identity.
123
+ */
124
+ rpcInit(params: {
125
+ uri: string;
126
+ authority: string;
127
+ type: string;
128
+ skey: string;
129
+ isAuthority: boolean;
130
+ config?: SpaceConfig;
131
+ }): Promise<void>;
132
+ rpcApplyWrites(writes: PreparedSpaceWrite[]): Promise<ApplyWritesResult>;
133
+ private appendOplog;
134
+ rpcGetRecord(collection: string, rkey: string): Promise<{
135
+ cid: string;
136
+ bytes: Uint8Array;
137
+ } | null>;
138
+ /**
139
+ * List records ordered by (collection, rkey) — equivalent to record-URI
140
+ * order since every record shares the space and repo prefix. Descending
141
+ * by default, matching the reference; `reverse` flips to ascending.
142
+ *
143
+ * `rev` is the repo revision the page was read at — the page and the
144
+ * revision are one snapshot (synchronous reads, single-threaded DO), so
145
+ * a paged reader can fence against concurrent writes.
146
+ */
147
+ rpcListRecords(params: {
148
+ collection?: string;
149
+ limit: number;
150
+ after?: {
151
+ collection: string;
152
+ rkey: string;
153
+ };
154
+ reverse?: boolean;
155
+ excludeValues?: boolean;
156
+ }): Promise<{
157
+ records: SpaceRecordRow[];
158
+ hasMore: boolean;
159
+ rev: string | null;
160
+ }>;
161
+ rpcGetRepoState(): Promise<RepoState | null>;
162
+ /**
163
+ * List oplog entries after `since` (a rev) or `after` (an exact cursor
164
+ * position). Creates and updates carry the record's current bytes when
165
+ * the oplog cid still matches the live record; superseded values are
166
+ * omitted. When the page reaches the head, `head` carries the repo
167
+ * state read in the same transaction so the Worker can attach a freshly
168
+ * signed commit without a state race.
169
+ */
170
+ rpcListRepoOps(params: {
171
+ since?: string;
172
+ after?: {
173
+ rev: string;
174
+ idx: number;
175
+ };
176
+ limit: number;
177
+ excludeValues?: boolean;
178
+ }): Promise<{
179
+ ops: OplogEntry[];
180
+ head?: RepoState;
181
+ }>;
182
+ /** Distinct blob CIDs referenced by records, ascending, paged. */
183
+ rpcListBlobs(params: {
184
+ since?: string;
185
+ limit: number;
186
+ afterCid?: string;
187
+ }): Promise<{
188
+ cids: string[];
189
+ hasMore: boolean;
190
+ }>;
191
+ /** Whether a blob CID is referenced by any record in this space. */
192
+ rpcHasSpaceBlob(cid: string): Promise<boolean>;
193
+ /**
194
+ * Record a single-use key. Returns true when the key was fresh (now
195
+ * recorded), false when it was already seen and must be refused.
196
+ */
197
+ rpcCheckReplay(kind: string, key: string, expiresAtSec: number): Promise<boolean>;
198
+ private writeConfig;
199
+ private readConfig;
200
+ /**
201
+ * State needed to answer getSpaceCredential: meta (including the
202
+ * deletion tombstone) and the simplespace config. Never throws on a
203
+ * deleted space — a late credential request must get SpaceDeleted, not
204
+ * SpaceNotFound, and that mapping is the caller's.
205
+ */
206
+ rpcGetAuthorityState(): Promise<{
207
+ meta: SpaceMeta | null;
208
+ config: SpaceConfig | null;
209
+ }>;
210
+ rpcUpdateConfig(update: {
211
+ policy?: SpacePolicy;
212
+ appAccess?: SpaceAppAccess;
213
+ }): Promise<void>;
214
+ rpcAddMember(did: string): Promise<void>;
215
+ rpcRemoveMember(did: string): Promise<void>;
216
+ rpcIsMember(did: string): Promise<boolean>;
217
+ rpcListMembers(params: {
218
+ limit: number;
219
+ afterDid?: string;
220
+ }): Promise<{
221
+ dids: string[];
222
+ hasMore: boolean;
223
+ }>;
224
+ /**
225
+ * Record a writer's latest (rev, hash), from notifyWrite or own writes.
226
+ * Monotonic per writer: a delayed or replayed notification with an older
227
+ * rev never rolls the writer set backwards. Returns whether the write
228
+ * advanced state, so callers can skip fan-out for stale notifications.
229
+ */
230
+ rpcRecordWriter(did: string, rev: string, hash: Uint8Array): Promise<{
231
+ advanced: boolean;
232
+ }>;
233
+ rpcListWriters(params: {
234
+ limit: number;
235
+ afterDid?: string;
236
+ }): Promise<{
237
+ repos: Array<{
238
+ did: string;
239
+ rev: string;
240
+ hash: Uint8Array;
241
+ }>;
242
+ hasMore: boolean;
243
+ }>;
244
+ /**
245
+ * Register a syncing service for write notifications. The endpoint was
246
+ * resolved by the Worker at registration time so fan-out never resolves
247
+ * DIDs. Re-registration replaces the endpoint and extends the expiry.
248
+ */
249
+ rpcRegisterNotify(service: string, endpoint: string): Promise<{
250
+ expiresAt: string;
251
+ }>;
252
+ /** Idempotent: succeeds whether or not a registration existed. */
253
+ rpcUnregisterNotify(service: string): Promise<void>;
254
+ rpcGetActiveRegistrations(): Promise<Array<{
255
+ service: string;
256
+ endpoint: string;
257
+ }>>;
258
+ /**
259
+ * Queue outbound notifications for the alarm to deliver with bounded
260
+ * retries. The Worker only enqueues; delivery happens here because this
261
+ * DO holds no WebSocket and does no storage-bound work that a slow
262
+ * outbound fetch could pin.
263
+ */
264
+ rpcEnqueueNotify(items: NotifyItem[]): Promise<void>;
265
+ /**
266
+ * Tombstone the space (authority role). Enqueues nothing itself — the
267
+ * caller reads the registrations from the result and enqueues
268
+ * `notifySpaceDeleted` before the queue rows would be unreachable. The
269
+ * meta row is retained so a late getSpaceCredential can answer
270
+ * SpaceDeleted rather than SpaceNotFound. Idempotent.
271
+ */
272
+ rpcDeleteSpace(): Promise<{
273
+ registrations: Array<{
274
+ service: string;
275
+ endpoint: string;
276
+ }>;
277
+ }>;
278
+ /** Wipe everything, including queued notifications and alarms. */
279
+ rpcDestroy(): Promise<void>;
280
+ rpcStatus(): Promise<{
281
+ meta: SpaceMeta | null;
282
+ outdated: boolean;
283
+ recordCount: number;
284
+ memberCount: number;
285
+ writerCount: number;
286
+ queuedNotifications: number;
287
+ }>;
288
+ alarm(): Promise<void>;
289
+ private deliverQueuedNotifications;
290
+ private runMaintenanceIfDue;
291
+ private scheduleNextAlarm;
292
+ }
293
+ //#endregion
294
+ //#region src/index-do.d.ts
295
+ type SpaceIndexState = "pending" | "active" | "deleted";
296
+ interface SpaceIndexEntry {
297
+ uri: string;
298
+ authority: string;
299
+ type: string;
300
+ skey: string;
301
+ isAuthority: boolean;
302
+ state: SpaceIndexState;
303
+ createdAt: string;
304
+ updatedAt: string;
305
+ }
306
+ declare class SpaceIndexDurableObject<Env = unknown> extends DurableObject<Env> {
307
+ private sql;
308
+ private initialized;
309
+ constructor(ctx: DurableObjectState, env: Env);
310
+ private ensureInitialized;
311
+ /** Register (or revive) an entry in `pending` state. */
312
+ rpcRegister(entry: {
313
+ uri: string;
314
+ authority: string;
315
+ type: string;
316
+ skey: string;
317
+ isAuthority: boolean;
318
+ }): Promise<void>;
319
+ rpcActivate(uri: string): Promise<void>;
320
+ rpcMarkDeleted(uri: string): Promise<void>;
321
+ rpcGet(uri: string): Promise<SpaceIndexEntry | null>;
322
+ rpcList(params: {
323
+ type?: string;
324
+ authority?: string;
325
+ state?: SpaceIndexState;
326
+ limit: number;
327
+ afterUri?: string;
328
+ }): Promise<{
329
+ spaces: SpaceIndexEntry[];
330
+ hasMore: boolean;
331
+ }>;
332
+ rpcStats(): Promise<{
333
+ total: number;
334
+ active: number;
335
+ pending: number;
336
+ deleted: number;
337
+ hosted: number;
338
+ }>;
339
+ /** Wipe the registry (spaces reset). */
340
+ rpcDestroy(): Promise<void>;
341
+ /**
342
+ * Tombstone `pending` entries that never activated. They become
343
+ * `deleted` rather than being removed: a crash between the space DO's
344
+ * initialisation and the index activation leaves real DO storage
345
+ * behind, and the index row is the only durable manifest `spaces reset`
346
+ * has for finding and destroying it.
347
+ */
348
+ alarm(): Promise<void>;
349
+ }
350
+ //#endregion
351
+ //#region src/errors.d.ts
352
+ /**
353
+ * Typed errors for the spaces engine.
354
+ *
355
+ * Durable Object RPC flattens thrown errors into a wrapper `Error` whose
356
+ * message is `"${name}: ${message}"`, so every error here encodes its
357
+ * protocol error name as a message prefix. Worker-side handlers recover the
358
+ * name with {@link parseSpaceErrorCode} and map it onto the lexicon error
359
+ * shape.
360
+ */
361
+ /** Protocol error names used across space and simplespace endpoints. */
362
+ declare const SPACE_ERROR_CODES: readonly ["SpaceNotFound", "SpaceDeleted", "SpaceAlreadyExists", "RepoNotFound", "RecordNotFound", "RecordAlreadyExists", "BlobNotFound", "UserNotAuthorized", "AppNotAuthorized", "NotAuthorized", "InvalidDelegationToken", "InvalidClientAttestation", "InvalidCredential", "NotSpaceOwner", "UnsupportedPolicy", "UnsupportedAppAccess", "ServiceNotResolvable", "MalformedCursor", "InvalidSpaceUri", "InvalidRequest", "SpacesSchemaOutdated"];
363
+ type SpaceErrorCode = (typeof SPACE_ERROR_CODES)[number];
364
+ declare class SpaceError extends Error {
365
+ readonly code: SpaceErrorCode;
366
+ name: string;
367
+ constructor(code: SpaceErrorCode, message: string);
368
+ get status(): number;
369
+ /** The human message without the code prefix. */
370
+ get detail(): string;
371
+ }
372
+ /**
373
+ * Recover the space error name from an error that may have crossed a DO RPC
374
+ * boundary. Returns null for errors that aren't space errors.
375
+ */
376
+ declare function parseSpaceErrorCode(err: unknown): {
377
+ code: SpaceErrorCode;
378
+ message: string;
379
+ } | null;
380
+ /** HTTP status for a recovered space error name. */
381
+ declare function spaceErrorStatus(code: SpaceErrorCode): number;
382
+ //#endregion
383
+ //#region src/space-uri.d.ts
384
+ /**
385
+ * Space URI handling.
386
+ *
387
+ * A space is addressed as `at://{authorityDid}/space/{typeNsid}/{skey}` —
388
+ * the literal `space` marker keeps it unambiguous with public record URIs
389
+ * because a collection NSID always contains at least two dots. A record in
390
+ * a space appends `/{authorDid}/{collection}/{rkey}`.
391
+ */
392
+ interface SpaceRef {
393
+ /** The full space URI. */
394
+ uri: string;
395
+ /** The space authority DID. */
396
+ authority: string;
397
+ /** The space type NSID. */
398
+ type: string;
399
+ /** The space key (record-key syntax). */
400
+ skey: string;
401
+ }
402
+ /**
403
+ * Parse a space URI. Returns null when the string is not a valid space
404
+ * reference.
405
+ */
406
+ declare function parseSpaceUri(uri: string): SpaceRef | null;
407
+ /** Parse a space URI or throw an InvalidSpaceUri error. */
408
+ declare function requireSpaceUri(uri: string | undefined): SpaceRef;
409
+ declare function formatSpaceUri(authority: string, type: string, skey: string): string;
410
+ /** URI of a record within a space: `{spaceUri}/{repoDid}/{collection}/{rkey}`. */
411
+ declare function spaceRecordUri(spaceUri: string, repo: string, collection: string, rkey: string): string;
412
+ /**
413
+ * Stable identifier for a space used in R2 key prefixes: the lowercase,
414
+ * unpadded base32 encoding of the SHA-256 of the space URI. Deterministic,
415
+ * filesystem-safe and free of the URI's slashes and colons.
416
+ */
417
+ declare function spaceId(spaceUri: string): Promise<string>;
418
+ //#endregion
419
+ //#region src/blob-keys.d.ts
420
+ /**
421
+ * R2 key layout for space blobs.
422
+ *
423
+ * A blob referenced by a record in a space lives at
424
+ * `${did}/space/${spaceId}/${cid}` and is served only by the
425
+ * credential-gated `com.atproto.space.getBlob`. The same blob referenced
426
+ * from two spaces is stored twice: per-space prefixes make space deletion
427
+ * and full reset a prefix delete with no cross-space reference counting.
428
+ */
429
+ /**
430
+ * Key for a staged (uploaded, not yet referenced) blob. Must match the
431
+ * host's public blob layout: uploads land here and are promoted to their
432
+ * serving key when a record write references them.
433
+ */
434
+ declare function stagedBlobKey(did: string, cid: string): string;
435
+ /** Prefix holding every space blob for the account. */
436
+ declare function spaceBlobRootPrefix(did: string): string;
437
+ /** Prefix holding one space's blobs. `id` comes from {@link spaceId}. */
438
+ declare function spaceBlobPrefix(did: string, id: string): string;
439
+ /** Key for one blob in one space. */
440
+ declare function spaceBlobKey(did: string, id: string, cid: string): string;
441
+ /** Convenience: key for a blob given the space URI rather than its id. */
442
+ declare function spaceBlobKeyForUri(did: string, spaceUri: string, cid: string): Promise<string>;
443
+ //#endregion
444
+ //#region src/auth.d.ts
445
+ /** Resolve an issuer DID (+ key id) to a did:key string. */
446
+ type GetSigningKey = (iss: string, kid: string | undefined, forceRefresh: boolean) => Promise<string>;
447
+ /** Record a single-use key; false when it was already seen. */
448
+ type CheckReplay = (kind: string, key: string, expiresAtSec: number) => Promise<boolean>;
449
+ /**
450
+ * Peek at an unverified JWT's `typ` header. Used only for routing between
451
+ * authentication schemes — safe because neither token type verifies as the
452
+ * other.
453
+ */
454
+ declare function unverifiedJwtTyp(token: string): string | null;
455
+ /** Whether an Authorization header carries a space credential. */
456
+ declare function isSpaceCredentialAuth(authorization: string | undefined): boolean;
457
+ interface VerifyRequestOpts {
458
+ /** HTTP method of the request. */
459
+ htm: string;
460
+ /** Request URL; its path is combined with `publicOrigin` for htu. */
461
+ url: string;
462
+ /**
463
+ * The origin clients see (`https://host`). The Worker may be behind a
464
+ * proxy, so htu is reconstructed from this rather than trusted from the
465
+ * incoming URL.
466
+ */
467
+ publicOrigin: string;
468
+ dpopProof: string | undefined;
469
+ getSigningKey: GetSigningKey;
470
+ checkReplay: CheckReplay;
471
+ }
472
+ interface SpaceCredentialResult {
473
+ kind: "credential";
474
+ /** The credential issuer — the space's authority DID. */
475
+ iss: string;
476
+ }
477
+ /**
478
+ * Verify a space credential (`Authorization: DPoP <jwt>` + `DPoP` proof)
479
+ * presented against `space`. Checks, per the proposal: signature against
480
+ * the issuer's `#atproto_space` / `#atproto` key, `sub` equal to the
481
+ * requested space, `iss` equal to the space's authority, `cnf.jkt` equal
482
+ * to the proof key's thumbprint, proof `htm`/`htu`/`ath`/`iat` valid and
483
+ * proof `jti` unseen.
484
+ */
485
+ declare function verifySpaceCredentialAuth(credential: string, space: SpaceRef, opts: VerifyRequestOpts): Promise<SpaceCredentialResult>;
486
+ interface DelegationResult {
487
+ /** The user the delegation token vouches for. */
488
+ userDid: string;
489
+ /** Thumbprint of the DPoP key the credential must be bound to. */
490
+ dpopJkt: string;
491
+ }
492
+ /**
493
+ * Verify a delegation token (`Authorization: Bearer <jwt>` on
494
+ * getSpaceCredential) plus its DPoP proof (no `ath` when obtaining a
495
+ * credential). Single use by `(iss, jti)`.
496
+ */
497
+ declare function verifyDelegationAuth(token: string, space: SpaceRef, opts: VerifyRequestOpts): Promise<DelegationResult>;
498
+ //#endregion
499
+ //#region src/routes.d.ts
500
+ type SpaceStub = DurableObjectStub<SpaceDurableObject>;
501
+ type SpaceIndexStub = DurableObjectStub<SpaceIndexDurableObject>;
502
+ /** The operation shapes checked against a session's `space:` grants. */
503
+ type SpaceScopeMatch = {
504
+ type: string;
505
+ authority: string;
506
+ skey: string;
507
+ } & ({
508
+ action: "read" | "read_self";
509
+ } | {
510
+ action: "create" | "update" | "delete";
511
+ collection: string;
512
+ } | {
513
+ manage: "create" | "update" | "delete";
514
+ });
515
+ /**
516
+ * A host session (OAuth token with `space:` grants, or a fully-trusted
517
+ * operator session). App passwords are excluded in the alpha — the host's
518
+ * authenticate() must not produce one of these for them.
519
+ */
520
+ interface SpaceSessionAuth {
521
+ did: string;
522
+ /** Fully-trusted operator session: skips scope checks. */
523
+ fullTrust: boolean;
524
+ allowsSpace(match: SpaceScopeMatch): boolean;
525
+ }
526
+ interface SpaceRoutesHost {
527
+ operatorDid: string;
528
+ /** Public origin clients address, e.g. `https://pds.example.com`. */
529
+ publicOrigin: string;
530
+ /** R2 bucket for blobs; space blob endpoints 503 without it. */
531
+ blobs?: R2Bucket;
532
+ getKeypair(): Promise<Keypair>;
533
+ /** DID-doc signing key resolution for foreign issuers. */
534
+ getSigningKey: GetSigningKey;
535
+ /**
536
+ * Resolve a service identifier (`did` or `did#fragment`) to an HTTPS
537
+ * endpoint, or null when unresolvable.
538
+ */
539
+ resolveServiceEndpoint(service: string): Promise<string | null>;
540
+ /**
541
+ * Resolve a space authority's host endpoint: try
542
+ * `#atproto_space_host`, fall back to `#atproto_pds`.
543
+ */
544
+ resolveAuthorityEndpoint(did: string): Promise<string | null>;
545
+ /** Verify an inbound service-auth JWT bound to `lxm`. */
546
+ verifyServiceJwt(token: string, lxm: string): Promise<{
547
+ iss: string;
548
+ aud: string;
549
+ }>;
550
+ /**
551
+ * Host session authentication (OAuth / operator sessions). Returns a
552
+ * Response for authentication failures.
553
+ */
554
+ authenticate(c: Context): Promise<SpaceSessionAuth | Response>;
555
+ /**
556
+ * Lexicon validation with the host's validator. Throws on invalid
557
+ * records; the thrown message is surfaced as an InvalidRecord error.
558
+ */
559
+ validateRecord(input: {
560
+ collection: string;
561
+ record: unknown;
562
+ rkey: string;
563
+ validate?: boolean;
564
+ }): {
565
+ record: unknown;
566
+ status?: "valid" | "unknown";
567
+ };
568
+ getSpaceDO(uri: string): SpaceStub;
569
+ getIndexDO(): SpaceIndexStub;
570
+ /** Fetch override for outbound calls (tests). */
571
+ outboundFetch?: typeof fetch;
572
+ }
573
+ declare function createSpaceRoutes(host: SpaceRoutesHost): Hono;
574
+ //#endregion
575
+ //#region src/attestation.d.ts
576
+ interface VerifyAttestationOpts {
577
+ /** Expected audience: `spaceHostAud(authorityDid)`. */
578
+ expectedAud: string;
579
+ /**
580
+ * When set, an (unverified) client_id outside this list is rejected
581
+ * before any network I/O. The membership check runs regardless of
582
+ * signature state because the caller re-derives authorization from the
583
+ * returned client_id after full verification.
584
+ */
585
+ allowedClientIds?: readonly string[];
586
+ checkReplay: CheckReplay;
587
+ /** Fetch override for tests. */
588
+ fetch?: typeof fetch;
589
+ }
590
+ /**
591
+ * Verify a client attestation and return the attested client_id.
592
+ * Single-use by `(clientId, jti)`.
593
+ */
594
+ declare function verifyClientAttestation(attestation: string, opts: VerifyAttestationOpts): Promise<string>;
595
+ //#endregion
596
+ //#region src/commit.d.ts
597
+ interface SignCommitParams {
598
+ spaceUri: string;
599
+ /** The repo author (the operator DID for every repo Cirrus serves). */
600
+ author: string;
601
+ state: RepoState;
602
+ }
603
+ declare function signCommit(params: SignCommitParams, keypair: Keypair): Promise<SignedCommit>;
604
+ /**
605
+ * Lexicon JSON form of a signed commit (`com.atproto.space.defs#signedCommit`):
606
+ * bytes fields encode as `{"$bytes": "<base64>"}`.
607
+ */
608
+ declare function commitToJson(commit: SignedCommit): Record<string, unknown>;
609
+ /** Lexicon JSON form of a bare bytes value. */
610
+ declare function bytesToJson(bytes: Uint8Array): {
611
+ $bytes: string;
612
+ };
613
+ //#endregion
614
+ //#region src/records.d.ts
615
+ /**
616
+ * Record preparation and serialization for the Worker side of the write
617
+ * and read paths. Records are stored as dag-cbor bytes with their CID,
618
+ * computed here — the same encoding path the reference uses.
619
+ */
620
+ interface PreparedRecord {
621
+ cid: string;
622
+ bytes: Uint8Array;
623
+ blobCids: string[];
624
+ /** The lex-normalised record, for echoing back in responses. */
625
+ json: unknown;
626
+ }
627
+ /**
628
+ * Convert a client-supplied JSON record into its stored form: lex value →
629
+ * dag-cbor bytes → CID, with blob references enumerated for the space's
630
+ * blob tracking.
631
+ */
632
+ declare function prepareRecord(record: unknown): Promise<PreparedRecord>;
633
+ /** Decode stored record bytes back into response JSON. */
634
+ declare function recordBytesToJson(bytes: Uint8Array): unknown;
635
+ //#endregion
636
+ //#region src/schema.d.ts
637
+ /**
638
+ * SQLite schema for SpaceDurableObject.
639
+ *
640
+ * Mirrors the reference PDS's `002-space` migration table for table, minus
641
+ * the `space` column on every row — one DO per space makes it redundant.
642
+ *
643
+ * There is no migration path between alpha schema versions: bumping
644
+ * {@link SPACE_SCHEMA_VERSION} puts existing DOs into a refusing state until
645
+ * `pds spaces reset` wipes them. That is the alpha policy, applied honestly.
646
+ */
647
+ /** Bump on any breaking change to the tables below. */
648
+ declare const SPACE_SCHEMA_VERSION = 1;
649
+ /** Retain oplog entries for at most this many days. */
650
+ declare const OPLOG_RETENTION_DAYS = 30;
651
+ /** Retain at most this many oplog entries. */
652
+ declare const OPLOG_RETENTION_OPS = 10000;
653
+ /** Notify registrations expire after this many days. */
654
+ declare const NOTIFY_REGISTRATION_DAYS = 7;
655
+ //#endregion
656
+ //#region src/service-jwt.d.ts
657
+ interface ServiceJwtParams {
658
+ iss: string;
659
+ aud: string;
660
+ lxm?: string;
661
+ /** Lifetime in seconds (default 60). */
662
+ expiresInSec?: number;
663
+ }
664
+ declare function createServiceJwt(params: ServiceJwtParams, keypair: Keypair): Promise<string>;
665
+ //#endregion
666
+ //#region src/tid.d.ts
667
+ /**
668
+ * Revision (TID) helpers for the space repo.
669
+ */
670
+ /**
671
+ * Next revision: a fresh TID guaranteed strictly greater than `prev`.
672
+ * `@atcute/tid`'s clock is monotonic within an isolate, but the previous
673
+ * rev may come from a different isolate's clock (e.g. after a DO restart),
674
+ * so bump lexicographically when needed.
675
+ */
676
+ declare function nextRev(prev: string | null | undefined): string;
677
+ /**
678
+ * The smallest TID whose timestamp is `ms` milliseconds in the past, with a
679
+ * zero clockid. Used as a deletion cutoff for oplog compaction.
680
+ */
681
+ declare function tidCutoff(msAgo: number): string;
682
+ //#endregion
683
+ export { type ApplyWritesResult, type CheckReplay, type GetSigningKey, NOTIFY_REGISTRATION_DAYS, type NotifyItem, OPLOG_RETENTION_DAYS, OPLOG_RETENTION_OPS, type OplogEntry, type PreparedRecord, type PreparedSpaceWrite, type RepoState, SPACE_ERROR_CODES, SPACE_SCHEMA_VERSION, type ServiceJwtParams, type SpaceAppAccess, type SpaceConfig, SpaceDurableObject, SpaceError, type SpaceErrorCode, type SpaceHostConfig, SpaceIndexDurableObject, type SpaceIndexEntry, type SpaceIndexState, type SpaceIndexStub, type SpaceMeta, type SpacePolicy, type SpaceRecordRow, type SpaceRef, type SpaceRoutesHost, type SpaceScopeMatch, type SpaceSessionAuth, type SpaceStub, bytesToJson, commitToJson, createServiceJwt, createSpaceRoutes, formatSpaceUri, isSpaceCredentialAuth, nextRev, parseSpaceErrorCode, parseSpaceUri, prepareRecord, recordBytesToJson, requireSpaceUri, signCommit, spaceBlobKey, spaceBlobKeyForUri, spaceBlobPrefix, spaceBlobRootPrefix, spaceErrorStatus, spaceId, spaceRecordUri, stagedBlobKey, tidCutoff, unverifiedJwtTyp, verifyClientAttestation, verifyDelegationAuth, verifySpaceCredentialAuth };
684
+ //# sourceMappingURL=index.d.ts.map