@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.
- package/API.md +301 -0
- package/LICENSE +21 -0
- package/LIMITATIONS.md +34 -0
- package/PRIVACY.md +119 -0
- package/README.md +720 -2
- package/RELEASING.md +117 -0
- package/SECURITY.md +121 -0
- package/dist/chunk-3AL32Q4K.js +241 -0
- package/dist/chunk-3AL32Q4K.js.map +1 -0
- package/dist/chunk-CYDXFAEB.js +33 -0
- package/dist/chunk-CYDXFAEB.js.map +1 -0
- package/dist/chunk-UYZJAMBR.js +27 -0
- package/dist/chunk-UYZJAMBR.js.map +1 -0
- package/dist/chunk-VWW5OS5B.js +841 -0
- package/dist/chunk-VWW5OS5B.js.map +1 -0
- package/dist/cli.d.ts +44 -0
- package/dist/cli.js +1501 -0
- package/dist/cli.js.map +1 -0
- package/dist/client-DgSnn9BE.d.ts +646 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.js +3007 -0
- package/dist/index.js.map +1 -0
- package/dist/react.d.ts +41 -0
- package/dist/react.js +59 -0
- package/dist/react.js.map +1 -0
- package/dist/schema-CVcGZJfR.d.ts +691 -0
- package/dist/schema-entry-CpO_IGFv.d.ts +522 -0
- package/dist/schema.d.ts +2 -0
- package/dist/schema.js +22 -0
- package/dist/schema.js.map +1 -0
- package/dist/worker.d.ts +437 -0
- package/dist/worker.js +9270 -0
- package/dist/worker.js.map +1 -0
- package/package.json +93 -4
package/RELEASING.md
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# Releasing TapeDB
|
|
2
|
+
|
|
3
|
+
## Current status
|
|
4
|
+
|
|
5
|
+
0.1.0 is the first release. Every later release passes the same gates and
|
|
6
|
+
checks before it is tagged or published.
|
|
7
|
+
|
|
8
|
+
The design boundaries are in [LIMITATIONS.md](LIMITATIONS.md). The security
|
|
9
|
+
model and operator responsibilities are in [SECURITY.md](SECURITY.md).
|
|
10
|
+
|
|
11
|
+
## Gates
|
|
12
|
+
|
|
13
|
+
All gates must be true before a release is tagged or published:
|
|
14
|
+
|
|
15
|
+
1. `bun install --frozen-lockfile && bun run verify` passes on Node 22.18 or
|
|
16
|
+
newer.
|
|
17
|
+
2. The secret and history scan is clean, and dependency updates have been
|
|
18
|
+
reviewed.
|
|
19
|
+
3. The security review covers claims, the trusted claim header, workspace
|
|
20
|
+
isolation, file routes and erasure. Findings are fixed or accepted in
|
|
21
|
+
writing.
|
|
22
|
+
4. A clean consumer project installs the packed artifact and exercises writes,
|
|
23
|
+
live queries, an upload, a migration and erasure through the packaged CLI.
|
|
24
|
+
5. The changelog and README describe the release and its design boundaries.
|
|
25
|
+
6. Independent source review is complete, and the release candidate passes
|
|
26
|
+
deployed-runtime durability, recovery, migration, erasure and offline
|
|
27
|
+
persistence checks.
|
|
28
|
+
7. The GitHub repository is made public only after the npm package is ready,
|
|
29
|
+
with branch protection or rulesets and secret scanning enabled. GitHub does
|
|
30
|
+
not offer branch protection or rulesets for private repositories on the
|
|
31
|
+
free plan, so this is applied at the visibility change; until then the
|
|
32
|
+
checks are advisory.
|
|
33
|
+
|
|
34
|
+
The scoped security review is recorded in
|
|
35
|
+
[SECURITY-REVIEW.md](SECURITY-REVIEW.md). The independent source review and
|
|
36
|
+
remediation are recorded in [INDEPENDENT-REVIEW.md](INDEPENDENT-REVIEW.md).
|
|
37
|
+
Check the validation results against the exact release candidate commit.
|
|
38
|
+
|
|
39
|
+
## Package checks
|
|
40
|
+
|
|
41
|
+
Run these before a tag, from a clean checkout:
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
bun install --frozen-lockfile
|
|
45
|
+
bun run verify
|
|
46
|
+
bun run test:e2e
|
|
47
|
+
bunx playwright install --with-deps chromium
|
|
48
|
+
bun run test:browser
|
|
49
|
+
bun pm pack --destination /tmp/pack
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The consumer check is `bun run test:e2e`: it exercises a freshly packed
|
|
53
|
+
artifact in workerd, including writes, live queries, files, migrations, owner
|
|
54
|
+
erasure and an R2 restore. `bun run test:browser` checks IndexedDB persistence
|
|
55
|
+
across a reload in Chromium.
|
|
56
|
+
|
|
57
|
+
The secret and history scan that a workflow used to run is `gitleaks detect`:
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
gitleaks detect --source . --redact --no-banner --verbose # gitleaks v8.30.1
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
The package smoke test inside `verify` installs the tarball under Node in
|
|
64
|
+
default npm, CommonJS and ESM projects. It uses Node 22.18 or newer and npm, and emits consumer TypeScript declarations.
|
|
65
|
+
|
|
66
|
+
Exercise the packed product as a consumer would:
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
cd "$(mktemp -d)"
|
|
70
|
+
npm init -y
|
|
71
|
+
npm install /tmp/pack/tapedb-*.tgz wrangler
|
|
72
|
+
npx @tapedb/tapedb init
|
|
73
|
+
npx @tapedb/tapedb dev
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Drive that project through a write, a live subscription, an upload, a
|
|
77
|
+
migration and erasure. Do not release on the strength of the unit suite alone.
|
|
78
|
+
|
|
79
|
+
## Publishing
|
|
80
|
+
|
|
81
|
+
Only after the gates and checks:
|
|
82
|
+
|
|
83
|
+
1. Update `CHANGELOG.md` and set the intended version in `package.json`.
|
|
84
|
+
2. Open the release pull request and remove `"private": true` there. Keep
|
|
85
|
+
`publishConfig` and the repository metadata. Merge only after the checks
|
|
86
|
+
pass.
|
|
87
|
+
3. Create an annotated tag and GitHub release from the merged commit.
|
|
88
|
+
4. From that tag on a clean checkout, run the package checks again.
|
|
89
|
+
5. Publish:
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
npm publish --access public
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Without an npm CI service there is no OIDC token, so this publish carries no
|
|
96
|
+
provenance attestation. Do not add `--provenance` unless the publish runs in
|
|
97
|
+
CI.
|
|
98
|
+
|
|
99
|
+
6. Verify the registry and the consumer path:
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
npm view tapedb version dist-tags.latest
|
|
103
|
+
cd "$(mktemp -d)" && npm init -y && npm install @tapedb/tapedb wrangler
|
|
104
|
+
npx @tapedb/tapedb init
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
7. Make the GitHub repository public and enable branch protection and secret
|
|
108
|
+
scanning. Update the package page and the documentation links.
|
|
109
|
+
|
|
110
|
+
## After publishing
|
|
111
|
+
|
|
112
|
+
- Publish a GitHub release with the changelog.
|
|
113
|
+
- Keep the previous version installable and document any migration steps.
|
|
114
|
+
- If a release is broken, deprecate it with `npm deprecate` and publish a fixed
|
|
115
|
+
version. Do not rewrite a published version or tag.
|
|
116
|
+
- Never put `TAPEDB_CLAIM_SECRET`, claim tokens, Cloudflare credentials or
|
|
117
|
+
customer data in a release, issue, pull request or artifact.
|
package/SECURITY.md
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
# Security policy
|
|
2
|
+
|
|
3
|
+
## Supported versions
|
|
4
|
+
|
|
5
|
+
The latest 0.x release receives security fixes. Fixes land on `main`, ship in
|
|
6
|
+
a patch release, and are called out in the changelog.
|
|
7
|
+
|
|
8
|
+
## Reporting a vulnerability
|
|
9
|
+
|
|
10
|
+
Do not open a public issue for a security report.
|
|
11
|
+
|
|
12
|
+
Use GitHub's private vulnerability reporting for this repository when it is
|
|
13
|
+
enabled:
|
|
14
|
+
|
|
15
|
+
<https://github.com/tapedb/tapedb/security/advisories/new>
|
|
16
|
+
|
|
17
|
+
Until the repository is public, private reporting may be unavailable; in that
|
|
18
|
+
case contact a repository maintainer directly through GitHub. Do not open a
|
|
19
|
+
public issue. Please include the affected commit or version, the trust boundary
|
|
20
|
+
you crossed, a minimal reproduction, and any suggested fix. Do not include real
|
|
21
|
+
claim tokens, Cloudflare secrets, customer data or personal data; use synthetic
|
|
22
|
+
values.
|
|
23
|
+
|
|
24
|
+
Maintainers will triage the report, confirm the affected path, and coordinate a
|
|
25
|
+
fix and disclosure. There is no bug bounty.
|
|
26
|
+
|
|
27
|
+
## Security model
|
|
28
|
+
|
|
29
|
+
- **Claims.** The Worker verifies a short-lived compact HS256 JWT before it
|
|
30
|
+
touches a Durable Object. `TAPEDB_CLAIM_SECRET` is the shared signing secret.
|
|
31
|
+
The optional issuer and audience checks are enforced only when configured.
|
|
32
|
+
The development claim route is enabled only when the code opts in, the
|
|
33
|
+
deployment sets `TAPEDB_DEV_CLAIMS=true`, and `ENVIRONMENT` is not
|
|
34
|
+
`production`; `tapedb deploy` refuses to ship the flag.
|
|
35
|
+
- **Identity seam.** The engine never issues sessions. A deployment implements
|
|
36
|
+
`getSubject` and `getRole`; the role it returns is signed into the claim.
|
|
37
|
+
- **Workspace isolation.** The Worker verifies the claim against the workspace
|
|
38
|
+
id in the URL, then forwards a trusted, unsigned claim header to that
|
|
39
|
+
workspace's Durable Object. Client-supplied `x-tapedb-*` headers are removed
|
|
40
|
+
before forwarding. The Durable Object binding is not a public route, and a
|
|
41
|
+
request path with an empty segment (`//`) outside `/files/` is refused, so
|
|
42
|
+
the room's internal routes (`/move/*`, `/storage/*`, writes to `/files`)
|
|
43
|
+
cannot be reached from outside. The file index accepts only objects stored
|
|
44
|
+
under the file's own path in that workspace.
|
|
45
|
+
- **Read and write rules.** `role()`, `filter()` and `check()` are applied in
|
|
46
|
+
the engine. A rule that throws denies. Erasing a workspace requires an owner
|
|
47
|
+
claim. With `audit: true`, a row's history (writers, roles, times and
|
|
48
|
+
actions, never values) is readable by admins and owners regardless of read
|
|
49
|
+
rules.
|
|
50
|
+
- **Files.** Uploads go to the workspace's R2 prefix. Without file rules,
|
|
51
|
+
reads require at least member, writes and deletes at least editor. With
|
|
52
|
+
rules (`schema(models, { files })`), the workspace's Durable Object decides
|
|
53
|
+
every read, write, delete and multipart start or completion before bytes
|
|
54
|
+
move, and lists only readable files; a file the caller may not read answers
|
|
55
|
+
404. Rules fail closed. One request carries at most 25 MiB; larger files
|
|
56
|
+
are R2 multipart uploads on the same route and role, tied to their file
|
|
57
|
+
path, and listed only once complete.
|
|
58
|
+
- **Transport.** HTTP uses `Authorization: Bearer`; WebSocket upgrades carry the
|
|
59
|
+
claim in `Sec-WebSocket-Protocol`, never in the URL. Claims should be kept out
|
|
60
|
+
of request-header logging.
|
|
61
|
+
|
|
62
|
+
Data reaches Cloudflare over TLS and is encrypted at rest by Cloudflare. The
|
|
63
|
+
application owner is the data controller and Cloudflare is the processor; see
|
|
64
|
+
[PRIVACY.md](PRIVACY.md).
|
|
65
|
+
|
|
66
|
+
## Operator responsibilities
|
|
67
|
+
|
|
68
|
+
The library cannot enforce these for you:
|
|
69
|
+
|
|
70
|
+
- Keep `TAPEDB_CLAIM_SECRET` out of source control, logs and client bundles.
|
|
71
|
+
It must be at least 32 bytes (`openssl rand -base64 32`); a shorter one is
|
|
72
|
+
refused, because it could be found offline from any claim.
|
|
73
|
+
Rotate it if it is exposed; all existing claims become invalid.
|
|
74
|
+
- Implement `getSubject` and `getRole` correctly. A role returned by
|
|
75
|
+
`getRole` is trusted by the engine.
|
|
76
|
+
- Do not set `TAPEDB_DEV_CLAIMS` in production. On a deployed test Worker
|
|
77
|
+
that untrusted users can reach, set it only together with a random
|
|
78
|
+
`TAPEDB_DEV_CLAIMS_TOKEN` secret: the dev claim route then mints only for
|
|
79
|
+
requests carrying that token in `x-tapedb-dev-token`, and answers 401
|
|
80
|
+
otherwise. Set the token before turning dev claims on. `tapedb deploy`
|
|
81
|
+
refuses `TAPEDB_DEV_CLAIMS`, but a manual `wrangler deploy` can still ship it.
|
|
82
|
+
- The claim route is rate-limited by default (per IP before the session
|
|
83
|
+
lookup, per subject after it; exact, global token buckets in Durable
|
|
84
|
+
Objects). Keep the limits on for a public route, and protect session-bearing
|
|
85
|
+
identity lookups against CSRF according to your auth system. An unreachable
|
|
86
|
+
limiter lets claims through and logs `claim_limit_unavailable`.
|
|
87
|
+
- Exclude the `Authorization` and `Sec-WebSocket-Protocol` headers from
|
|
88
|
+
Cloudflare request-header logging.
|
|
89
|
+
- Do not add R2 bucket lock rules to the data or files buckets; they prevent
|
|
90
|
+
retention and erasure.
|
|
91
|
+
- Account for Cloudflare's 30-day Durable Object point-in-time recovery when
|
|
92
|
+
making erasure promises.
|
|
93
|
+
|
|
94
|
+
## Design boundaries
|
|
95
|
+
|
|
96
|
+
The design boundaries and release gates are listed in
|
|
97
|
+
[LIMITATIONS.md](LIMITATIONS.md). Who made each write is recorded only with
|
|
98
|
+
`defineTapeDB({ audit: true })`. Deleting a subject key makes personal fields
|
|
99
|
+
unreadable everywhere, Cloudflare's point-in-time recovery copies included;
|
|
100
|
+
ordinary plaintext stays in those copies for up to 30 days.
|
|
101
|
+
|
|
102
|
+
## Workspace moves and imports
|
|
103
|
+
|
|
104
|
+
Only workspace owners can move or import. A move checks that the destination
|
|
105
|
+
is empty, freezes source writes, preserves retry receipts, and publishes the
|
|
106
|
+
destination only after rows and indexed files are present. Internal move
|
|
107
|
+
controls accept only Worker-forwarded claims and have no public route.
|
|
108
|
+
Concurrent move requests are serialized by the destination room. Uploads use
|
|
109
|
+
separate byte objects and commit their index pointers afterwards, so a write
|
|
110
|
+
refused during a move cannot overwrite a file already being transferred.
|
|
111
|
+
|
|
112
|
+
## Personal-field keys
|
|
113
|
+
|
|
114
|
+
Personal string and JSON values use AES-GCM with random per-subject keys.
|
|
115
|
+
`TAPEDB_KEY_SECRET` wraps those keys; it also derives opaque R2 key names by
|
|
116
|
+
HMAC. Ciphertext authenticates its workspace, subject key, table, row and field.
|
|
117
|
+
Only an owner may delete a subject key. Erasure clears room plaintext caches
|
|
118
|
+
and refreshes live queries. Keep the wrapping secret stable and restrict R2
|
|
119
|
+
access: copying a wrapped subject key preserves the ability to decrypt it.
|
|
120
|
+
A plaintext export is a separate copy. Enabling encryption does not remove
|
|
121
|
+
plaintext from historical storage predating that change.
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
// src/engine/registry.ts
|
|
2
|
+
var ENGINE_TABLES = {
|
|
3
|
+
migrations: "_migrations",
|
|
4
|
+
txLog: "_tx_log",
|
|
5
|
+
txReceipts: "_tx_receipts",
|
|
6
|
+
txState: "_tx_state",
|
|
7
|
+
flushState: "_flush_state",
|
|
8
|
+
snapshotState: "_snapshot_state",
|
|
9
|
+
engineMeta: "_engine_meta",
|
|
10
|
+
files: "_files",
|
|
11
|
+
txAudit: "_tx_audit"
|
|
12
|
+
};
|
|
13
|
+
var NAMESPACES = {};
|
|
14
|
+
var LINKS = {};
|
|
15
|
+
var configured = false;
|
|
16
|
+
var generation = 0;
|
|
17
|
+
function registryGeneration() {
|
|
18
|
+
return generation;
|
|
19
|
+
}
|
|
20
|
+
function configureRegistry(registry) {
|
|
21
|
+
for (const key of Object.keys(NAMESPACES)) delete NAMESPACES[key];
|
|
22
|
+
for (const key of Object.keys(LINKS)) delete LINKS[key];
|
|
23
|
+
for (const namespace of registry.namespaces) {
|
|
24
|
+
NAMESPACES[namespace.apiName] = namespace;
|
|
25
|
+
}
|
|
26
|
+
for (const link of registry.links) {
|
|
27
|
+
LINKS[link.apiName] = link;
|
|
28
|
+
}
|
|
29
|
+
configured = true;
|
|
30
|
+
generation += 1;
|
|
31
|
+
}
|
|
32
|
+
function registryConfigured() {
|
|
33
|
+
return configured;
|
|
34
|
+
}
|
|
35
|
+
function toSnakeCase(value) {
|
|
36
|
+
return value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[-\s]+/g, "_").toLowerCase();
|
|
37
|
+
}
|
|
38
|
+
function findNamespace(apiName) {
|
|
39
|
+
return NAMESPACES[apiName];
|
|
40
|
+
}
|
|
41
|
+
function namespaceTables() {
|
|
42
|
+
return Object.values(NAMESPACES).map((namespace) => namespace.table);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// src/engine/migrations-bundle.ts
|
|
46
|
+
var BASELINE_MIGRATION_ID = "0001_baseline";
|
|
47
|
+
var ENGINE_MIGRATION_PREFIX = "tapedb_";
|
|
48
|
+
var ENGINE_MIGRATIONS = [
|
|
49
|
+
{
|
|
50
|
+
id: "tapedb_0002_files_table",
|
|
51
|
+
sql: 'ALTER TABLE "$files" RENAME TO "_files";'
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
id: "tapedb_0003_tx_receipts",
|
|
55
|
+
sql: `CREATE TABLE "_tx_receipts" (
|
|
56
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
57
|
+
seq INTEGER NOT NULL,
|
|
58
|
+
ops_hash TEXT NOT NULL
|
|
59
|
+
);
|
|
60
|
+
INSERT INTO "_tx_receipts" (id, seq, ops_hash)
|
|
61
|
+
SELECT client_tx_id, seq, ops_hash FROM "_tx_log" WHERE client_tx_id IS NOT NULL;`
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
// Receipts expire with the history retention, so each records when its
|
|
65
|
+
// write was applied. Existing ones take their log row's time, or now.
|
|
66
|
+
id: "tapedb_0004_receipt_time",
|
|
67
|
+
sql: `ALTER TABLE "_tx_receipts" ADD COLUMN at INTEGER NOT NULL DEFAULT 0;
|
|
68
|
+
UPDATE "_tx_receipts" SET at = COALESCE(
|
|
69
|
+
(SELECT l.at FROM "_tx_log" l WHERE l.seq = "_tx_receipts".seq),
|
|
70
|
+
CAST(strftime('%s', 'now') AS INTEGER) * 1000
|
|
71
|
+
);`
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
// A log entry larger than a row holds keeps its ops in parts: part 0 in
|
|
75
|
+
// _tx_log.ops, the rest here (see tx-log.ts).
|
|
76
|
+
id: "tapedb_0005_log_parts",
|
|
77
|
+
sql: `CREATE TABLE "_tx_log_parts" (
|
|
78
|
+
seq INTEGER NOT NULL,
|
|
79
|
+
part INTEGER NOT NULL,
|
|
80
|
+
ops TEXT NOT NULL,
|
|
81
|
+
PRIMARY KEY (seq, part)
|
|
82
|
+
) WITHOUT ROWID;`
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
// Who uploaded a file: the claim subject, for file access rules.
|
|
86
|
+
id: "tapedb_0006_file_uploader",
|
|
87
|
+
sql: `ALTER TABLE "_files" ADD COLUMN uploaded_by TEXT;`
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
// Socket state past the attachment's 16 KiB, and messages arriving in
|
|
91
|
+
// parts (see socket-state.ts). Ephemeral: never logged or snapshotted.
|
|
92
|
+
id: "tapedb_0007_socket_state",
|
|
93
|
+
sql: `CREATE TABLE "_socket_state" (
|
|
94
|
+
client_id TEXT NOT NULL,
|
|
95
|
+
part INTEGER NOT NULL,
|
|
96
|
+
data TEXT NOT NULL,
|
|
97
|
+
PRIMARY KEY (client_id, part)
|
|
98
|
+
) WITHOUT ROWID;
|
|
99
|
+
CREATE TABLE "_socket_parts" (
|
|
100
|
+
client_id TEXT NOT NULL,
|
|
101
|
+
id TEXT NOT NULL,
|
|
102
|
+
idx INTEGER NOT NULL,
|
|
103
|
+
data TEXT NOT NULL,
|
|
104
|
+
PRIMARY KEY (client_id, id, idx)
|
|
105
|
+
) WITHOUT ROWID;`
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
// Old engines may have deleted receipts. Preserve known keys and set a
|
|
109
|
+
// fixed safety boundary for unknown pre-upgrade requests in used rooms.
|
|
110
|
+
id: "tapedb_0008_permanent_receipts",
|
|
111
|
+
sql: `ALTER TABLE "_tx_receipts" RENAME TO "_tx_receipts_old";
|
|
112
|
+
CREATE TABLE "_tx_receipts" (
|
|
113
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
114
|
+
seq INTEGER NOT NULL,
|
|
115
|
+
ops_hash TEXT,
|
|
116
|
+
at INTEGER NOT NULL
|
|
117
|
+
);
|
|
118
|
+
INSERT INTO "_tx_receipts" SELECT id, seq, ops_hash, at FROM "_tx_receipts_old";
|
|
119
|
+
DROP TABLE "_tx_receipts_old";
|
|
120
|
+
CREATE INDEX "_tx_receipts_hash_age" ON "_tx_receipts" (at) WHERE ops_hash IS NOT NULL;
|
|
121
|
+
INSERT OR REPLACE INTO "_engine_meta" ("key", value)
|
|
122
|
+
SELECT 'receipts_since', CAST(MAX(
|
|
123
|
+
COALESCE((SELECT CAST(value AS INTEGER) FROM "_engine_meta" WHERE "key" = 'receipts_since'), 0),
|
|
124
|
+
CAST(strftime('%s', 'now') AS INTEGER) * 1000 + CAST(substr(strftime('%f', 'now'), 4, 3) AS INTEGER)
|
|
125
|
+
) AS TEXT) WHERE EXISTS (SELECT 1 FROM "_tx_state" WHERE high_water_seq > 0);`
|
|
126
|
+
},
|
|
127
|
+
{
|
|
128
|
+
// Recent topic messages, for clients rejoining after a reconnect.
|
|
129
|
+
// Ephemeral like the sockets: never logged, snapshotted or exported.
|
|
130
|
+
id: "tapedb_0009_topic_buffer",
|
|
131
|
+
sql: `CREATE TABLE "_topic_buffer" (
|
|
132
|
+
topic TEXT NOT NULL,
|
|
133
|
+
seq INTEGER NOT NULL,
|
|
134
|
+
at INTEGER NOT NULL,
|
|
135
|
+
frame TEXT NOT NULL,
|
|
136
|
+
PRIMARY KEY (topic, seq)
|
|
137
|
+
) WITHOUT ROWID;
|
|
138
|
+
CREATE TABLE "_topic_seq" (
|
|
139
|
+
topic TEXT PRIMARY KEY NOT NULL,
|
|
140
|
+
seq INTEGER NOT NULL
|
|
141
|
+
) WITHOUT ROWID;`
|
|
142
|
+
},
|
|
143
|
+
{
|
|
144
|
+
// Opt-in write audit (audit.ts): who changed each row, pruned by age.
|
|
145
|
+
id: "tapedb_0010_tx_audit",
|
|
146
|
+
sql: `CREATE TABLE "_tx_audit" (
|
|
147
|
+
-- table, row and sequence in one key, for snapshot paging.
|
|
148
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
149
|
+
table_name TEXT NOT NULL,
|
|
150
|
+
row_id TEXT NOT NULL,
|
|
151
|
+
seq INTEGER NOT NULL,
|
|
152
|
+
at INTEGER NOT NULL,
|
|
153
|
+
user_id TEXT,
|
|
154
|
+
role INTEGER,
|
|
155
|
+
action TEXT NOT NULL
|
|
156
|
+
) WITHOUT ROWID;
|
|
157
|
+
CREATE INDEX "_tx_audit_row" ON "_tx_audit" (table_name, row_id, seq);
|
|
158
|
+
CREATE INDEX "_tx_audit_at" ON "_tx_audit" (at);`
|
|
159
|
+
}
|
|
160
|
+
];
|
|
161
|
+
var WORKSPACE_MIGRATIONS = [];
|
|
162
|
+
function isEngineMigration(id) {
|
|
163
|
+
return id === BASELINE_MIGRATION_ID || id.startsWith(ENGINE_MIGRATION_PREFIX);
|
|
164
|
+
}
|
|
165
|
+
function configureMigrations(migrations) {
|
|
166
|
+
const baseline = migrations.find((migration) => migration.id === BASELINE_MIGRATION_ID);
|
|
167
|
+
if (!baseline) {
|
|
168
|
+
throw new Error(`Migrations must include ${BASELINE_MIGRATION_ID}.`);
|
|
169
|
+
}
|
|
170
|
+
const app = migrations.filter((migration) => !isEngineMigration(migration.id));
|
|
171
|
+
WORKSPACE_MIGRATIONS.length = 0;
|
|
172
|
+
WORKSPACE_MIGRATIONS.push(baseline, ...ENGINE_MIGRATIONS, ...app);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// src/claims.ts
|
|
176
|
+
var WORKSPACE_ROLE_LEVELS = {
|
|
177
|
+
GUEST: 0,
|
|
178
|
+
USER: 1,
|
|
179
|
+
MEMBER: 2,
|
|
180
|
+
EDITOR: 3,
|
|
181
|
+
MODERATOR: 4,
|
|
182
|
+
ADMIN: 5,
|
|
183
|
+
OWNER: 6,
|
|
184
|
+
FOUNDER: 7,
|
|
185
|
+
DEVELOPER: 8
|
|
186
|
+
};
|
|
187
|
+
function hasRoleLevel(role, minimum) {
|
|
188
|
+
return role >= minimum;
|
|
189
|
+
}
|
|
190
|
+
function hasRole(claim, minimum) {
|
|
191
|
+
return hasRoleLevel(claim.role, minimum);
|
|
192
|
+
}
|
|
193
|
+
var MIN_CLAIM_SECRET_BYTES = 32;
|
|
194
|
+
function claimSecretProblem(secret) {
|
|
195
|
+
if (!secret) return "TAPEDB_CLAIM_SECRET is not configured.";
|
|
196
|
+
if (new TextEncoder().encode(secret).length < MIN_CLAIM_SECRET_BYTES) {
|
|
197
|
+
return `TAPEDB_CLAIM_SECRET must be at least ${MIN_CLAIM_SECRET_BYTES} bytes; generate one with \`openssl rand -base64 32\`.`;
|
|
198
|
+
}
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// src/engine/permission-shape.ts
|
|
203
|
+
function isViewWhereRule(decision) {
|
|
204
|
+
return typeof decision === "object" && decision !== null && typeof decision.where === "function";
|
|
205
|
+
}
|
|
206
|
+
function assertDecisionShape(namespace, action, decision) {
|
|
207
|
+
if (typeof decision === "number" || typeof decision === "function") return;
|
|
208
|
+
if (isViewWhereRule(decision)) {
|
|
209
|
+
if (action === "view") return;
|
|
210
|
+
throw new Error(
|
|
211
|
+
`"${namespace}.${action}" uses a where rule; where rules are only valid for view.`
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
throw new Error(
|
|
215
|
+
`"${namespace}.${action}" must be a role level, a rule function or { where }.`
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export {
|
|
220
|
+
ENGINE_TABLES,
|
|
221
|
+
NAMESPACES,
|
|
222
|
+
LINKS,
|
|
223
|
+
registryGeneration,
|
|
224
|
+
configureRegistry,
|
|
225
|
+
registryConfigured,
|
|
226
|
+
toSnakeCase,
|
|
227
|
+
findNamespace,
|
|
228
|
+
namespaceTables,
|
|
229
|
+
BASELINE_MIGRATION_ID,
|
|
230
|
+
ENGINE_MIGRATIONS,
|
|
231
|
+
WORKSPACE_MIGRATIONS,
|
|
232
|
+
isEngineMigration,
|
|
233
|
+
configureMigrations,
|
|
234
|
+
isViewWhereRule,
|
|
235
|
+
assertDecisionShape,
|
|
236
|
+
WORKSPACE_ROLE_LEVELS,
|
|
237
|
+
hasRoleLevel,
|
|
238
|
+
hasRole,
|
|
239
|
+
claimSecretProblem
|
|
240
|
+
};
|
|
241
|
+
//# sourceMappingURL=chunk-3AL32Q4K.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/engine/registry.ts","../src/engine/migrations-bundle.ts","../src/claims.ts","../src/engine/permission-shape.ts"],"sourcesContent":["/**\n * Registry mapping model names to workspace SQLite tables.\n *\n * The registry is the runtime contract shared by query compilation, envelope\n * validation, permissions and durability. It is *not* a hardcoded schema: the\n * consumer defines one schema with `defineSchema()` and the Worker hands the\n * resulting registry to `configureRegistry()` before any request is served.\n *\n * Both `NAMESPACES` and `LINKS` are mutated in place rather than reassigned, so\n * modules that imported the binding at load time observe the configured values.\n * A deployment serves exactly one schema, so this configuration is per Worker\n * instance, not per request.\n */\n\nexport type AttributeType =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"date\"\n | \"json\"\n | \"any\";\n\nexport type DeleteRule = \"CASCADE\" | \"SET NULL\" | \"RESTRICT\";\n\nexport interface AttributeReference {\n table: string;\n column: string;\n onDelete?: DeleteRule;\n}\n\nexport interface AttributeDefinition {\n type: AttributeType;\n personal?: { subject: string; required: boolean; defaultValue?: string | number | null };\n optional?: boolean;\n /**\n * Column default, as stored (booleans 0/1, dates epoch ms, json as text).\n * Fills the field for rows written before it existed: replayed inserts and,\n * through the migration, rows already in the table.\n */\n default?: string | number | null;\n indexed?: boolean;\n unique?: boolean;\n references?: AttributeReference;\n}\n\nexport interface NamespaceDefinition {\n apiName: string;\n table: string;\n attributes: Record<string, AttributeDefinition>;\n}\n\nexport interface OneToManyLink {\n apiName: string;\n kind: \"one-to-many\";\n forward: { namespace: string; label: string; has: \"many\" };\n reverse: { namespace: string; label: string; has: \"one\" };\n foreignKey: { namespace: string; attribute: string };\n}\n\nexport interface OneToOneLink {\n apiName: string;\n kind: \"one-to-one\";\n forward: { namespace: string; label: string; has: \"one\" };\n reverse: { namespace: string; label: string; has: \"one\" };\n foreignKey: { namespace: string; attribute: string; unique: true };\n}\n\nexport type LinkDefinition = OneToManyLink | OneToOneLink;\n\n/**\n * Engine-owned tables. `_files` holds file metadata; the rest hold migration\n * state, the transaction log, flush and snapshot bookkeeping, and engine\n * metadata.\n */\nexport const ENGINE_TABLES = {\n migrations: \"_migrations\",\n txLog: \"_tx_log\",\n txReceipts: \"_tx_receipts\",\n txState: \"_tx_state\",\n flushState: \"_flush_state\",\n snapshotState: \"_snapshot_state\",\n engineMeta: \"_engine_meta\",\n files: \"_files\",\n txAudit: \"_tx_audit\",\n} as const;\n\n/** Configured namespaces, keyed by API name. Mutated by `configureRegistry`. */\nexport const NAMESPACES: Record<string, NamespaceDefinition> = {};\n\n/** Configured links, keyed by API name. Mutated by `configureRegistry`. */\nexport const LINKS: Record<string, LinkDefinition> = {};\n\nexport type NamespaceApiName = string;\nexport type LinkApiName = string;\n\nexport interface RegistryDefinition {\n namespaces: readonly NamespaceDefinition[];\n links: readonly LinkDefinition[];\n}\n\nlet configured = false;\nlet generation = 0;\n\n/**\n * Bumped every time the registry is configured. Derived indexes (such as the\n * link-label map in the query compiler) compare against this so they rebuild\n * after the deployment schema is installed, which happens after module load.\n */\nexport function registryGeneration(): number {\n return generation;\n}\n\n/**\n * Installs the deployment schema. Called once per Worker instance, from the\n * Durable Object constructor, before any request is handled.\n */\nexport function configureRegistry(registry: RegistryDefinition): void {\n for (const key of Object.keys(NAMESPACES)) delete NAMESPACES[key];\n for (const key of Object.keys(LINKS)) delete LINKS[key];\n\n for (const namespace of registry.namespaces) {\n NAMESPACES[namespace.apiName] = namespace;\n }\n for (const link of registry.links) {\n LINKS[link.apiName] = link;\n }\n configured = true;\n generation += 1;\n}\n\n/** True once a schema has been installed. Request handling asserts this. */\nexport function registryConfigured(): boolean {\n return configured;\n}\n\nexport function toSnakeCase(value: string): string {\n return value\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .replace(/[-\\s]+/g, \"_\")\n .toLowerCase();\n}\n\nexport function columnFor(\n namespace: NamespaceDefinition,\n attribute: string\n): string | undefined {\n return namespace.attributes[attribute] ? toSnakeCase(attribute) : undefined;\n}\n\nexport function findNamespace(\n apiName: string\n): NamespaceDefinition | undefined {\n return NAMESPACES[apiName];\n}\n\nexport function tableFor(apiName: string): string | undefined {\n return findNamespace(apiName)?.table;\n}\n\nexport function namespaceTables(): string[] {\n return Object.values(NAMESPACES).map((namespace) => namespace.table);\n}\n\nexport function allWorkspaceTables(): string[] {\n return [...Object.values(ENGINE_TABLES), ...namespaceTables()];\n}\n","/**\n * Workspace migrations, in two tracks.\n *\n * The engine track belongs to tapedb: `0001_baseline` (its bookkeeping tables,\n * frozen because deployed workspaces hold its checksum) and every\n * `tapedb_NNNN_*` migration after it. The app track belongs to the deployment:\n * its `NNNN_*` migrations, generated from its schema. Engine migrations run\n * first, so app SQL can rely on the engine's tables as they are now.\n *\n * The configured list is mutated in place by `configureMigrations()` so\n * `migrations.ts` can keep its default-argument shape.\n */\n\nimport type { SchemaChange } from \"./schema-evolution\";\n\nexport interface BundledWorkspaceMigration {\n id: string;\n sql: string;\n /**\n * What this migration changed, for reading data written before it. Not part\n * of the checksum: only the SQL changes a workspace.\n */\n changes?: SchemaChange[];\n}\n\nexport const BASELINE_MIGRATION_ID = \"0001_baseline\";\nexport const ENGINE_MIGRATION_PREFIX = \"tapedb_\";\n\n/** Engine schema changes after the baseline, oldest first. Never edit one; add the next. */\nexport const ENGINE_MIGRATIONS: readonly BundledWorkspaceMigration[] = [\n {\n id: \"tapedb_0002_files_table\",\n sql: 'ALTER TABLE \"$files\" RENAME TO \"_files\";',\n },\n {\n id: \"tapedb_0003_tx_receipts\",\n sql: `CREATE TABLE \"_tx_receipts\" (\n id TEXT PRIMARY KEY NOT NULL,\n seq INTEGER NOT NULL,\n ops_hash TEXT NOT NULL\n );\n INSERT INTO \"_tx_receipts\" (id, seq, ops_hash)\n SELECT client_tx_id, seq, ops_hash FROM \"_tx_log\" WHERE client_tx_id IS NOT NULL;`,\n },\n {\n // Receipts expire with the history retention, so each records when its\n // write was applied. Existing ones take their log row's time, or now.\n id: \"tapedb_0004_receipt_time\",\n sql: `ALTER TABLE \"_tx_receipts\" ADD COLUMN at INTEGER NOT NULL DEFAULT 0;\n UPDATE \"_tx_receipts\" SET at = COALESCE(\n (SELECT l.at FROM \"_tx_log\" l WHERE l.seq = \"_tx_receipts\".seq),\n CAST(strftime('%s', 'now') AS INTEGER) * 1000\n );`,\n },\n {\n // A log entry larger than a row holds keeps its ops in parts: part 0 in\n // _tx_log.ops, the rest here (see tx-log.ts).\n id: \"tapedb_0005_log_parts\",\n sql: `CREATE TABLE \"_tx_log_parts\" (\n seq INTEGER NOT NULL,\n part INTEGER NOT NULL,\n ops TEXT NOT NULL,\n PRIMARY KEY (seq, part)\n ) WITHOUT ROWID;`,\n },\n {\n // Who uploaded a file: the claim subject, for file access rules.\n id: \"tapedb_0006_file_uploader\",\n sql: `ALTER TABLE \"_files\" ADD COLUMN uploaded_by TEXT;`,\n },\n {\n // Socket state past the attachment's 16 KiB, and messages arriving in\n // parts (see socket-state.ts). Ephemeral: never logged or snapshotted.\n id: \"tapedb_0007_socket_state\",\n sql: `CREATE TABLE \"_socket_state\" (\n client_id TEXT NOT NULL,\n part INTEGER NOT NULL,\n data TEXT NOT NULL,\n PRIMARY KEY (client_id, part)\n ) WITHOUT ROWID;\n CREATE TABLE \"_socket_parts\" (\n client_id TEXT NOT NULL,\n id TEXT NOT NULL,\n idx INTEGER NOT NULL,\n data TEXT NOT NULL,\n PRIMARY KEY (client_id, id, idx)\n ) WITHOUT ROWID;`,\n },\n {\n // Old engines may have deleted receipts. Preserve known keys and set a\n // fixed safety boundary for unknown pre-upgrade requests in used rooms.\n id: \"tapedb_0008_permanent_receipts\",\n sql: `ALTER TABLE \"_tx_receipts\" RENAME TO \"_tx_receipts_old\";\n CREATE TABLE \"_tx_receipts\" (\n id TEXT PRIMARY KEY NOT NULL,\n seq INTEGER NOT NULL,\n ops_hash TEXT,\n at INTEGER NOT NULL\n );\n INSERT INTO \"_tx_receipts\" SELECT id, seq, ops_hash, at FROM \"_tx_receipts_old\";\n DROP TABLE \"_tx_receipts_old\";\n CREATE INDEX \"_tx_receipts_hash_age\" ON \"_tx_receipts\" (at) WHERE ops_hash IS NOT NULL;\n INSERT OR REPLACE INTO \"_engine_meta\" (\"key\", value)\n SELECT 'receipts_since', CAST(MAX(\n COALESCE((SELECT CAST(value AS INTEGER) FROM \"_engine_meta\" WHERE \"key\" = 'receipts_since'), 0),\n CAST(strftime('%s', 'now') AS INTEGER) * 1000 + CAST(substr(strftime('%f', 'now'), 4, 3) AS INTEGER)\n ) AS TEXT) WHERE EXISTS (SELECT 1 FROM \"_tx_state\" WHERE high_water_seq > 0);`,\n },\n {\n // Recent topic messages, for clients rejoining after a reconnect.\n // Ephemeral like the sockets: never logged, snapshotted or exported.\n id: \"tapedb_0009_topic_buffer\",\n sql: `CREATE TABLE \"_topic_buffer\" (\n topic TEXT NOT NULL,\n seq INTEGER NOT NULL,\n at INTEGER NOT NULL,\n frame TEXT NOT NULL,\n PRIMARY KEY (topic, seq)\n ) WITHOUT ROWID;\n CREATE TABLE \"_topic_seq\" (\n topic TEXT PRIMARY KEY NOT NULL,\n seq INTEGER NOT NULL\n ) WITHOUT ROWID;`,\n },\n {\n // Opt-in write audit (audit.ts): who changed each row, pruned by age.\n id: \"tapedb_0010_tx_audit\",\n sql: `CREATE TABLE \"_tx_audit\" (\n -- table, row and sequence in one key, for snapshot paging.\n id TEXT PRIMARY KEY NOT NULL,\n table_name TEXT NOT NULL,\n row_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n at INTEGER NOT NULL,\n user_id TEXT,\n role INTEGER,\n action TEXT NOT NULL\n ) WITHOUT ROWID;\n CREATE INDEX \"_tx_audit_row\" ON \"_tx_audit\" (table_name, row_id, seq);\n CREATE INDEX \"_tx_audit_at\" ON \"_tx_audit\" (at);`,\n },\n];\n\n/** Configured migrations, applied in order on Durable Object boot. */\nexport const WORKSPACE_MIGRATIONS: BundledWorkspaceMigration[] = [];\n\nexport function isEngineMigration(id: string): boolean {\n return id === BASELINE_MIGRATION_ID || id.startsWith(ENGINE_MIGRATION_PREFIX);\n}\n\n/**\n * Installs the deployment's migrations. Engine migrations are always the\n * package's own: a deployment bundle that carries copies of them (as one\n * generated by an older tapedb does) is normalised, so the engine track can\n * grow without regenerating every app's bundle.\n */\nexport function configureMigrations(\n migrations: readonly BundledWorkspaceMigration[]\n): void {\n const baseline = migrations.find((migration) => migration.id === BASELINE_MIGRATION_ID);\n if (!baseline) {\n throw new Error(`Migrations must include ${BASELINE_MIGRATION_ID}.`);\n }\n const app = migrations.filter((migration) => !isEngineMigration(migration.id));\n\n WORKSPACE_MIGRATIONS.length = 0;\n WORKSPACE_MIGRATIONS.push(baseline, ...ENGINE_MIGRATIONS, ...app);\n}\n","/**\n * Shared role-claim contract between the Worker (JWT verification) and the\n * workspace engine (permission checks).\n * consumes this shape.\n */\n\nexport const WORKSPACE_ROLE_LEVELS = {\n GUEST: 0,\n USER: 1,\n MEMBER: 2,\n EDITOR: 3,\n MODERATOR: 4,\n ADMIN: 5,\n OWNER: 6,\n FOUNDER: 7,\n DEVELOPER: 8,\n} as const;\n\nexport type WorkspaceRole =\n (typeof WORKSPACE_ROLE_LEVELS)[keyof typeof WORKSPACE_ROLE_LEVELS];\n\nexport interface RoleClaim {\n /** Platform user id. */\n sub: string;\n /** Platform workspace id (the DO name). */\n workspaceId: string;\n /** Numeric workspace role level. */\n role: WorkspaceRole;\n /** Expiry, seconds since epoch. */\n exp: number;\n /** Issued at, seconds since epoch. */\n iat: number;\n iss?: string;\n aud?: string;\n}\n\nexport function hasRoleLevel(\n role: WorkspaceRole,\n minimum: WorkspaceRole\n): boolean {\n return role >= minimum;\n}\n\nexport function hasRole(claim: RoleClaim, minimum: WorkspaceRole): boolean {\n return hasRoleLevel(claim.role, minimum);\n}\n\n/**\n * Shortest accepted `TAPEDB_CLAIM_SECRET`, in bytes. HS256 keys need at\n * least the hash's 256 bits (RFC 7518, section 3.2); a shorter secret can be\n * found offline from any one claim, and then claims can be forged.\n */\nexport const MIN_CLAIM_SECRET_BYTES = 32;\n\n/** Why `secret` cannot sign or verify claims, or null when it can. */\nexport function claimSecretProblem(secret: string | undefined): string | null {\n if (!secret) return \"TAPEDB_CLAIM_SECRET is not configured.\";\n if (new TextEncoder().encode(secret).length < MIN_CLAIM_SECRET_BYTES) {\n return `TAPEDB_CLAIM_SECRET must be at least ${MIN_CLAIM_SECRET_BYTES} bytes; generate one with \\`openssl rand -base64 32\\`.`;\n }\n return null;\n}\n","/**\n * Shape checks for permission decisions.\n *\n * Kept free of engine imports: `defineSchema` runs in the client entry too,\n * and validating a schema must not pull the engine into a browser bundle.\n */\n\n/** A `{ where }` view rule, recognised structurally. */\nexport function isViewWhereRule(\n decision: unknown\n): decision is { where: (...args: never[]) => unknown } {\n return (\n typeof decision === \"object\" &&\n decision !== null &&\n typeof (decision as { where?: unknown }).where === \"function\"\n );\n}\n\n/** Throws when a decision is not valid for its action. */\nexport function assertDecisionShape(\n namespace: string,\n action: string,\n decision: unknown\n): void {\n if (typeof decision === \"number\" || typeof decision === \"function\") return;\n if (isViewWhereRule(decision)) {\n if (action === \"view\") return;\n // A where rule on a write would be skipped by the row-rule pass, which\n // only evaluates functions: refusing it here is what keeps it from\n // silently allowing every write.\n throw new Error(\n `\"${namespace}.${action}\" uses a where rule; where rules are only valid for view.`\n );\n }\n throw new Error(\n `\"${namespace}.${action}\" must be a role level, a rule function or { where }.`\n );\n}\n"],"mappings":"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","names":[]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// src/socket-protocol.ts
|
|
2
|
+
var SOCKET_PROTOCOL = "tapedb";
|
|
3
|
+
var CLAIM_PROTOCOL_PREFIX = "tapedb.claim.";
|
|
4
|
+
function socketProtocols(token) {
|
|
5
|
+
return [SOCKET_PROTOCOL, `${CLAIM_PROTOCOL_PREFIX}${token}`];
|
|
6
|
+
}
|
|
7
|
+
function offeredProtocols(header) {
|
|
8
|
+
if (header === null) return [];
|
|
9
|
+
return header.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
|
|
10
|
+
}
|
|
11
|
+
function claimFromProtocols(header) {
|
|
12
|
+
const entry = offeredProtocols(header).find((part) => part.startsWith(CLAIM_PROTOCOL_PREFIX));
|
|
13
|
+
const token = entry?.slice(CLAIM_PROTOCOL_PREFIX.length) ?? "";
|
|
14
|
+
return token.length > 0 ? token : null;
|
|
15
|
+
}
|
|
16
|
+
var MAX_SOCKET_MESSAGE_BYTES = 4 * 1024 * 1024;
|
|
17
|
+
var MAX_SOCKET_PENDING_BYTES = 8 * 1024 * 1024;
|
|
18
|
+
var MAX_ROOM_PENDING_BYTES = 32 * 1024 * 1024;
|
|
19
|
+
var MAX_SOCKET_PENDING_MESSAGES = 8;
|
|
20
|
+
var MAX_SOCKET_MESSAGE_PARTS = 1024;
|
|
21
|
+
|
|
22
|
+
export {
|
|
23
|
+
SOCKET_PROTOCOL,
|
|
24
|
+
socketProtocols,
|
|
25
|
+
offeredProtocols,
|
|
26
|
+
claimFromProtocols,
|
|
27
|
+
MAX_SOCKET_MESSAGE_BYTES,
|
|
28
|
+
MAX_SOCKET_PENDING_BYTES,
|
|
29
|
+
MAX_ROOM_PENDING_BYTES,
|
|
30
|
+
MAX_SOCKET_PENDING_MESSAGES,
|
|
31
|
+
MAX_SOCKET_MESSAGE_PARTS
|
|
32
|
+
};
|
|
33
|
+
//# sourceMappingURL=chunk-CYDXFAEB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/socket-protocol.ts"],"sourcesContent":["/**\n * How the WebSocket upgrade carries the role claim. Browsers cannot set an\n * `Authorization` header on an upgrade, so the client offers two subprotocols:\n * `tapedb`, which the room selects, and `tapedb.claim.<jwt>`, which carries\n * the token. A JWT's characters are all valid in a protocol token. Unlike a\n * query parameter, a header does not end up in URLs, request logs or the\n * browser's history.\n */\nexport const SOCKET_PROTOCOL = \"tapedb\";\nexport const CLAIM_PROTOCOL_PREFIX = \"tapedb.claim.\";\n\n/** The subprotocols a client offers for `token`. */\nexport function socketProtocols(token: string): string[] {\n return [SOCKET_PROTOCOL, `${CLAIM_PROTOCOL_PREFIX}${token}`];\n}\n\n/** The offered subprotocols in a `Sec-WebSocket-Protocol` header. */\nexport function offeredProtocols(header: string | null): string[] {\n if (header === null) return [];\n return header.split(\",\").map((part) => part.trim()).filter((part) => part.length > 0);\n}\n\n/** The claim token carried in the offered subprotocols, if any. */\nexport function claimFromProtocols(header: string | null): string | null {\n const entry = offeredProtocols(header).find((part) => part.startsWith(CLAIM_PROTOCOL_PREFIX));\n const token = entry?.slice(CLAIM_PROTOCOL_PREFIX.length) ?? \"\";\n return token.length > 0 ? token : null;\n}\n\n/** Bounds complete JSON messages assembled in memory, including broadcasts. */\nexport const MAX_SOCKET_MESSAGE_BYTES = 4 * 1024 * 1024;\nexport const MAX_SOCKET_PENDING_BYTES = 8 * 1024 * 1024;\nexport const MAX_ROOM_PENDING_BYTES = 32 * 1024 * 1024;\nexport const MAX_SOCKET_PENDING_MESSAGES = 8;\nexport const MAX_SOCKET_MESSAGE_PARTS = 1024;\n"],"mappings":";AAQO,IAAM,kBAAkB;AACxB,IAAM,wBAAwB;AAG9B,SAAS,gBAAgB,OAAyB;AACvD,SAAO,CAAC,iBAAiB,GAAG,qBAAqB,GAAG,KAAK,EAAE;AAC7D;AAGO,SAAS,iBAAiB,QAAiC;AAChE,MAAI,WAAW,KAAM,QAAO,CAAC;AAC7B,SAAO,OAAO,MAAM,GAAG,EAAE,IAAI,CAAC,SAAS,KAAK,KAAK,CAAC,EAAE,OAAO,CAAC,SAAS,KAAK,SAAS,CAAC;AACtF;AAGO,SAAS,mBAAmB,QAAsC;AACvE,QAAM,QAAQ,iBAAiB,MAAM,EAAE,KAAK,CAAC,SAAS,KAAK,WAAW,qBAAqB,CAAC;AAC5F,QAAM,QAAQ,OAAO,MAAM,sBAAsB,MAAM,KAAK;AAC5D,SAAO,MAAM,SAAS,IAAI,QAAQ;AACpC;AAGO,IAAM,2BAA2B,IAAI,OAAO;AAC5C,IAAM,2BAA2B,IAAI,OAAO;AAC5C,IAAM,yBAAyB,KAAK,OAAO;AAC3C,IAAM,8BAA8B;AACpC,IAAM,2BAA2B;","names":[]}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// src/client/stable.ts
|
|
2
|
+
function stableStringify(value) {
|
|
3
|
+
if (value === null || typeof value !== "object") {
|
|
4
|
+
return JSON.stringify(value) ?? "null";
|
|
5
|
+
}
|
|
6
|
+
if (Array.isArray(value)) {
|
|
7
|
+
return `[${value.map((item) => stableStringify(item)).join(",")}]`;
|
|
8
|
+
}
|
|
9
|
+
const record = value;
|
|
10
|
+
const keys = Object.keys(record).sort();
|
|
11
|
+
return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(",")}}`;
|
|
12
|
+
}
|
|
13
|
+
function cloneJson(value) {
|
|
14
|
+
if (typeof structuredClone === "function") {
|
|
15
|
+
try {
|
|
16
|
+
return structuredClone(value);
|
|
17
|
+
} catch {
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return JSON.parse(JSON.stringify(value));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export {
|
|
24
|
+
stableStringify,
|
|
25
|
+
cloneJson
|
|
26
|
+
};
|
|
27
|
+
//# sourceMappingURL=chunk-UYZJAMBR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client/stable.ts"],"sourcesContent":["/** Small serialisation helpers shared by the cache and outbox. */\n\n/**\n * Deterministic JSON serialisation so two queries with the same shape share a\n * cache entry and subscription regardless of property order.\n */\nexport function stableStringify(value: unknown): string {\n if (value === null || typeof value !== \"object\") {\n return JSON.stringify(value) ?? \"null\";\n }\n if (Array.isArray(value)) {\n return `[${value.map((item) => stableStringify(item)).join(\",\")}]`;\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record).sort();\n return `{${keys\n .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)\n .join(\",\")}}`;\n}\n\n/**\n * Deep-clones JSON-shaped data. `structuredClone` is used when available; the\n * fallback covers older runtimes and test doubles.\n */\nexport function cloneJson<T>(value: T): T {\n if (typeof structuredClone === \"function\") {\n try {\n return structuredClone(value);\n } catch {\n // Fall through to JSON. Data from the engine is JSON-shaped.\n }\n }\n return JSON.parse(JSON.stringify(value)) as T;\n}\n"],"mappings":";AAMO,SAAS,gBAAgB,OAAwB;AACtD,MAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;AAC/C,WAAO,KAAK,UAAU,KAAK,KAAK;AAAA,EAClC;AACA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,IAAI,MAAM,IAAI,CAAC,SAAS,gBAAgB,IAAI,CAAC,EAAE,KAAK,GAAG,CAAC;AAAA,EACjE;AAEA,QAAM,SAAS;AACf,QAAM,OAAO,OAAO,KAAK,MAAM,EAAE,KAAK;AACtC,SAAO,IAAI,KACR,IAAI,CAAC,QAAQ,GAAG,KAAK,UAAU,GAAG,CAAC,IAAI,gBAAgB,OAAO,GAAG,CAAC,CAAC,EAAE,EACrE,KAAK,GAAG,CAAC;AACd;AAMO,SAAS,UAAa,OAAa;AACxC,MAAI,OAAO,oBAAoB,YAAY;AACzC,QAAI;AACF,aAAO,gBAAgB,KAAK;AAAA,IAC9B,QAAQ;AAAA,IAER;AAAA,EACF;AACA,SAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AACzC;","names":[]}
|