@chipmobilesdk/rn-local-db 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/CHANGELOG.md +52 -0
- package/README.md +726 -0
- package/package.json +61 -0
- package/src/adapter/budgets.ts +67 -0
- package/src/adapter/collection.ts +298 -0
- package/src/adapter/deletion.ts +238 -0
- package/src/adapter/index.ts +68 -0
- package/src/adapter/lifecycle.ts +444 -0
- package/src/adapter/transaction.ts +65 -0
- package/src/artifacts/availability.ts +69 -0
- package/src/artifacts/cascade.ts +78 -0
- package/src/artifacts/paths.ts +29 -0
- package/src/artifacts/reconcile.ts +63 -0
- package/src/artifacts/store.ts +323 -0
- package/src/contract/adapter.ts +78 -0
- package/src/contract/attachment.ts +72 -0
- package/src/contract/backup.ts +28 -0
- package/src/contract/config.ts +54 -0
- package/src/contract/encryption.ts +34 -0
- package/src/contract/errors.ts +76 -0
- package/src/contract/migration.ts +40 -0
- package/src/contract/query.ts +81 -0
- package/src/contract/record.ts +42 -0
- package/src/contract/schema.ts +36 -0
- package/src/contract/scope.ts +36 -0
- package/src/contract/transaction.ts +46 -0
- package/src/crypto/chunked-cipher.ts +144 -0
- package/src/crypto/derive.ts +63 -0
- package/src/crypto/key-provider.ts +78 -0
- package/src/crypto/provider.ts +81 -0
- package/src/diagnostics/dev-log.ts +108 -0
- package/src/diagnostics/errors.ts +66 -0
- package/src/diagnostics/faults.ts +64 -0
- package/src/diagnostics/map-native.ts +106 -0
- package/src/diagnostics/redact.ts +141 -0
- package/src/index.ts +110 -0
- package/src/migration/executor.ts +136 -0
- package/src/migration/ledger.ts +97 -0
- package/src/migration/validate-chain.ts +65 -0
- package/src/platform/backup-android-verify.ts +88 -0
- package/src/platform/backup-ios.ts +48 -0
- package/src/platform/fs.ts +89 -0
- package/src/platform/location.ts +135 -0
- package/src/query/budgets.ts +57 -0
- package/src/query/compare.ts +91 -0
- package/src/query/cursor.ts +99 -0
- package/src/query/filter.ts +82 -0
- package/src/query/paginate.ts +51 -0
- package/src/query/sort.ts +56 -0
- package/src/query/validate.ts +171 -0
- package/src/schema/declare.ts +45 -0
- package/src/schema/validate-config.ts +158 -0
- package/src/scope/hash.ts +134 -0
- package/src/scope/normalize.ts +90 -0
- package/src/scope/validate.ts +83 -0
- package/src/sqlite/adapter.ts +26 -0
- package/src/sqlite/batch.ts +232 -0
- package/src/sqlite/catalog.ts +108 -0
- package/src/sqlite/connection.ts +205 -0
- package/src/sqlite/index-coverage.ts +53 -0
- package/src/sqlite/native.ts +83 -0
- package/src/sqlite/row-codec.ts +201 -0
- package/src/sqlite/sql-builder.ts +244 -0
- package/src/sqlite/transactions.ts +33 -0
- package/src/sqlite/values.ts +24 -0
- package/src/testing/conformance/attachments.ts +136 -0
- package/src/testing/conformance/encryption.ts +150 -0
- package/src/testing/conformance/index.ts +161 -0
- package/src/testing/conformance/lifecycle.ts +99 -0
- package/src/testing/conformance/migrations.ts +177 -0
- package/src/testing/conformance/queries.ts +167 -0
- package/src/testing/conformance/records.ts +169 -0
- package/src/testing/conformance/scopes.ts +88 -0
- package/src/testing/conformance/transactions.ts +149 -0
- package/src/testing/faults.ts +21 -0
- package/src/testing/index.ts +21 -0
- package/src/testing/memory-adapter/collection.ts +219 -0
- package/src/testing/memory-adapter/index.ts +388 -0
- package/src/testing/memory-adapter/migrations.ts +119 -0
- package/src/testing/memory-adapter/reset.ts +50 -0
- package/src/testing/memory-adapter/store.ts +134 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@chipmobilesdk/rn-local-db`
|
|
3
|
+
*
|
|
4
|
+
* Offline-first, scope-isolated local storage for ChipMobileSdk apps.
|
|
5
|
+
*
|
|
6
|
+
* What is deliberately absent is part of the contract: there is no
|
|
7
|
+
* `switchScope`, and no read, write, or query operation accepts a scope
|
|
8
|
+
* argument. Scope is bound to a handle at open time and immutable, so a
|
|
9
|
+
* cross-scope leak is not expressible rather than merely prevented.
|
|
10
|
+
*
|
|
11
|
+
* The underlying engine, the physical layout, key material, and the query
|
|
12
|
+
* translation are private and unreachable by deep import.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
// Lifecycle
|
|
16
|
+
export {
|
|
17
|
+
deleteDatabase,
|
|
18
|
+
deleteScopeData,
|
|
19
|
+
openDatabase,
|
|
20
|
+
resetScope,
|
|
21
|
+
} from './adapter';
|
|
22
|
+
|
|
23
|
+
// Diagnostics
|
|
24
|
+
export {
|
|
25
|
+
DiagnosticCodes,
|
|
26
|
+
StorageError,
|
|
27
|
+
isCode,
|
|
28
|
+
isStorageError,
|
|
29
|
+
} from './diagnostics/errors';
|
|
30
|
+
export { setDiagnosticLogger, type DiagnosticLogger } from './diagnostics/dev-log';
|
|
31
|
+
|
|
32
|
+
// Budgets, so a consumer can check before it writes rather than after
|
|
33
|
+
export { Budgets } from './contract/config';
|
|
34
|
+
|
|
35
|
+
// Contract types
|
|
36
|
+
export type {
|
|
37
|
+
DatabaseConfig,
|
|
38
|
+
DatabaseTargetConfig,
|
|
39
|
+
ScopeTargetConfig,
|
|
40
|
+
} from './contract/config';
|
|
41
|
+
export type {
|
|
42
|
+
ResolvedScope,
|
|
43
|
+
ScopeDescriptor,
|
|
44
|
+
ScopeKind,
|
|
45
|
+
} from './contract/scope';
|
|
46
|
+
export type {
|
|
47
|
+
CollectionSchema,
|
|
48
|
+
FieldDeclaration,
|
|
49
|
+
FieldType,
|
|
50
|
+
IndexDeclaration,
|
|
51
|
+
} from './contract/schema';
|
|
52
|
+
export type {
|
|
53
|
+
RecordInput,
|
|
54
|
+
StorableRecordData,
|
|
55
|
+
StorableValue,
|
|
56
|
+
StoredRecord,
|
|
57
|
+
WriteOperation,
|
|
58
|
+
WriteOutcome,
|
|
59
|
+
} from './contract/record';
|
|
60
|
+
export type {
|
|
61
|
+
ComparisonNode,
|
|
62
|
+
FilterNode,
|
|
63
|
+
FilterValue,
|
|
64
|
+
IndexCoverageReport,
|
|
65
|
+
LogicalNode,
|
|
66
|
+
PageRequest,
|
|
67
|
+
Query,
|
|
68
|
+
ResultPage,
|
|
69
|
+
SortDirection,
|
|
70
|
+
SortKey,
|
|
71
|
+
} from './contract/query';
|
|
72
|
+
export type {
|
|
73
|
+
BatchOperation,
|
|
74
|
+
BatchOutcome,
|
|
75
|
+
CollectionOps,
|
|
76
|
+
Transaction,
|
|
77
|
+
} from './contract/transaction';
|
|
78
|
+
export type {
|
|
79
|
+
Migration,
|
|
80
|
+
MigrationContext,
|
|
81
|
+
MigrationFailureDetail,
|
|
82
|
+
MigrationLedgerEntry,
|
|
83
|
+
MigrationOutcome,
|
|
84
|
+
} from './contract/migration';
|
|
85
|
+
export type {
|
|
86
|
+
AttachmentAvailability,
|
|
87
|
+
AttachmentAvailabilityState,
|
|
88
|
+
AttachmentInput,
|
|
89
|
+
AttachmentOwner,
|
|
90
|
+
AttachmentReference,
|
|
91
|
+
ByteRange,
|
|
92
|
+
DeletionOutcome,
|
|
93
|
+
ReconciliationReport,
|
|
94
|
+
} from './contract/attachment';
|
|
95
|
+
export type {
|
|
96
|
+
EncryptionConfig,
|
|
97
|
+
EncryptionPosture,
|
|
98
|
+
KeyProvider,
|
|
99
|
+
} from './contract/encryption';
|
|
100
|
+
export type {
|
|
101
|
+
BackupConfig,
|
|
102
|
+
BackupPostureValue,
|
|
103
|
+
EffectivePosture,
|
|
104
|
+
} from './contract/backup';
|
|
105
|
+
export type { DiagnosticCode } from './contract/errors';
|
|
106
|
+
export type {
|
|
107
|
+
Attachments,
|
|
108
|
+
DatabaseHandle,
|
|
109
|
+
StorageAdapter,
|
|
110
|
+
} from './contract/adapter';
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The migration executor.
|
|
3
|
+
*
|
|
4
|
+
* Four rules, each of which exists because the alternative loses data:
|
|
5
|
+
*
|
|
6
|
+
* - **Ascending, and pending only.** A migration whose version is at or below
|
|
7
|
+
* the recorded one has already run against this scope (FR-047, FR-049).
|
|
8
|
+
* - **One transaction per migration.** A failure unwinds that migration and
|
|
9
|
+
* nothing else, so the recorded version and the data always agree.
|
|
10
|
+
* - **The recorded version moves only on success**, inside the same
|
|
11
|
+
* transaction as the migration's own writes. Writing it separately would
|
|
12
|
+
* leave a window where a crash records a migration that did not happen.
|
|
13
|
+
* - **A failure returns no handle** (FR-050). Half-migrated data behind a
|
|
14
|
+
* working handle is the failure this whole design exists to prevent, and it
|
|
15
|
+
* is worse than being unable to open at all: the app writes to it.
|
|
16
|
+
*
|
|
17
|
+
* A retry starts from the same version rather than skipping ahead (FR-051),
|
|
18
|
+
* which is what makes a transient failure — a locked keychain, a full disk
|
|
19
|
+
* mid-migration — recoverable on the next launch instead of permanent.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import type { DatabaseConfig } from '../contract/config';
|
|
23
|
+
import { DiagnosticCodes } from '../contract/errors';
|
|
24
|
+
import type { MigrationContext } from '../contract/migration';
|
|
25
|
+
import type { StorableRecordData } from '../contract/record';
|
|
26
|
+
import type { CollectionSchema } from '../contract/schema';
|
|
27
|
+
import type { CollectionOps } from '../contract/transaction';
|
|
28
|
+
import { raise } from '../diagnostics/errors';
|
|
29
|
+
import { throwIfFaulted } from '../diagnostics/faults';
|
|
30
|
+
import { createSqlCollection } from '../adapter/collection';
|
|
31
|
+
import type { Connection, Executor } from '../sqlite/connection';
|
|
32
|
+
import { ensureLedger, readSchemaVersion, recordAttempt, writeSchemaVersion } from './ledger';
|
|
33
|
+
import { pendingMigrations, validateMigrationChain } from './validate-chain';
|
|
34
|
+
|
|
35
|
+
export type MigrationRunContext = {
|
|
36
|
+
connection: Connection;
|
|
37
|
+
config: DatabaseConfig;
|
|
38
|
+
schemaFor(name: string): CollectionSchema;
|
|
39
|
+
now(): number;
|
|
40
|
+
/**
|
|
41
|
+
* Called before a migration failure is raised. The executor does not own
|
|
42
|
+
* the connection, so it asks rather than closing directly — but the close
|
|
43
|
+
* has to happen before the error escapes, or a caller catching it could
|
|
44
|
+
* still be holding something usable (FR-050).
|
|
45
|
+
*/
|
|
46
|
+
closeOnFailure(): Promise<void>;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
function migrationContextFor(
|
|
50
|
+
context: MigrationRunContext,
|
|
51
|
+
executor: Executor,
|
|
52
|
+
): MigrationContext {
|
|
53
|
+
return {
|
|
54
|
+
collection<T extends StorableRecordData>(name: string): CollectionOps<T> {
|
|
55
|
+
return createSqlCollection<T>({
|
|
56
|
+
executor: () => executor,
|
|
57
|
+
schema: context.schemaFor(name),
|
|
58
|
+
now: context.now,
|
|
59
|
+
// Inside a migration the handle does not exist yet, so there is
|
|
60
|
+
// no closed-handle or deleted-scope state to guard against.
|
|
61
|
+
assertUsable: () => {},
|
|
62
|
+
});
|
|
63
|
+
},
|
|
64
|
+
async abort(): Promise<void> {
|
|
65
|
+
// A migration that wants to give up should throw; aborting the
|
|
66
|
+
// transaction from inside while the executor still believes it is
|
|
67
|
+
// running would record an outcome that never happened.
|
|
68
|
+
raise(DiagnosticCodes.TRANSACTION_STATE, {
|
|
69
|
+
message: 'a migration cannot abort its own transaction',
|
|
70
|
+
});
|
|
71
|
+
},
|
|
72
|
+
async execute(sql: string, params?: unknown[]): Promise<void> {
|
|
73
|
+
await executor.execute(sql, params as never);
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function runMigrations(context: MigrationRunContext): Promise<number> {
|
|
79
|
+
const { config, connection } = context;
|
|
80
|
+
validateMigrationChain(config);
|
|
81
|
+
await ensureLedger(connection);
|
|
82
|
+
|
|
83
|
+
const recorded = await readSchemaVersion(connection);
|
|
84
|
+
|
|
85
|
+
if (recorded > config.schemaVersion) {
|
|
86
|
+
// Opening anyway would mean newer data read by older code, which drops
|
|
87
|
+
// whatever the newer schema added — silently, and on write (FR-052).
|
|
88
|
+
await context.closeOnFailure();
|
|
89
|
+
raise(DiagnosticCodes.SCHEMA_DOWNGRADE, {
|
|
90
|
+
message: 'recorded schema version is newer than the declared one',
|
|
91
|
+
detail: { recordedVersion: recorded, version: config.schemaVersion },
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
let current = recorded;
|
|
96
|
+
|
|
97
|
+
for (const migration of pendingMigrations(config, recorded)) {
|
|
98
|
+
try {
|
|
99
|
+
await connection.transaction(async tx => {
|
|
100
|
+
throwIfFaulted('migration');
|
|
101
|
+
await migration.migrate(migrationContextFor(context, tx));
|
|
102
|
+
await writeSchemaVersion(tx, migration.version);
|
|
103
|
+
await recordAttempt(tx, {
|
|
104
|
+
version: migration.version,
|
|
105
|
+
attemptedAt: context.now(),
|
|
106
|
+
outcome: 'applied',
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
current = migration.version;
|
|
110
|
+
} catch (error) {
|
|
111
|
+
// Recorded outside the rolled-back transaction, or it would vanish
|
|
112
|
+
// with the migration it describes.
|
|
113
|
+
await recordAttempt(connection, {
|
|
114
|
+
version: migration.version,
|
|
115
|
+
attemptedAt: context.now(),
|
|
116
|
+
outcome: 'failed',
|
|
117
|
+
failureCode:
|
|
118
|
+
(error as { code?: string }).code ?? DiagnosticCodes.MIGRATION_FAILED,
|
|
119
|
+
});
|
|
120
|
+
await context.closeOnFailure();
|
|
121
|
+
raise(DiagnosticCodes.MIGRATION_FAILED, {
|
|
122
|
+
message: 'migration failed',
|
|
123
|
+
migration: {
|
|
124
|
+
// Unchanged: the next open retries from here rather than
|
|
125
|
+
// skipping the migration that failed.
|
|
126
|
+
recordedVersion: current,
|
|
127
|
+
failingVersion: migration.version,
|
|
128
|
+
outcome: 'failed',
|
|
129
|
+
},
|
|
130
|
+
cause: error,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return current;
|
|
136
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The per-scope migration ledger.
|
|
3
|
+
*
|
|
4
|
+
* Per scope, not per database, and that is the whole reason FR-054 works: a
|
|
5
|
+
* scope created after a migration shipped starts at version 0 and is migrated
|
|
6
|
+
* on first open, rather than being assumed current because some other scope
|
|
7
|
+
* already ran the chain.
|
|
8
|
+
*
|
|
9
|
+
* The ledger records a **code**, never a message (FR-079). A migration that
|
|
10
|
+
* failed because a domain constraint was violated could otherwise write the
|
|
11
|
+
* offending value into a table that outlives the failure — a payload leak
|
|
12
|
+
* with a long half-life, sitting in a file the next crash report might carry.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { MigrationLedgerEntry, MigrationOutcome } from '../contract/migration';
|
|
16
|
+
import type { Executor } from '../sqlite/connection';
|
|
17
|
+
import { maybeText, num, text } from '../sqlite/values';
|
|
18
|
+
|
|
19
|
+
/** Physical layout version, independent of the app's schema version. */
|
|
20
|
+
export const FORMAT_VERSION = 1;
|
|
21
|
+
|
|
22
|
+
const CREATE_META = `CREATE TABLE IF NOT EXISTS _meta (
|
|
23
|
+
key TEXT PRIMARY KEY,
|
|
24
|
+
value TEXT NOT NULL
|
|
25
|
+
)`;
|
|
26
|
+
|
|
27
|
+
const CREATE_MIGRATIONS = `CREATE TABLE IF NOT EXISTS _migrations (
|
|
28
|
+
version INTEGER PRIMARY KEY,
|
|
29
|
+
attempted_at INTEGER NOT NULL,
|
|
30
|
+
outcome TEXT NOT NULL,
|
|
31
|
+
failure_code TEXT
|
|
32
|
+
)`;
|
|
33
|
+
|
|
34
|
+
export async function ensureLedger(executor: Executor): Promise<void> {
|
|
35
|
+
await executor.execute(CREATE_META);
|
|
36
|
+
await executor.execute(CREATE_MIGRATIONS);
|
|
37
|
+
await executor.execute(
|
|
38
|
+
'INSERT INTO _meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO NOTHING',
|
|
39
|
+
['format_version', String(FORMAT_VERSION)],
|
|
40
|
+
);
|
|
41
|
+
await executor.execute(
|
|
42
|
+
'INSERT INTO _meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO NOTHING',
|
|
43
|
+
['schema_version', '0'],
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function readMeta(executor: Executor, key: string): Promise<string | null> {
|
|
48
|
+
const result = await executor.execute('SELECT value FROM _meta WHERE key = ?', [key]);
|
|
49
|
+
const row = result.rows[0];
|
|
50
|
+
return row ? text(row.value) : null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function readSchemaVersion(executor: Executor): Promise<number> {
|
|
54
|
+
const raw = await readMeta(executor, 'schema_version');
|
|
55
|
+
return raw === null ? 0 : Number(raw);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function readFormatVersion(executor: Executor): Promise<number> {
|
|
59
|
+
const raw = await readMeta(executor, 'format_version');
|
|
60
|
+
return raw === null ? FORMAT_VERSION : Number(raw);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function writeSchemaVersion(executor: Executor, version: number): Promise<void> {
|
|
64
|
+
await executor.execute(
|
|
65
|
+
'INSERT INTO _meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value',
|
|
66
|
+
['schema_version', String(version)],
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function recordAttempt(
|
|
71
|
+
executor: Executor,
|
|
72
|
+
entry: { version: number; attemptedAt: number; outcome: MigrationOutcome; failureCode?: string },
|
|
73
|
+
): Promise<void> {
|
|
74
|
+
await executor.execute(
|
|
75
|
+
`INSERT INTO _migrations (version, attempted_at, outcome, failure_code)
|
|
76
|
+
VALUES (?, ?, ?, ?)
|
|
77
|
+
ON CONFLICT(version) DO UPDATE SET
|
|
78
|
+
attempted_at = excluded.attempted_at,
|
|
79
|
+
outcome = excluded.outcome,
|
|
80
|
+
failure_code = excluded.failure_code`,
|
|
81
|
+
[entry.version, entry.attemptedAt, entry.outcome, entry.failureCode ?? null],
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export async function readLedger(executor: Executor): Promise<MigrationLedgerEntry[]> {
|
|
86
|
+
const result = await executor.execute(
|
|
87
|
+
'SELECT version, attempted_at, outcome, failure_code FROM _migrations ORDER BY version ASC',
|
|
88
|
+
);
|
|
89
|
+
return result.rows.map(row => ({
|
|
90
|
+
version: num(row.version),
|
|
91
|
+
attemptedAt: num(row.attempted_at),
|
|
92
|
+
outcome: text(row.outcome) as MigrationOutcome,
|
|
93
|
+
...(maybeText(row.failure_code) === null
|
|
94
|
+
? {}
|
|
95
|
+
: { failureCode: text(row.failure_code) }),
|
|
96
|
+
}));
|
|
97
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Migration chain validation, run before any migration executes (FR-053).
|
|
3
|
+
*
|
|
4
|
+
* Validating first is what stops a half-run chain from being the thing that
|
|
5
|
+
* discovers the problem. A duplicate version, a gap, or a chain that does not
|
|
6
|
+
* reach the declared `schemaVersion` are all configuration errors the
|
|
7
|
+
* developer can fix; discovering them after migration 3 of 5 has already
|
|
8
|
+
* rewritten a user's data is not.
|
|
9
|
+
*
|
|
10
|
+
* A gap is refused rather than skipped over deliberately. A user upgrading
|
|
11
|
+
* from the version inside the gap has no path across it, and opening anyway
|
|
12
|
+
* would hand them a database the code believes is current and is not.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { DatabaseConfig } from '../contract/config';
|
|
16
|
+
import { DiagnosticCodes } from '../contract/errors';
|
|
17
|
+
import type { Migration } from '../contract/migration';
|
|
18
|
+
import { raise } from '../diagnostics/errors';
|
|
19
|
+
|
|
20
|
+
function invalid(message: string, detail?: Record<string, unknown>): never {
|
|
21
|
+
raise(DiagnosticCodes.MIGRATION_CONFIG_INVALID, { message, detail });
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function validateMigrationChain(config: DatabaseConfig): void {
|
|
25
|
+
const migrations = config.migrations ?? [];
|
|
26
|
+
|
|
27
|
+
if (!Number.isInteger(config.schemaVersion) || config.schemaVersion < 1) {
|
|
28
|
+
invalid('schemaVersion must be a positive integer');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const versions = new Set<number>();
|
|
32
|
+
for (const migration of migrations) {
|
|
33
|
+
if (!Number.isInteger(migration.version) || migration.version < 1) {
|
|
34
|
+
invalid('migration version must be a positive integer');
|
|
35
|
+
}
|
|
36
|
+
if (versions.has(migration.version)) {
|
|
37
|
+
invalid('duplicate migration version', { version: migration.version });
|
|
38
|
+
}
|
|
39
|
+
versions.add(migration.version);
|
|
40
|
+
if (typeof migration.migrate !== 'function') {
|
|
41
|
+
invalid('migration has no migrate function', { version: migration.version });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
for (let version = 1; version <= config.schemaVersion; version += 1) {
|
|
46
|
+
if (!versions.has(version)) {
|
|
47
|
+
invalid('migration chain has a gap', { version });
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
for (const version of versions) {
|
|
52
|
+
if (version > config.schemaVersion) {
|
|
53
|
+
invalid('migration version exceeds the declared schemaVersion', { version });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Ascending, because the order a consumer declared them in is not a contract. */
|
|
59
|
+
export function orderedMigrations(config: DatabaseConfig): Migration[] {
|
|
60
|
+
return [...(config.migrations ?? [])].sort((a, b) => a.version - b.version);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function pendingMigrations(config: DatabaseConfig, recordedVersion: number): Migration[] {
|
|
64
|
+
return orderedMigrations(config).filter(migration => migration.version > recordedVersion);
|
|
65
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Android backup posture: verified and reported, never enforced.
|
|
3
|
+
*
|
|
4
|
+
* Android decides backup participation from `android:dataExtractionRules` in
|
|
5
|
+
* the app's manifest. That is build-time and app-owned, and this package
|
|
6
|
+
* authors no native code, so it cannot contribute an entry and cannot change
|
|
7
|
+
* the answer at runtime (research.md R5).
|
|
8
|
+
*
|
|
9
|
+
* What it can do is check the one thing that silently breaks the documented
|
|
10
|
+
* fix: the rule the README tells an app to ship addresses the `file` domain,
|
|
11
|
+
* which is the app's `files/` directory. If the managed root did not land
|
|
12
|
+
* under that directory, the app can ship the XML exactly as documented and
|
|
13
|
+
* still have an unprotected database. That mismatch is detectable here, and
|
|
14
|
+
* an app learning it from this report is the whole point of FR-111 — the
|
|
15
|
+
* alternative is learning it from an incident.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { Platform } from 'react-native';
|
|
19
|
+
|
|
20
|
+
import type { EffectivePosture } from '../contract/backup';
|
|
21
|
+
import { MANAGED_ROOT_NAME, normalizePath, type StorageLayout } from './location';
|
|
22
|
+
|
|
23
|
+
export function isAndroid(): boolean {
|
|
24
|
+
return Platform.OS === 'android';
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The `path` an app's exclusion rule must name for the root it actually got. */
|
|
28
|
+
export function coveragePathFor(layout: StorageLayout): string | null {
|
|
29
|
+
const root = normalizePath(layout.root);
|
|
30
|
+
const marker = `/files/`;
|
|
31
|
+
const index = root.indexOf(marker);
|
|
32
|
+
if (index === -1) {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
return root.slice(index + marker.length);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function androidPosture(
|
|
39
|
+
layout: StorageLayout,
|
|
40
|
+
includeInPlatformBackup: boolean,
|
|
41
|
+
): EffectivePosture {
|
|
42
|
+
const requested = includeInPlatformBackup ? 'included' : 'excluded';
|
|
43
|
+
const coverage = coveragePathFor(layout);
|
|
44
|
+
|
|
45
|
+
if (coverage === null) {
|
|
46
|
+
return {
|
|
47
|
+
requested,
|
|
48
|
+
// Not "excluded" and not "included": the package genuinely does not
|
|
49
|
+
// know, and saying either would be a claim it cannot support.
|
|
50
|
+
observed: 'unknown',
|
|
51
|
+
enforcedBy: 'app-manifest',
|
|
52
|
+
warning:
|
|
53
|
+
'The managed storage area is not under the Android file domain, so the ' +
|
|
54
|
+
'documented data_extraction_rules.xml entry will not cover it. Backup ' +
|
|
55
|
+
'posture cannot be honoured on this platform until the app supplies a ' +
|
|
56
|
+
'rule matching the actual storage location.',
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return {
|
|
61
|
+
requested,
|
|
62
|
+
observed: 'unknown',
|
|
63
|
+
enforcedBy: 'app-manifest',
|
|
64
|
+
warning:
|
|
65
|
+
`Android backup participation is declared by the app, not this package. ` +
|
|
66
|
+
`Confirm android/app/src/main/res/xml/data_extraction_rules.xml contains an ` +
|
|
67
|
+
`entry for domain="file" path="${MANAGED_ROOT_NAME}/" and that ` +
|
|
68
|
+
`AndroidManifest.xml references it; the observed posture cannot be verified ` +
|
|
69
|
+
`from JavaScript.`,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The posture the handle reports (FR-111).
|
|
75
|
+
*
|
|
76
|
+
* Split by platform rather than smoothed over, because a consumer writing a
|
|
77
|
+
* privacy disclosure needs to know which of the two answers it is holding.
|
|
78
|
+
*/
|
|
79
|
+
export function effectivePostureFor(
|
|
80
|
+
layout: StorageLayout,
|
|
81
|
+
includeInPlatformBackup: boolean,
|
|
82
|
+
iosPostureFor: (include: boolean) => EffectivePosture,
|
|
83
|
+
): EffectivePosture {
|
|
84
|
+
if (isAndroid()) {
|
|
85
|
+
return androidPosture(layout, includeInPlatformBackup);
|
|
86
|
+
}
|
|
87
|
+
return iosPostureFor(includeInPlatformBackup);
|
|
88
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* iOS backup exclusion.
|
|
3
|
+
*
|
|
4
|
+
* `NSURLIsExcludedFromBackupKey` is set on the managed root at creation, and
|
|
5
|
+
* the attribute is inherited by everything beneath it — so one call covers
|
|
6
|
+
* the catalog, every scope database, and every artifact, including ones
|
|
7
|
+
* created years later. Setting it per file would leave a window in which a
|
|
8
|
+
* freshly written artifact is backed up before the attribute lands.
|
|
9
|
+
*
|
|
10
|
+
* This is the half of FR-109 the package can actually enforce. Android is
|
|
11
|
+
* manifest-owned; see backup-android-verify.ts and research.md R5.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { Platform } from 'react-native';
|
|
15
|
+
|
|
16
|
+
import type { EffectivePosture } from '../contract/backup';
|
|
17
|
+
import { fileSystem } from './fs';
|
|
18
|
+
import type { StorageLayout } from './location';
|
|
19
|
+
|
|
20
|
+
export function isIos(): boolean {
|
|
21
|
+
return Platform.OS === 'ios';
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Create the managed root with the exclusion attribute already on it.
|
|
26
|
+
*
|
|
27
|
+
* Idempotent: `mkdir` on an existing directory re-applies the attribute,
|
|
28
|
+
* which matters because an app that flips the posture between launches must
|
|
29
|
+
* get the new one without a reinstall.
|
|
30
|
+
*/
|
|
31
|
+
export async function ensureManagedRoot(
|
|
32
|
+
layout: StorageLayout,
|
|
33
|
+
includeInPlatformBackup: boolean,
|
|
34
|
+
): Promise<void> {
|
|
35
|
+
await fileSystem().mkdir(layout.root, {
|
|
36
|
+
NSURLIsExcludedFromBackupKey: isIos() ? !includeInPlatformBackup : undefined,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** What the package can state about iOS, where it enforces rather than reports. */
|
|
41
|
+
export function iosPosture(includeInPlatformBackup: boolean): EffectivePosture {
|
|
42
|
+
const requested = includeInPlatformBackup ? 'included' : 'excluded';
|
|
43
|
+
return {
|
|
44
|
+
requested,
|
|
45
|
+
observed: requested,
|
|
46
|
+
enforcedBy: 'package',
|
|
47
|
+
};
|
|
48
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The filesystem peer, behind one lazy accessor.
|
|
3
|
+
*
|
|
4
|
+
* Required lazily for the same reason the engine is: a consuming app that
|
|
5
|
+
* only ever runs the in-memory adapter in tests must not have to install a
|
|
6
|
+
* native module to import this package. Confining the require to `platform/`
|
|
7
|
+
* also keeps the native surface four directories wide, which is the layering
|
|
8
|
+
* rule the ESLint config enforces.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { DiagnosticCodes } from '../contract/errors';
|
|
12
|
+
import { raise } from '../diagnostics/errors';
|
|
13
|
+
|
|
14
|
+
export type FileStat = {
|
|
15
|
+
path: string;
|
|
16
|
+
size: number;
|
|
17
|
+
mtime: number;
|
|
18
|
+
isFile(): boolean;
|
|
19
|
+
isDirectory(): boolean;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export type MkdirOptions = {
|
|
23
|
+
/** iOS only. Set at creation so nothing beneath it is ever backed up. */
|
|
24
|
+
NSURLIsExcludedFromBackupKey?: boolean;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Only what the package actually uses. The peer's upload and download
|
|
29
|
+
* helpers are deliberately absent from this type: the package must never
|
|
30
|
+
* make a network request (FR-084, SC-016), and a surface that cannot express
|
|
31
|
+
* one is a stronger guarantee than a rule that says not to.
|
|
32
|
+
*/
|
|
33
|
+
export type FileSystem = {
|
|
34
|
+
DocumentDirectoryPath: string;
|
|
35
|
+
mkdir(path: string, options?: MkdirOptions): Promise<void>;
|
|
36
|
+
writeFile(path: string, contents: string, encoding?: string): Promise<void>;
|
|
37
|
+
appendFile(path: string, contents: string, encoding?: string): Promise<void>;
|
|
38
|
+
readFile(path: string, encoding?: string): Promise<string>;
|
|
39
|
+
/** Chunked read at an offset — what FR-107a's flat memory bound rests on. */
|
|
40
|
+
read(path: string, length: number, position: number, encoding?: string): Promise<string>;
|
|
41
|
+
stat(path: string): Promise<FileStat>;
|
|
42
|
+
readdir(path: string): Promise<string[]>;
|
|
43
|
+
unlink(path: string): Promise<void>;
|
|
44
|
+
exists(path: string): Promise<boolean>;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
let override: FileSystem | null = null;
|
|
48
|
+
let cached: FileSystem | null = null;
|
|
49
|
+
|
|
50
|
+
/** Swap the peer. Tests and the demo app's in-memory mode only. */
|
|
51
|
+
export function setFileSystem(module: FileSystem | null): void {
|
|
52
|
+
override = module;
|
|
53
|
+
cached = null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function fileSystem(): FileSystem {
|
|
57
|
+
if (override) {
|
|
58
|
+
return override;
|
|
59
|
+
}
|
|
60
|
+
if (!cached) {
|
|
61
|
+
try {
|
|
62
|
+
cached = require('@dr.pogodin/react-native-fs') as FileSystem;
|
|
63
|
+
} catch (error) {
|
|
64
|
+
raise(DiagnosticCodes.STORAGE_ACCESS, {
|
|
65
|
+
message: 'filesystem peer is not installed',
|
|
66
|
+
cause: error,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return cached!;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function pathExists(path: string): Promise<boolean> {
|
|
74
|
+
try {
|
|
75
|
+
return await fileSystem().exists(path);
|
|
76
|
+
} catch {
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Remove a path, treating "already gone" as success (FR-062). */
|
|
82
|
+
export async function removeIfPresent(path: string): Promise<boolean> {
|
|
83
|
+
try {
|
|
84
|
+
await fileSystem().unlink(path);
|
|
85
|
+
return true;
|
|
86
|
+
} catch {
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
}
|