@tldraw/store 5.5.2 → 5.6.0-canary.035b741dc331

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.
@@ -444,6 +444,22 @@ describe('getMigrationsSince (MG)', () => {
444
444
  expect(result.error).toBe('Incompatible schema?')
445
445
  })
446
446
 
447
+ it('[MG5] a persisted version that is present but not a number is an error', () => {
448
+ for (const retroactive of [true, false]) {
449
+ const foo = mockSequence({ id: 'foo', retroactive, versions: 2 })
450
+ const schema = StoreSchema.create({}, { migrations: [foo] })
451
+
452
+ for (const version of [null, '2', '0']) {
453
+ const result = schema.getMigrationsSince({
454
+ schemaVersion: 2,
455
+ sequences: { foo: version as any },
456
+ })
457
+ assert(!result.ok)
458
+ expect(result.error).toBe('Incompatible schema?')
459
+ }
460
+ }
461
+ })
462
+
447
463
  it('[MG6] results are cached per persisted-schema object identity', () => {
448
464
  const schema = makeSchema([mockSequence({ id: 'foo', retroactive: true, versions: 2 })])
449
465
  const oldSchema = schema.serializeEarliestVersion()
@@ -1107,3 +1123,65 @@ describe('migrateStorage (MA)', () => {
1107
1123
  expect(result.value[newRecord.id as keyof typeof result.value]).toMatchObject({ name: 'new' })
1108
1124
  })
1109
1125
  })
1126
+
1127
+ describe('malformed persisted schemas (SC, MA)', () => {
1128
+ const schema = StoreSchema.create<Book>(
1129
+ { book: Book },
1130
+ {
1131
+ migrations: [
1132
+ createMigrationSequence({
1133
+ sequenceId: 'com.tldraw.book',
1134
+ sequence: [{ id: 'com.tldraw.book/1', scope: 'record', up: () => {} }],
1135
+ }),
1136
+ ],
1137
+ }
1138
+ )
1139
+
1140
+ it('[SC5] schemas with a missing version or collections produce an error result, not a throw', () => {
1141
+ expect(upgradeSchema({} as any).ok).toBe(false)
1142
+ expect(upgradeSchema({ schemaVersion: 2 } as any).ok).toBe(false)
1143
+ expect(upgradeSchema({ schemaVersion: 1 } as any).ok).toBe(false)
1144
+ expect(upgradeSchema(null as any).ok).toBe(false)
1145
+ })
1146
+
1147
+ it('[MA6] migrateStoreSnapshot reports malformed schemas as a migration error', () => {
1148
+ for (const bad of [{}, { schemaVersion: 2 }, { schemaVersion: 1, recordVersions: null }]) {
1149
+ expect(schema.migrateStoreSnapshot({ store: {}, schema: bad as any })).toEqual({
1150
+ type: 'error',
1151
+ reason: 'migration-error',
1152
+ })
1153
+ }
1154
+ })
1155
+
1156
+ it('[MG3] a persisted sequence named after an Object.prototype member is just unknown', () => {
1157
+ const persisted = { schemaVersion: 2, sequences: { constructor: 1, 'com.tldraw.book': 1 } }
1158
+ expect(schema.getMigrationsSince(persisted as any)).toEqual({ ok: true, value: [] })
1159
+ })
1160
+ })
1161
+
1162
+ describe('malformed v1 schemas (SC)', () => {
1163
+ it('[SC5] a v1 schema with a malformed record entry produces an error result', () => {
1164
+ expect(
1165
+ upgradeSchema({ schemaVersion: 1, storeVersion: 1, recordVersions: { book: null } } as any).ok
1166
+ ).toBe(false)
1167
+ expect(
1168
+ upgradeSchema({
1169
+ schemaVersion: 1,
1170
+ storeVersion: 1,
1171
+ recordVersions: { book: { version: 1, subTypeKey: 'type', subTypeVersions: null } },
1172
+ } as any).ok
1173
+ ).toBe(false)
1174
+ })
1175
+ })
1176
+
1177
+ describe('non-object persisted schemas (MA)', () => {
1178
+ it('[MA6] a missing schema is a migration error, not a throw', () => {
1179
+ const schema = StoreSchema.create<Book>({ book: Book })
1180
+ for (const bad of [undefined, null, 'v2', 3]) {
1181
+ expect(schema.migrateStoreSnapshot({ store: {}, schema: bad as any })).toEqual({
1182
+ type: 'error',
1183
+ reason: 'migration-error',
1184
+ })
1185
+ }
1186
+ })
1187
+ })
@@ -123,6 +123,10 @@ export interface SerializedSchemaV2 {
123
123
  */
124
124
  export type SerializedSchema = SerializedSchemaV1 | SerializedSchemaV2
125
125
 
126
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
127
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
128
+ }
129
+
126
130
  /**
127
131
  * Upgrades a serialized schema from version 1 to version 2 format.
128
132
  *
@@ -153,8 +157,15 @@ export type SerializedSchema = SerializedSchemaV1 | SerializedSchemaV2
153
157
  * @public
154
158
  */
