@tapedb/tapedb 0.0.0-stage → 0.1.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,437 @@
1
+ import { DurableObject } from 'cloudflare:workers';
2
+ import { B as BundledWorkspaceMigration, m as TapeDBSchema } from './schema-CVcGZJfR.js';
3
+ import { WorkspaceRole, RoleClaim } from './index.js';
4
+ export { W as WORKSPACE_ROLE_LEVELS } from './schema-CVcGZJfR.js';
5
+
6
+ /**
7
+ * Broadcast topics: fire-and-forget messages between the sockets of one
8
+ * workspace, on the socket they already hold.
9
+ *
10
+ * A socket joins topics; a message sent to a topic reaches every other socket
11
+ * joined to it, with the sender's client id and subject, and a per-topic
12
+ * sequence number. The room keeps the last `replaySeconds` of each topic
13
+ * (default 60, at most `REPLAY_MESSAGES`): a client that rejoins after a
14
+ * reconnect passes the last sequence it saw and gets what it missed first.
15
+ * Joined topics live in the socket attachment, so they survive hibernation,
16
+ * and the client rejoins them after a reconnect.
17
+ *
18
+ * Who may join or send is the deployment's call (`defineTapeDB({ topics })`);
19
+ * by default anyone with a claim for the workspace may, guests included, as
20
+ * with presence.
21
+ */
22
+
23
+ /** @experimental May change in a minor release. */
24
+ type TopicAction = "join" | "send";
25
+ /**
26
+ * Decides whether a caller may join a topic or send to it. Return false (or
27
+ * throw) to refuse; the socket gets a `topic:error` and nothing else happens.
28
+ *
29
+ * @experimental May change in a minor release.
30
+ */
31
+ type TopicAuthorizer = (context: {
32
+ auth: {
33
+ sub: string;
34
+ role: number;
35
+ workspaceId: string;
36
+ };
37
+ topic: string;
38
+ action: TopicAction;
39
+ }) => boolean;
40
+ /**
41
+ * Topic options for `defineTapeDB({ topics })`.
42
+ *
43
+ * @experimental May change in a minor release.
44
+ */
45
+ interface TopicOptions {
46
+ authorize?: TopicAuthorizer;
47
+ /** Seconds of each topic kept for clients that reconnect; 0 keeps none. Default 60. */
48
+ replaySeconds?: number;
49
+ }
50
+
51
+ interface RetentionOptions {
52
+ /** Days a deleted or overwritten value may remain in history. Defaults to 30; at least 2. */
53
+ days?: number;
54
+ }
55
+
56
+ /**
57
+ * Worker bindings and vars. `tapedb init` writes exactly these.
58
+ *
59
+ * Three resources: one Durable Object namespace, two R2 buckets. There is no
60
+ * D1 and no identity database: the engine consumes a verified claim and never
61
+ * reads a session.
62
+ */
63
+ interface Env {
64
+ /** The database room. One instance per workspace. */
65
+ WORKSPACE: DurableObjectNamespace<WorkspaceRoom>;
66
+ /** Transaction log segments and snapshots. */
67
+ DATA: R2Bucket;
68
+ /** Uploaded files. Optional unless `db.$files` is used. */
69
+ FILES?: R2Bucket;
70
+ /** Original buckets and optional namespace while moving workspaces. */
71
+ DATA_FROM?: R2Bucket;
72
+ FILES_FROM?: R2Bucket;
73
+ WORKSPACE_FROM?: DurableObjectNamespace<WorkspaceRoom>;
74
+ /** Original jurisdiction during a move: eu, fedramp, or none. */
75
+ TAPEDB_MOVE_FROM?: string;
76
+ ENVIRONMENT?: string;
77
+ /**
78
+ * Restricts every workspace's Durable Object to a Cloudflare jurisdiction
79
+ * ("eu" or "fedramp"): it runs and stores data only there. Use `tapedb move`
80
+ * to relocate existing workspaces. The R2 buckets use the same jurisdiction.
81
+ */
82
+ TAPEDB_JURISDICTION?: string;
83
+ /** Shared HS256 secret used to verify role claims. */
84
+ TAPEDB_CLAIM_SECRET: string;
85
+ /** Wraps erasable subject keys; at least 32 characters when personal fields exist. */
86
+ TAPEDB_KEY_SECRET?: string;
87
+ /** Optional expected `iss` claim; checked only when set. */
88
+ TAPEDB_CLAIM_ISSUER?: string;
89
+ /** Optional expected `aud` claim; checked only when set. */
90
+ TAPEDB_CLAIM_AUDIENCE?: string;
91
+ /**
92
+ * Enables the development claim issuer. Set to `"true"` by `tapedb dev` on
93
+ * the command line and never written to `wrangler.jsonc`, so a plain
94
+ * `wrangler deploy` has no dev claim route.
95
+ */
96
+ TAPEDB_DEV_CLAIMS?: string;
97
+ /** Requires this token (x-tapedb-dev-token) on the development claim route; for deployed test Workers. */
98
+ TAPEDB_DEV_CLAIMS_TOKEN?: string;
99
+ }
100
+
101
+ declare class WorkspaceRoom extends DurableObject<Env> {
102
+ /**
103
+ * Last emitted result per socket client id and subscription id. This is a
104
+ * cache, not a source of truth: hibernation clears it and the next pass
105
+ * falls back to a full `query:data` payload.
106
+ */
107
+ private readonly subscriptionResults;
108
+ /** Namespaces touched since the current debounce window opened. */
109
+ private pendingInvalidationNamespaces;
110
+ private personal?;
111
+ private erased;
112
+ private erasurePending;
113
+ private erasureRun;
114
+ private readonly activeWork;
115
+ private fileWork;
116
+ private serializeFileWork;
117
+ private trackWork;
118
+ private importing;
119
+ private moving;
120
+ private moveState;
121
+ /** Boot stopped on a storage read that failed; the next request boots again. */
122
+ private bootDeferred;
123
+ private readonly roomEnv;
124
+ /** Restoring from R2 in budgeted steps; requests wait (503). */
125
+ private recovering;
126
+ private limiter;
127
+ private misplaced;
128
+ private invalidationTimer;
129
+ constructor(ctx: DurableObjectState, env: Env);
130
+ /** Readiness, migrations and recovery before the first request. */
131
+ private boot;
132
+ /** Boots again after a deferred boot; false while it still cannot. */
133
+ private bootAgain;
134
+ /**
135
+ * One budgeted step of a restore from R2. Progress is committed as it
136
+ * goes; a step that runs out of budget leaves the workspace recovering,
137
+ * answering 503, and continues on an alarm right away.
138
+ */
139
+ private recoverStep;
140
+ private get workspaceId();
141
+ /**
142
+ * Applies pending migrations before the object serves any request. Each
143
+ * migration and its `_migrations` row commit in the same transaction, so a
144
+ * failed boot cannot leave a half-migrated schema, and each runs with
145
+ * foreign keys off and checked before commit (see
146
+ * `applyMigrationWithoutCascades`).
147
+ */
148
+ private applyMigrations;
149
+ private applyMigration;
150
+ fetch(request: Request): Promise<Response>;
151
+ private route;
152
+ private moveControl;
153
+ private readPersonal;
154
+ private transact;
155
+ /**
156
+ * Runs a query document against this workspace. The claim is read from the
157
+ * Worker-forwarded header; `executeQuery` requires `view` on every requested
158
+ * and traversed namespace before touching SQL.
159
+ */
160
+ private query;
161
+ private handleWebSocket;
162
+ webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void>;
163
+ private handleSocketMessage;
164
+ /**
165
+ * One whole message. A frame is at most Cloudflare's 32 MiB; a larger
166
+ * message comes as `part` frames, stored until the last (see
167
+ * socket-state.ts), and then runs here like any other.
168
+ */
169
+ private handleText;
170
+ webSocketClose(ws: WebSocket, code: number, reason: string): void;
171
+ webSocketError(ws: WebSocket): void;
172
+ /** A socket's attachment, with any state stored past its 16 KiB. */
173
+ private readSocket;
174
+ private writeSocket;
175
+ private forgetSocketState;
176
+ private handlePing;
177
+ private topicError;
178
+ private handleTopicJoin;
179
+ /**
180
+ * The next sequence number of a topic, and the frame kept for replay.
181
+ * Old frames go as new ones arrive, by age and by count.
182
+ */
183
+ private sequenceTopicFrame;
184
+ private handleTopicLeave;
185
+ /**
186
+ * Delivers to every other socket joined to the topic. The sender need not
187
+ * be joined; it never receives its own message.
188
+ *
189
+ * A message too large for one frame comes as parts
190
+ * (`{ topic, part: { id, index, last }, data }`, `data` a slice of the
191
+ * message's JSON). Each part is checked and relayed as it arrives, and the
192
+ * receivers join them: the room never holds a whole message, so a
193
+ * broadcast has no size bound here.
194
+ */
195
+ private handleTopicSend;
196
+ private handlePresenceSet;
197
+ private handlePresenceClear;
198
+ private handleCursorSet;
199
+ private handleDragSet;
200
+ private handleDragClear;
201
+ private broadcastPresence;
202
+ private broadcastToTarget;
203
+ private presencePeers;
204
+ private socketsForTarget;
205
+ private removePresence;
206
+ private handleSubscribe;
207
+ private handleUnsubscribe;
208
+ /**
209
+ * Erases the workspace: its R2 history (manifest first, so nothing can
210
+ * recover from what is left), its uploaded files, then its Durable Object
211
+ * storage and alarm. Owners only. Each step is idempotent, so a failed
212
+ * erase is retried by calling it again. A tombstone stays behind so the
213
+ * workspace answers 410 from then on: a reconnecting client's outbox cannot
214
+ * quietly recreate it under the same id.
215
+ */
216
+ private erase;
217
+ private finishErase;
218
+ private eraseStorage;
219
+ private send;
220
+ private closeSocket;
221
+ private resultsFor;
222
+ private dropSubscriptionResults;
223
+ private scheduleInvalidation;
224
+ private flushInvalidations;
225
+ /** One subscription's re-run for this flush: its result, or why it failed. */
226
+ private runSubscription;
227
+ /**
228
+ * Runs the durability pass (flush then snapshot) and schedules the next
229
+ * pass only while there is work left. The 30s delay lets transactions
230
+ * accumulate into fewer, larger log segments.
231
+ */
232
+ alarm(): Promise<void>;
233
+ private runAlarm;
234
+ /**
235
+ * Schedules an alarm for the next due durability pass. An existing alarm is
236
+ * never pushed later: a write must not delay a flush that is already due.
237
+ */
238
+ private scheduleNextDurabilityAlarm;
239
+ private scheduleDurabilityAlarm;
240
+ /**
241
+ * File metadata rows. Bytes live in R2 and never enter the transaction log;
242
+ * this table is the queryable index over them.
243
+ */
244
+ private listFiles;
245
+ /** The stored file at `path`, as file rules see it. */
246
+ private storedFile;
247
+ /**
248
+ * Decides one file operation for the Worker, before it touches bytes:
249
+ * `{ path, action, size?, contentType? }`. A read of a file the caller may
250
+ * not see answers 404, like a file that does not exist, so a rule does not
251
+ * reveal what it hides.
252
+ */
253
+ private authorizeFileRequest;
254
+ private recordFile;
255
+ private forgetFile;
256
+ /** File-index entries are log rows, so they ship to R2 like any write. */
257
+ private scheduleFileFlush;
258
+ /** Registry snapshot for tooling: API names, attribute types and links. */
259
+ private schemaDocument;
260
+ private status;
261
+ }
262
+
263
+ /**
264
+ * Built-in limits for the claim route: exact token buckets, global per key.
265
+ *
266
+ * Each bucket lives in one of `LIMITER_SHARDS` Durable Objects of the
267
+ * workspace class, addressed by a name that is not a workspace id, so a
268
+ * deployment needs no extra binding or migration. A Durable Object is one
269
+ * place in the world and runs one request at a time, so a count is exact and
270
+ * shared by every location, unlike Cloudflare's rate-limit binding, which
271
+ * counts per location and approximately.
272
+ *
273
+ * Keys are HMACs of the caller's IP or subject under the claim secret: the
274
+ * limiter never stores an address or a user id. A bucket that has refilled
275
+ * is indistinguishable from none and is deleted.
276
+ */
277
+
278
+ interface ClaimLimit {
279
+ /** Requests a caller may make in a burst; the bucket's size. */
280
+ requests: number;
281
+ /** Seconds the bucket takes to refill from empty. */
282
+ perSeconds: number;
283
+ }
284
+ /**
285
+ * Limits on `POST /_tapedb/claim`. `ip` is checked before the session lookup
286
+ * (it protects your identity system from floods), `subject` after it.
287
+ * `false` turns one off.
288
+ */
289
+ interface ClaimLimits {
290
+ ip?: ClaimLimit | false;
291
+ subject?: ClaimLimit | false;
292
+ }
293
+
294
+ /**
295
+ * Claim minting.
296
+ *
297
+ * The engine consumes a short-lived signed claim and never issues one. This
298
+ * module is the other half: it turns a session into that claim, and it is
299
+ * deliberately identity-agnostic. Bring BetterAuth, your own JWT, a session
300
+ * cookie or an API key and implement two methods.
301
+ *
302
+ * Wire format matches the verifier exactly: compact JWS, HS256, base64url with
303
+ * no padding, payload `{ sub, workspaceId, role, iat, exp, iss?, aud? }`.
304
+ */
305
+
306
+ interface MintClaimInput {
307
+ sub: string;
308
+ workspaceId: string;
309
+ role: WorkspaceRole;
310
+ iss?: string;
311
+ aud?: string;
312
+ ttlSeconds?: number;
313
+ }
314
+ interface MintedClaim {
315
+ token: string;
316
+ expiresAt: number;
317
+ expiresIn: number;
318
+ }
319
+ /** Signs the compact HS256 claim the engine verifier accepts. */
320
+ declare function signRoleClaim(secret: string, input: MintClaimInput, now?: number): Promise<MintedClaim>;
321
+ /**
322
+ * The two methods a deployment implements, and an optional rate limit.
323
+ * Everything else about identity (passwords, magic codes, OAuth, cookies)
324
+ * stays in the host application.
325
+ */
326
+ interface ClaimIdentity {
327
+ /** Resolve the caller's subject from the request. Null means "not signed in". */
328
+ getSubject(headers: Headers): Promise<{
329
+ sub: string;
330
+ } | null>;
331
+ /** Resolve the caller's role in a workspace. Null means "not a member". */
332
+ getRole(workspaceId: string, sub: string): Promise<WorkspaceRole | null>;
333
+ /**
334
+ * Optional per-caller limit for the claim route, checked before anything
335
+ * else. `key` is `claim:<cf-connecting-ip>`. Return false to refuse with
336
+ * 429 `rate_limited`; a throw refuses with 500 `rate_limit_unavailable`.
337
+ * Back it with a Cloudflare rate-limit binding when the route is public.
338
+ */
339
+ allowRequest?(key: string): Promise<boolean>;
340
+ /**
341
+ * Built-in limits, on by default: exact, global token buckets per caller
342
+ * IP (before the session lookup) and per subject (after it). Defaults: 300
343
+ * requests per IP and 30 per subject, refilling over 60 seconds. Set a
344
+ * limit to `false`, or `limits: false`, to turn it off.
345
+ */
346
+ limits?: ClaimLimits | false;
347
+ }
348
+
349
+ type ClaimErrorCode = "missing_token" | "invalid_format" | "invalid_signature" | "expired" | "wrong_workspace" | "invalid_claim";
350
+ /** Typed verification failure; `code` is safe to return to the caller. */
351
+ declare class ClaimError extends Error {
352
+ readonly code: ClaimErrorCode;
353
+ constructor(code: ClaimErrorCode, message: string);
354
+ }
355
+ /** Minimal env view needed to verify a claim. */
356
+ interface ClaimVerificationEnv {
357
+ TAPEDB_CLAIM_SECRET: string;
358
+ TAPEDB_CLAIM_ISSUER?: string;
359
+ TAPEDB_CLAIM_AUDIENCE?: string;
360
+ }
361
+ /**
362
+ * Verifies a compact JWS against the frozen `RoleClaim` contract.
363
+ *
364
+ * Throws `ClaimError` for malformed tokens, bad signatures, expiry, workspace
365
+ * mismatches and invalid claim values. A missing server secret throws a plain
366
+ * `Error`: that is a deployment problem, not a client failure.
367
+ */
368
+ declare function verifyRoleClaim(token: string, env: ClaimVerificationEnv, expectedWorkspaceId: string): Promise<RoleClaim>;
369
+
370
+ declare const MAX_UPLOAD_BYTES: number;
371
+
372
+ /**
373
+ * Worker entry.
374
+ *
375
+ * `defineTapeDB()` installs the deployment schema and returns the Durable
376
+ * Object class plus the fetch handler. The consumer's Worker is then two
377
+ * exports and nothing else:
378
+ *
379
+ * const tapedb = defineTapeDB({ schema });
380
+ * export const WorkspaceRoom = tapedb.WorkspaceRoom;
381
+ * export default tapedb.worker;
382
+ */
383
+
384
+ /** One app migration, as `tapedb migrate` bundles it. */
385
+ type AppMigration = BundledWorkspaceMigration;
386
+ interface DefineTapeDBOptions {
387
+ schema: TapeDBSchema;
388
+ /**
389
+ * The app's committed migrations, from `tapedb/migrations.gen.ts`. Omit
390
+ * only before the first `tapedb migrate dev`: the schema's generated SQL
391
+ * is used, which cannot evolve.
392
+ */
393
+ migrations?: readonly AppMigration[];
394
+ /**
395
+ * Identity adapter. Implement `getSubject` and `getRole` to serve
396
+ * `POST /_tapedb/claim`. Without it that route returns 501 and the consumer
397
+ * must supply tokens to the client itself.
398
+ */
399
+ identity?: ClaimIdentity;
400
+ /**
401
+ * Development-only issuer: mints an OWNER claim for any workspace with no
402
+ * session. Always refused when `ENVIRONMENT` is `production`.
403
+ */
404
+ devClaims?: boolean;
405
+ /**
406
+ * Broadcast topics. `authorize` decides whether a caller may join a topic
407
+ * or send to it; without it anyone with a claim for the workspace may,
408
+ * guests included, as with presence. `replaySeconds` (default 60) is how
409
+ * much of each topic the room keeps for clients that reconnect.
410
+ *
411
+ * @experimental May change in a minor release.
412
+ */
413
+ topics?: TopicOptions;
414
+ /**
415
+ * Records who changed each row: the claim's subject and role on every log
416
+ * entry (also in R2), and a per-row history read with `db.$history`.
417
+ * Off by default; the history is pruned with `retention`.
418
+ */
419
+ audit?: boolean;
420
+ /**
421
+ * How long deleted or overwritten values may remain in the workspace's
422
+ * history (R2 log segments, older snapshots, the local replay log).
423
+ * Defaults to 30 days; at least 2.
424
+ */
425
+ retention?: RetentionOptions;
426
+ }
427
+ interface TapeDBWorker {
428
+ /** The database room class. Export it from the Worker entry. */
429
+ WorkspaceRoom: typeof WorkspaceRoom;
430
+ worker: {
431
+ fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response>;
432
+ };
433
+ }
434
+ declare function defineTapeDB(options: DefineTapeDBOptions): TapeDBWorker;
435
+
436
+ export { BundledWorkspaceMigration, ClaimError, MAX_UPLOAD_BYTES, WorkspaceRoom as TapeDBRoom, TapeDBSchema, defineTapeDB, signRoleClaim, verifyRoleClaim };
437
+ export type { AppMigration, ClaimIdentity, ClaimLimit, ClaimLimits, DefineTapeDBOptions, Env, TapeDBWorker, TopicAction, TopicAuthorizer, TopicOptions };