155
159
  export function upgradeSchema(schema: SerializedSchema): Result<SerializedSchemaV2, string> {
156
- if (schema.schemaVersion > 2 || schema.schemaVersion < 1) return Result.err('Bad schema version')
157
- if (schema.schemaVersion === 2) return Result.ok(schema as SerializedSchemaV2)
160
+ // Persisted schemas are untrusted input: check the shape rather than crash on a missing or
161
+ // malformed `sequences`/`recordVersions` further down.
162
+ if (!isPlainRecord(schema)) return Result.err('Bad schema')
163
+ if (schema.schemaVersion === 2) {
164
+ if (!isPlainRecord(schema.sequences)) return Result.err('Bad schema: missing sequences')
165
+ return Result.ok(schema)
166
+ }
167
+ if (schema.schemaVersion !== 1) return Result.err('Bad schema version')
168
+ if (!isPlainRecord(schema.recordVersions)) return Result.err('Bad schema: missing recordVersions')
158
169
  const result: SerializedSchemaV2 = {
159
170
  schemaVersion: 2,
160
171
  sequences: {
@@ -163,8 +174,12 @@ export function upgradeSchema(schema: SerializedSchema): Result<SerializedSchema
163
174
  }
164
175
 
165
176
  for (const [typeName, recordVersion] of Object.entries(schema.recordVersions)) {
177
+ if (!isPlainRecord(recordVersion)) return Result.err('Bad schema: malformed recordVersions')
166
178
  result.sequences[`com.tldraw.${typeName}`] = recordVersion.version
167
179
  if ('subTypeKey' in recordVersion) {
180
+ if (!isPlainRecord(recordVersion.subTypeVersions)) {
181
+ return Result.err('Bad schema: malformed subTypeVersions')
182
+ }
168
183
  for (const [subType, version] of Object.entries(recordVersion.subTypeVersions)) {
169
184
  result.sequences[`com.tldraw.${typeName}.${subType}`] = version
170
185
  }
@@ -425,6 +440,10 @@ export class StoreSchema<R extends UnknownRecord, P = unknown> {
425
440
  public getMigrationsSince(persistedSchema: SerializedSchema): Result<Migration[], string> {
426
441
  // Every result — success, empty, or error — is cached, so cache once around the whole
427
442
  // computation rather than at each of its exit points.
443
+ // A non-object schema (see upgradeSchema) cannot be a WeakMap key; its error result is cheap
444
+ // to recompute.
445
+ if (!isPlainRecord(persistedSchema)) return this.computeMigrationsSince(persistedSchema)
446
+
428
447
  const cached = this.migrationCache.get(persistedSchema)
429
448
  if (cached) {
430
449
  return cached
@@ -442,8 +461,11 @@ export class StoreSchema<R extends UnknownRecord, P = unknown> {
442
461
  }
443
462
  const schema = upgradeResult.value
444
463
  const sequenceIdsToInclude = new Set(
445
- // start with any shared sequences
446
- Object.keys(schema.sequences).filter((sequenceId) => this.migrations[sequenceId])
464
+ // start with any shared sequences. Own-property lookups: a persisted sequence id like
465
+ // 'constructor' must not resolve to an Object.prototype member.
466
+ Object.keys(schema.sequences).filter((sequenceId) =>
467
+ getOwnProperty(this.migrations, sequenceId)
468
+ )
447
469
  )
448
470
 
449
471
  // also include any sequences that are not in the persisted schema but are marked as postHoc
@@ -460,8 +482,13 @@ export class StoreSchema<R extends UnknownRecord, P = unknown> {
460
482
  const allMigrationsToInclude = new Set<MigrationId>()
461
483
  for (const sequenceId of sequenceIdsToInclude) {
462
484
  const theirVersion = schema.sequences[sequenceId]
485
+ // Only a missing version means "never applied"; rerunning migrations on data that may
486
+ // already be migrated would corrupt it.
487
+ if (theirVersion !== undefined && typeof theirVersion !== 'number') {
488
+ return Result.err('Incompatible schema?')
489
+ }
463
490
  if (
464
- (typeof theirVersion !== 'number' && this.migrations[sequenceId].retroactive) ||
491
+ (theirVersion === undefined && this.migrations[sequenceId].retroactive) ||
465
492
  theirVersion === 0
466
493
  ) {
467
494
  for (const migration of this.migrations[sequenceId].sequence) {
@@ -548,8 +575,8 @@ export class StoreSchema<R extends UnknownRecord, P = unknown> {
548
575
  migrationsToApply = migrationsToApply.slice().reverse()
549
576
  }
550
577
 
551
- record = structuredClone(record)
552
578
  try {
579
+ record = structuredClone(record)
553
580
  for (const migration of migrationsToApply) {
554
581
  if (migration.scope === 'store') throw new Error(/* won't happen, just for TS */)
555
582
  if (migration.scope === 'storage') throw new Error(/* won't happen, just for TS */)
@@ -683,14 +710,15 @@ export class StoreSchema<R extends UnknownRecord, P = unknown> {
683
710
  if (migrationsToApply.length === 0) {
684
711
  return { type: 'success', value: snapshot.store }
685
712
  }
686
- const store = Object.assign(
687
- new Map<string, R>(objectMapEntries(snapshot.store).map(devFreeze)),
688
- {
689
- getSchema: () => snapshot.schema,
690
- setSchema: (_: SerializedSchema) => {},
691
- }
692
- )
693
713
  try {
714
+ // devFreeze throws for non-plain values, which is a migration failure like any other
715
+ const store = Object.assign(
716
+ new Map<string, R>(objectMapEntries(snapshot.store).map(devFreeze)),
717
+ {
718
+ getSchema: () => snapshot.schema,
719
+ setSchema: (_: SerializedSchema) => {},
720
+ }
721
+ )
694
722
  this.migrateStorage(store)
695
723
  if (opts?.mutateInputStore) {
696
724
  for (const [id, record] of store.entries()) {