@runeditrun/rer 0.2.85 → 0.2.87
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/README.md +138 -29
- package/cli/README.md +61 -1
- package/cli/agent-bindings.mjs +25 -0
- package/cli/agent-door.mjs +145 -0
- package/cli/agent-fixtures.mjs +16 -0
- package/cli/agent-journey-fixtures.mjs +17 -0
- package/cli/agent-mail.mjs +54 -0
- package/cli/agent-network.mjs +64 -0
- package/cli/agent-reviewers.mjs +110 -0
- package/cli/agent-rpc.mjs +23 -0
- package/cli/agent-secrets.mjs +23 -0
- package/cli/agent-sponsors.mjs +43 -0
- package/cli/agent-surface.mjs +34 -0
- package/cli/agent-verifier.mjs +31 -0
- package/cli/agent-webhooks.mjs +19 -0
- package/cli/authoring.mjs +2 -1
- package/cli/business/archive-task.mjs +32 -0
- package/cli/business/carry.mjs +3 -1
- package/cli/business/catchup-task.mjs +42 -0
- package/cli/business/choices.mjs +97 -0
- package/cli/business/command.mjs +23 -5
- package/cli/business/connect.mjs +19 -7
- package/cli/business/detector.mjs +4 -1
- package/cli/business/device.mjs +13 -0
- package/cli/business/export-inputs.mjs +69 -0
- package/cli/business/export-task.mjs +17 -0
- package/cli/business/invocation.mjs +8 -1
- package/cli/business/keychain.mjs +8 -1
- package/cli/business/lease.mjs +11 -1
- package/cli/business/local-commands.mjs +79 -31
- package/cli/business/outbound.mjs +9 -4
- package/cli/business/parsers-config.mjs +8 -7
- package/cli/business/parsers-syntax.mjs +7 -3
- package/cli/business/permissions.mjs +2 -0
- package/cli/business/questions.mjs +89 -9
- package/cli/business/setup-command.mjs +49 -0
- package/cli/business/setup-company.json +15 -0
- package/cli/business/setup-demo.mjs +95 -0
- package/cli/business/state.mjs +44 -10
- package/cli/business/supervisor.mjs +94 -35
- package/cli/business/vendor-door.mjs +230 -0
- package/cli/business/vendors/README.md +29 -3
- package/cli/business/vendors/common.mjs +8 -6
- package/cli/business/vendors/index.mjs +22 -11
- package/cli/business/vendors/sorry.mjs +106 -0
- package/cli/contract.mjs +2 -2
- package/cli/demo-deploy-error.mjs +14 -0
- package/cli/demo-native.mjs +4 -1
- package/cli/deploy-config.mjs +1 -1
- package/cli/deploy-owner-input.mjs +3 -1
- package/cli/deploy-variables.mjs +89 -0
- package/cli/door-clauses.mjs +157 -0
- package/cli/export.mjs +17 -4
- package/cli/hosted-output.mjs +31 -8
- package/cli/inspect.mjs +4 -0
- package/cli/jsonc.mjs +8 -4
- package/cli/lifecycle.mjs +3 -1
- package/cli/main.mjs +1 -0
- package/cli/managed-data-schema.mjs +14 -1
- package/cli/managed-data.mjs +8 -4
- package/cli/portability-empty.mjs +6 -0
- package/cli/portability-migrations.mjs +26 -4
- package/cli/portability-worker.mjs +2 -1
- package/cli/portability.mjs +1 -0
- package/cli/production-auth.mjs +2 -2
- package/cli/production-mail.mjs +19 -3
- package/cli/server-registry.mjs +2 -0
- package/edition-authoring/archive-source.mjs +65 -0
- package/edition-authoring/base-copies.mjs +108 -21
- package/edition-authoring/cli.mjs +1 -1
- package/edition-authoring/copy-namespaces.mjs +28 -0
- package/edition-authoring/edition-migrations.mjs +7 -3
- package/edition-authoring/files.mjs +2 -1
- package/edition-authoring/module-closure.mjs +58 -27
- package/edition-authoring/module-edges.mjs +13 -2
- package/edition-authoring/workflow-copies.mjs +1 -1
- package/edition-authoring/workflow-scripts.mjs +12 -3
- package/foundation/runtime/contract-docs.mjs +220 -32
- package/foundation/runtime/contract-prose-patterns.mjs +14 -0
- package/foundation/runtime/contract-prose.mjs +88 -0
- package/global/CHANGELOG.md +151 -0
- package/global/README.md +138 -29
- package/global/door/command.mjs +3 -1
- package/global/main.mjs +1 -1
- package/modules/agent-door/CLAUSES.md +215 -0
- package/modules/agent-door/conformance/audit-pages.mjs +11 -0
- package/modules/agent-door/conformance/audit-rows.mjs +20 -0
- package/modules/agent-door/conformance/audit.mjs +63 -0
- package/modules/agent-door/conformance/authority.d.mts +2 -0
- package/modules/agent-door/conformance/authority.mjs +17 -0
- package/modules/agent-door/conformance/crypto.mjs +36 -0
- package/modules/agent-door/conformance/discovery.mjs +61 -0
- package/modules/agent-door/conformance/fixtures.mjs +41 -0
- package/modules/agent-door/conformance/index.mjs +41 -0
- package/modules/agent-door/conformance/injection.mjs +24 -0
- package/modules/agent-door/conformance/invocation.mjs +33 -0
- package/modules/agent-door/conformance/journey.mjs +117 -0
- package/modules/agent-door/conformance/narrowing.d.mts +2 -0
- package/modules/agent-door/conformance/narrowing.mjs +29 -0
- package/modules/agent-door/conformance/negative.mjs +48 -0
- package/modules/agent-door/conformance/network-modules.mjs +86 -0
- package/modules/agent-door/conformance/network-runtime.mjs +46 -0
- package/modules/agent-door/conformance/policy-phases.mjs +83 -0
- package/modules/agent-door/conformance/protocol.mjs +153 -0
- package/modules/agent-door/conformance/replay.mjs +39 -0
- package/modules/agent-door/conformance/schema.mjs +71 -0
- package/modules/agent-door/conformance/security.mjs +34 -0
- package/modules/agent-door/conformance/sponsors.mjs +68 -0
- package/modules/agent-door/conformance/step-hooks.mjs +4 -0
- package/modules/agent-door/conformance/surface.mjs +92 -0
- package/modules/agent-door/conformance/target.mjs +19 -0
- package/modules/agent-door/conformance/tool-name.d.mts +1 -0
- package/modules/agent-door/conformance/tool-name.mjs +7 -0
- package/modules/agent-door/conformance/webhooks.mjs +31 -0
- package/modules/container/image-variables.mjs +8 -2
- package/modules/delivery-producer/mail.mjs +20 -0
- package/modules/demo-host/README.md +6 -0
- package/modules/demo-host/ownership.mjs +39 -0
- package/modules/demo-host/plan.mjs +2 -1
- package/modules/demo-host/remove.mjs +6 -1
- package/modules/import-kit/schema/importer-verification-receipt.schema.json +171 -0
- package/modules/import-kit/schema/importers.schema.json +107 -0
- package/modules/import-kit/src/door/ADOPTING.md +20 -0
- package/modules/import-kit/src/door/README.md +2 -1
- package/modules/import-kit/src/door/admission.ts +5 -3
- package/modules/import-kit/src/door/archive.ts +5 -2
- package/modules/import-kit/src/door/authority.ts +1 -0
- package/modules/import-kit/src/door/grants.ts +1 -1
- package/modules/import-kit/src/door/handler.ts +14 -8
- package/modules/import-kit/src/door/index.ts +1 -1
- package/modules/import-kit/src/door/jobs.ts +40 -0
- package/modules/import-kit/src/door/operator.ts +3 -3
- package/modules/import-kit/src/door/planning.ts +10 -6
- package/modules/import-kit/src/door/protocol.ts +2 -2
- package/modules/import-kit/src/door/raw.ts +25 -0
- package/modules/import-kit/src/door/refusals.ts +1 -0
- package/modules/import-kit/src/door/types.ts +26 -6
- package/modules/import-kit/src/receipt/encoding.ts +37 -0
- package/modules/import-kit/src/receipt/index.ts +69 -0
- package/modules/import-kit/src/receipt/policy.ts +24 -0
- package/modules/import-kit/src/receipt/types.ts +64 -0
- package/modules/import-kit/src/receipt/uri.ts +45 -0
- package/modules/import-kit/src/receipt/validation.ts +87 -0
- package/modules/import-kit/src/status/encoding.ts +13 -0
- package/modules/import-kit/src/status/evidence.ts +218 -0
- package/modules/import-kit/src/status/index.ts +56 -0
- package/modules/import-kit/src/status/schema.ts +208 -0
- package/modules/import-kit/src/status/types.ts +86 -0
- package/modules/operator-auth/accounts/delegated.mjs +48 -0
- package/modules/operator-auth/index.d.mts +7 -0
- package/modules/operator-auth/service.mjs +2 -0
- package/modules/portability/README.md +37 -13
- package/modules/portability/bridge.mjs +22 -2
- package/modules/portability/catalogue.mjs +12 -2
- package/modules/portability/copies.mjs +8 -1
- package/modules/portability/derived.mjs +33 -0
- package/modules/portability/http-errors.mjs +1 -1
- package/modules/portability/import.mjs +14 -7
- package/package.json +4 -2
- package/scripts/publish-check/copy_identities.py +3 -1
- package/scripts/publish-check/github_refs.py +32 -13
- package/cli/business/opt-ins.mjs +0 -37
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { validateImporterEvidence } from './evidence.ts';
|
|
2
|
+
import { validateStatusDocumentSchema } from './schema.ts';
|
|
3
|
+
import type {
|
|
4
|
+
ImporterEvidencePort,
|
|
5
|
+
ImporterRecord,
|
|
6
|
+
ImporterValidationIssue,
|
|
7
|
+
ImporterValidationResult,
|
|
8
|
+
ImportersDocument,
|
|
9
|
+
} from './types.ts';
|
|
10
|
+
|
|
11
|
+
export type * from './types.ts';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Validate the published status document and resolve its evidence through the
|
|
15
|
+
* consumer's trust policy. A verified status also needs a trusted signed receipt.
|
|
16
|
+
*/
|
|
17
|
+
export async function validateImporters(
|
|
18
|
+
document: unknown,
|
|
19
|
+
evidence?: ImporterEvidencePort,
|
|
20
|
+
): Promise<ImporterValidationResult> {
|
|
21
|
+
const issues = validateStatusDocumentSchema(document);
|
|
22
|
+
const counters: ImporterValidationResult['evidence'] = { required: 0, resolved: 0, verifiedReceipts: 0 };
|
|
23
|
+
if (issues.length > 0) return result(issues, counters);
|
|
24
|
+
|
|
25
|
+
const records = (document as ImportersDocument).importers;
|
|
26
|
+
const seen = new Map<string, number>();
|
|
27
|
+
for (let index = 0; index < records.length; index += 1) {
|
|
28
|
+
const record = records[index]!;
|
|
29
|
+
const path = `$.importers[${index}]`;
|
|
30
|
+
const incumbent = normalizeLabel(record.incumbent);
|
|
31
|
+
const product = normalizeLabel(record.product);
|
|
32
|
+
if (record.incumbent.trim() !== record.incumbent || record.product.trim() !== record.product || !incumbent || !product) {
|
|
33
|
+
issues.push({ code: 'LABEL_NOT_NORMALIZED', path, message: 'Incumbent and product must be trimmed, non-empty labels.' });
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
const key = JSON.stringify([incumbent, product]);
|
|
37
|
+
const previous = seen.get(key);
|
|
38
|
+
if (previous !== undefined) {
|
|
39
|
+
issues.push({ code: 'DUPLICATE_PAIR', path, message: `Importer pair duplicates $.importers[${previous}].` });
|
|
40
|
+
} else {
|
|
41
|
+
seen.set(key, index);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (issues.length > 0) return result(issues, counters);
|
|
45
|
+
|
|
46
|
+
const evidenceCounters = await validateImporterEvidence(records as ImporterRecord[], evidence, issues);
|
|
47
|
+
return result(issues, evidenceCounters);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function result(issues: ImporterValidationIssue[], evidence: ImporterValidationResult['evidence']): ImporterValidationResult {
|
|
51
|
+
return { valid: issues.length === 0, issues, evidence: { ...evidence } };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function normalizeLabel(value: string): string {
|
|
55
|
+
return value.normalize('NFKC').trim().toLowerCase();
|
|
56
|
+
}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import importersSchemaJson from '../../schema/importers.schema.json' with { type: 'json' };
|
|
2
|
+
import receiptSchemaJson from '../../schema/importer-verification-receipt.schema.json' with { type: 'json' };
|
|
3
|
+
import { canonicalReceiptJson as canonicalJson } from '../receipt/encoding.ts';
|
|
4
|
+
import type { ImporterValidationIssue } from './types.ts';
|
|
5
|
+
|
|
6
|
+
interface JsonSchema {
|
|
7
|
+
$ref?: string;
|
|
8
|
+
type?: string;
|
|
9
|
+
const?: unknown;
|
|
10
|
+
enum?: unknown[];
|
|
11
|
+
minLength?: number;
|
|
12
|
+
maxLength?: number;
|
|
13
|
+
pattern?: string;
|
|
14
|
+
minimum?: number;
|
|
15
|
+
minItems?: number;
|
|
16
|
+
minProperties?: number;
|
|
17
|
+
required?: string[];
|
|
18
|
+
properties?: Record<string, JsonSchema>;
|
|
19
|
+
additionalProperties?: boolean | JsonSchema;
|
|
20
|
+
items?: JsonSchema;
|
|
21
|
+
oneOf?: JsonSchema[];
|
|
22
|
+
format?: string;
|
|
23
|
+
[key: string]: unknown;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const importersSchema = importersSchemaJson as unknown as JsonSchema;
|
|
27
|
+
const receiptSchema = receiptSchemaJson as unknown as JsonSchema;
|
|
28
|
+
|
|
29
|
+
export function validateStatusDocumentSchema(document: unknown): ImporterValidationIssue[] {
|
|
30
|
+
if (!isJsonValue(document)) {
|
|
31
|
+
return [{ code: 'DOCUMENT_NOT_JSON', path: '$', message: 'Importer status must be JSON data.' }];
|
|
32
|
+
}
|
|
33
|
+
return schemaIssues(document, importersSchema, importersSchema, '$');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function validateReceiptDocumentSchema(document: unknown, path: string): ImporterValidationIssue[] {
|
|
37
|
+
if (!isJsonValue(document)) {
|
|
38
|
+
return [{ code: 'RECEIPT_NOT_JSON', path, message: 'Verification receipt must be JSON data.' }];
|
|
39
|
+
}
|
|
40
|
+
return schemaIssues(document, receiptSchema, receiptSchema, path);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function schemaIssues(value: unknown, schema: JsonSchema, root: JsonSchema, path: string): ImporterValidationIssue[] {
|
|
44
|
+
if (typeof schema.$ref === 'string') {
|
|
45
|
+
const target = resolveSchemaReference(root, schema.$ref);
|
|
46
|
+
if (!target) return [{ code: 'INVALID_SCHEMA_REFERENCE', path, message: `Schema reference ${schema.$ref} does not resolve.` }];
|
|
47
|
+
return schemaIssues(value, target, root, path);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (schema.oneOf) {
|
|
51
|
+
const matching = schema.oneOf.filter((branch) => schemaIssues(value, branch, root, path).length === 0).length;
|
|
52
|
+
return matching === 1
|
|
53
|
+
? []
|
|
54
|
+
: [{ code: 'SCHEMA_ONE_OF', path, message: matching === 0 ? 'Value does not match any allowed schema branch.' : 'Value matches more than one schema branch.' }];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const issues: ImporterValidationIssue[] = [];
|
|
58
|
+
if (schema.type && !matchesType(value, schema.type)) {
|
|
59
|
+
return [{ code: 'SCHEMA_TYPE', path, message: `Expected ${schema.type}.` }];
|
|
60
|
+
}
|
|
61
|
+
if (Object.hasOwn(schema, 'const') && !sameJsonValue(value, schema.const)) {
|
|
62
|
+
issues.push({ code: 'SCHEMA_CONST', path, message: `Expected the constant ${JSON.stringify(schema.const)}.` });
|
|
63
|
+
}
|
|
64
|
+
if (schema.enum && !schema.enum.some((allowed) => sameJsonValue(value, allowed))) {
|
|
65
|
+
issues.push({ code: 'SCHEMA_ENUM', path, message: 'Value is not one of the allowed values.' });
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (typeof value === 'string') {
|
|
69
|
+
const length = codePointLength(value);
|
|
70
|
+
if (schema.minLength !== undefined && value.trim().length === 0) {
|
|
71
|
+
issues.push({ code: 'SCHEMA_BLANK_STRING', path, message: 'A non-empty string cannot contain only whitespace.' });
|
|
72
|
+
}
|
|
73
|
+
if (schema.minLength !== undefined && length < schema.minLength) {
|
|
74
|
+
issues.push({ code: 'SCHEMA_MIN_LENGTH', path, message: `String must contain at least ${schema.minLength} character(s).` });
|
|
75
|
+
}
|
|
76
|
+
if (schema.maxLength !== undefined && length > schema.maxLength) {
|
|
77
|
+
issues.push({ code: 'SCHEMA_MAX_LENGTH', path, message: `String must contain no more than ${schema.maxLength} character(s).` });
|
|
78
|
+
}
|
|
79
|
+
if (schema.pattern && !new RegExp(schema.pattern).test(value)) {
|
|
80
|
+
issues.push({ code: 'SCHEMA_PATTERN', path, message: 'String does not match the required pattern.' });
|
|
81
|
+
}
|
|
82
|
+
if (schema.format === 'date-time' && !isDateTime(value)) {
|
|
83
|
+
issues.push({ code: 'SCHEMA_FORMAT', path, message: 'Expected an ISO 8601 date-time with a timezone.' });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (typeof value === 'number' && schema.minimum !== undefined && value < schema.minimum) {
|
|
87
|
+
issues.push({ code: 'SCHEMA_MINIMUM', path, message: `Number must be at least ${schema.minimum}.` });
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (Array.isArray(value)) {
|
|
91
|
+
if (schema.minItems !== undefined && value.length < schema.minItems) {
|
|
92
|
+
issues.push({ code: 'SCHEMA_MIN_ITEMS', path, message: `Array must contain at least ${schema.minItems} item(s).` });
|
|
93
|
+
}
|
|
94
|
+
if (schema.items) {
|
|
95
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
96
|
+
issues.push(...schemaIssues(value[index], schema.items, root, `${path}[${index}]`));
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (isPlainObject(value)) {
|
|
102
|
+
for (const required of schema.required ?? []) {
|
|
103
|
+
if (!Object.hasOwn(value, required)) {
|
|
104
|
+
issues.push({ code: 'SCHEMA_REQUIRED', path: `${path}.${required}`, message: 'Required property is missing.' });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
if (schema.minProperties !== undefined && Object.keys(value).length < schema.minProperties) {
|
|
108
|
+
issues.push({ code: 'SCHEMA_MIN_PROPERTIES', path, message: `Object must contain at least ${schema.minProperties} property/properties.` });
|
|
109
|
+
}
|
|
110
|
+
for (const [key, propertyValue] of Object.entries(value)) {
|
|
111
|
+
// Own members only: `constructor` or `__proto__` must not resolve to Object.prototype.
|
|
112
|
+
const propertySchema = schema.properties && Object.hasOwn(schema.properties, key) ? schema.properties[key] : undefined;
|
|
113
|
+
if (propertySchema) {
|
|
114
|
+
issues.push(...schemaIssues(propertyValue, propertySchema, root, `${path}.${key}`));
|
|
115
|
+
} else if (schema.additionalProperties === false) {
|
|
116
|
+
issues.push({ code: 'SCHEMA_ADDITIONAL_PROPERTY', path: `${path}.${key}`, message: 'Unknown property is not allowed.' });
|
|
117
|
+
} else if (schema.additionalProperties && typeof schema.additionalProperties === 'object') {
|
|
118
|
+
issues.push(...schemaIssues(propertyValue, schema.additionalProperties, root, `${path}.${key}`));
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
return issues;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Array.from(value).length without building the array: a surrogate pair counts once, a lone surrogate once. */
|
|
127
|
+
function codePointLength(value: string): number {
|
|
128
|
+
let length = value.length;
|
|
129
|
+
for (let index = 0; index + 1 < value.length; index += 1) {
|
|
130
|
+
const unit = value.charCodeAt(index);
|
|
131
|
+
if (unit >= 0xd800 && unit <= 0xdbff) {
|
|
132
|
+
const next = value.charCodeAt(index + 1);
|
|
133
|
+
if (next >= 0xdc00 && next <= 0xdfff) { length -= 1; index += 1; }
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return length;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function resolveSchemaReference(root: JsonSchema, reference: string): JsonSchema | undefined {
|
|
140
|
+
if (!reference.startsWith('#/')) return undefined;
|
|
141
|
+
let value: unknown = root;
|
|
142
|
+
for (const token of reference.slice(2).split('/').map((part) => part.replaceAll('~1', '/').replaceAll('~0', '~'))) {
|
|
143
|
+
if (!isPlainObject(value) || !Object.hasOwn(value, token)) return undefined;
|
|
144
|
+
value = value[token];
|
|
145
|
+
}
|
|
146
|
+
return isPlainObject(value) ? value as JsonSchema : undefined;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function matchesType(value: unknown, type: string): boolean {
|
|
150
|
+
switch (type) {
|
|
151
|
+
case 'object': return isPlainObject(value);
|
|
152
|
+
case 'array': return Array.isArray(value);
|
|
153
|
+
case 'string': return typeof value === 'string';
|
|
154
|
+
case 'integer': return typeof value === 'number' && Number.isInteger(value);
|
|
155
|
+
case 'number': return typeof value === 'number' && Number.isFinite(value);
|
|
156
|
+
case 'boolean': return typeof value === 'boolean';
|
|
157
|
+
case 'null': return value === null;
|
|
158
|
+
default: return false;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function isJsonValue(value: unknown, active = new WeakSet<object>()): boolean {
|
|
163
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean') return true;
|
|
164
|
+
if (typeof value === 'number') return Number.isFinite(value);
|
|
165
|
+
if (Array.isArray(value)) {
|
|
166
|
+
if (active.has(value)) return false;
|
|
167
|
+
active.add(value);
|
|
168
|
+
const valid = value.every((item) => isJsonValue(item, active));
|
|
169
|
+
active.delete(value);
|
|
170
|
+
return valid;
|
|
171
|
+
}
|
|
172
|
+
if (isPlainObject(value)) {
|
|
173
|
+
if (active.has(value)) return false;
|
|
174
|
+
active.add(value);
|
|
175
|
+
const valid = Object.values(value).every((item) => isJsonValue(item, active));
|
|
176
|
+
active.delete(value);
|
|
177
|
+
return valid;
|
|
178
|
+
}
|
|
179
|
+
return false;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function isPlainObject(value: unknown): value is Record<string, any> {
|
|
183
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
|
|
184
|
+
const prototype = Object.getPrototypeOf(value);
|
|
185
|
+
return prototype === Object.prototype || prototype === null;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function sameJsonValue(left: unknown, right: unknown): boolean {
|
|
189
|
+
return canonicalJson(left) === canonicalJson(right);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function isDateTime(value: string): boolean {
|
|
193
|
+
const match = value.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(Z|([+-])(\d{2}):(\d{2}))$/);
|
|
194
|
+
if (!match || !Number.isFinite(Date.parse(value))) return false;
|
|
195
|
+
const year = Number(match[1]);
|
|
196
|
+
const month = Number(match[2]);
|
|
197
|
+
const day = Number(match[3]);
|
|
198
|
+
const hour = Number(match[4]);
|
|
199
|
+
const minute = Number(match[5]);
|
|
200
|
+
const second = Number(match[6]);
|
|
201
|
+
const offsetHour = Number(match[9] ?? 0);
|
|
202
|
+
const offsetMinute = Number(match[10] ?? 0);
|
|
203
|
+
const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
204
|
+
const daysInMonth = [31, leapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
205
|
+
const offsetWithinRange = offsetHour < 14 || (offsetHour === 14 && offsetMinute === 0);
|
|
206
|
+
return month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth[month - 1]!
|
|
207
|
+
&& hour <= 23 && minute <= 59 && second <= 59 && offsetMinute <= 59 && offsetWithinRange;
|
|
208
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { ImporterReceiptTrustPolicy } from '../receipt/types.ts';
|
|
2
|
+
|
|
3
|
+
export type ImporterStatus = 'verified' | 'documented format' | 'none';
|
|
4
|
+
|
|
5
|
+
export interface ImporterEvidenceArtifact {
|
|
6
|
+
link: string;
|
|
7
|
+
sha256: string;
|
|
8
|
+
size: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface DocumentedFormatEvidence extends ImporterEvidenceArtifact {
|
|
12
|
+
sourceRepository: string;
|
|
13
|
+
sourceRevision: string;
|
|
14
|
+
sourcePath: string;
|
|
15
|
+
sourceSha256: string;
|
|
16
|
+
validation: 'synthetic-only';
|
|
17
|
+
realExport: 'not-supplied';
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface VerifiedEvidence extends ImporterEvidenceArtifact {
|
|
21
|
+
research: ImporterEvidenceArtifact;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface NoneEvidence extends ImporterEvidenceArtifact {
|
|
25
|
+
reason: string;
|
|
26
|
+
checkedAt: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface VerifiedImporter {
|
|
30
|
+
incumbent: string;
|
|
31
|
+
product: string;
|
|
32
|
+
status: 'verified';
|
|
33
|
+
evidence: VerifiedEvidence;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface DocumentedImporter {
|
|
37
|
+
incumbent: string;
|
|
38
|
+
product: string;
|
|
39
|
+
status: 'documented format';
|
|
40
|
+
evidence: DocumentedFormatEvidence;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface NoImporter {
|
|
44
|
+
incumbent: string;
|
|
45
|
+
product: string;
|
|
46
|
+
status: 'none';
|
|
47
|
+
evidence: NoneEvidence;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export type ImporterRecord = VerifiedImporter | DocumentedImporter | NoImporter;
|
|
51
|
+
|
|
52
|
+
export interface ImportersDocument {
|
|
53
|
+
$schema: './schema/importers.schema.json';
|
|
54
|
+
schemaVersion: 1;
|
|
55
|
+
importers: ImporterRecord[];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** A resolver must return the bytes it actually resolved and the final URL. */
|
|
59
|
+
export interface ResolvedEvidenceArtifact {
|
|
60
|
+
url: string;
|
|
61
|
+
bytes: Uint8Array;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Trust anchors belong to the consumer, never to the status document. */
|
|
65
|
+
export interface ImporterEvidencePort {
|
|
66
|
+
resolve: (link: string) => ResolvedEvidenceArtifact | undefined | Promise<ResolvedEvidenceArtifact | undefined>;
|
|
67
|
+
trustedHosts: readonly string[];
|
|
68
|
+
receiptPublicKeys?: Readonly<Record<string, string>>;
|
|
69
|
+
receiptTrustPolicy?: ImporterReceiptTrustPolicy;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface ImporterValidationIssue {
|
|
73
|
+
code: string;
|
|
74
|
+
path: string;
|
|
75
|
+
message: string;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface ImporterValidationResult {
|
|
79
|
+
valid: boolean;
|
|
80
|
+
issues: ImporterValidationIssue[];
|
|
81
|
+
evidence: {
|
|
82
|
+
required: number;
|
|
83
|
+
resolved: number;
|
|
84
|
+
verifiedReceipts: number;
|
|
85
|
+
};
|
|
86
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Trusted server callers have already admitted a delegated principal. These
|
|
2
|
+
// commands reuse native administration, without minting or inventing a session.
|
|
3
|
+
import { administration } from './admin.mjs';
|
|
4
|
+
import { bindPolicyActor } from '../scheduled/fence.mjs';
|
|
5
|
+
import { emailAllowed } from './roles.mjs';
|
|
6
|
+
import { deny } from '../errors.mjs';
|
|
7
|
+
import { normalizeEmail } from '../policy.mjs';
|
|
8
|
+
|
|
9
|
+
export function delegatedAdministration(context, { personId, auditLabel, agentId }) {
|
|
10
|
+
const { store, config } = context;
|
|
11
|
+
if (typeof agentId !== 'string' || !agentId || typeof personId !== 'string' || !personId || typeof auditLabel !== 'string' || !auditLabel.trim()) deny('invalid_delegation', 400);
|
|
12
|
+
const request = new Request(new URL('/auth/delegated-administration', config.origin), {
|
|
13
|
+
method: 'POST', headers: { origin: config.origin, host: new URL(config.origin).host },
|
|
14
|
+
});
|
|
15
|
+
async function commands() {
|
|
16
|
+
const operator = await store.operator(personId);
|
|
17
|
+
if (!operator || operator.status !== 'active' || !emailAllowed(operator.email, config.allowList)) deny('unauthenticated', 401);
|
|
18
|
+
const actor = Object.freeze({ operator });
|
|
19
|
+
bindPolicyActor(actor, () => ({
|
|
20
|
+
sql: "EXISTS(SELECT 1 FROM oa_operators WHERE id=? AND version=? AND status='active' AND role=?)",
|
|
21
|
+
args: [operator.id, operator.version, operator.role],
|
|
22
|
+
}));
|
|
23
|
+
const audit = async event => {
|
|
24
|
+
const extra = context.audit ? await context.audit({ ...event, actorLabel: auditLabel, sponsorId: personId }) : [];
|
|
25
|
+
return [[`INSERT INTO oa_auth_audit(id,actor_id,action,value,created_at) VALUES(?,?,?,?,?)`,
|
|
26
|
+
[crypto.randomUUID(), `agent:${agentId}`, event.action, JSON.stringify({ operatorId: event.subjectId, detail: event.detail,
|
|
27
|
+
actor: auditLabel, for: personId }), event.now]], ...extra];
|
|
28
|
+
};
|
|
29
|
+
return administration({ ...context, authenticate: async () => actor, audit });
|
|
30
|
+
}
|
|
31
|
+
return Object.freeze({
|
|
32
|
+
async invite(input) {
|
|
33
|
+
if (input.role === 'owner') deny('delegated_owner_change', 403);
|
|
34
|
+
const admin = await commands();
|
|
35
|
+
const plan = await admin.prepareInvitation(request, input, { operator: await store.byEmail(normalizeEmail(input.email)) });
|
|
36
|
+
if (!await store.invite(plan.mutation, plan.actor, plan)) deny('invitation_conflict', 409);
|
|
37
|
+
await plan.afterCommit();
|
|
38
|
+
return { status: 'accepted' };
|
|
39
|
+
},
|
|
40
|
+
async setRole(operatorId, role) {
|
|
41
|
+
const target = await store.operator(operatorId);
|
|
42
|
+
// A delegation cannot widen its sponsor or transfer owner authority.
|
|
43
|
+
if (operatorId === personId || target?.role === 'owner' || role === 'owner') deny('delegated_owner_change', 403);
|
|
44
|
+
return (await commands()).setRole(request, operatorId, role);
|
|
45
|
+
},
|
|
46
|
+
async listOperators() { return (await commands()).listOperators(request); },
|
|
47
|
+
});
|
|
48
|
+
}
|
|
@@ -220,6 +220,13 @@ export interface OperatorAuth<R extends string = Role> {
|
|
|
220
220
|
cancelInvitation(request: Request, operatorId: string): Promise<Operator<R>>;
|
|
221
221
|
setOperatorStatus(request: Request, operatorId: string, status: 'active' | 'inactive'): Promise<Operator<R>>;
|
|
222
222
|
setRole(request: Request, operatorId: string, role: Role): Promise<Operator<R>>;
|
|
223
|
+
/** Trusted server only: caller admits the delegated principal; native policy
|
|
224
|
+
* and sponsor authority are checked again in each mutation transaction. */
|
|
225
|
+
delegatedAdministration(input: { personId: string; auditLabel: string; agentId: string }): {
|
|
226
|
+
invite(input: { email: string; displayName: string; role?: 'admin' | 'member'; returnTo?: string }): Promise<{ status: 'accepted' }>;
|
|
227
|
+
setRole(operatorId: string, role: 'admin' | 'member'): Promise<Operator<R>>;
|
|
228
|
+
listOperators(): Promise<Operator<R>[]>;
|
|
229
|
+
};
|
|
223
230
|
listSessions(request: Request, operatorId?: string): Promise<Array<{ id: string; kind: SessionKind; createdAt: number; expiresAt: number; active: boolean }>>;
|
|
224
231
|
revokeSession(request: Request, sessionId: string): Promise<void>;
|
|
225
232
|
issueReviewSession(request: Request, input?: { returnTo?: string }): Promise<CompletedSession<R>>;
|
|
@@ -25,6 +25,7 @@ import { displayNameChange } from './accounts/display-name.mjs';
|
|
|
25
25
|
import { isLocalCli } from './local-cli.mjs';
|
|
26
26
|
import { devAdmitted } from './dev-admission.mjs';
|
|
27
27
|
import { oneClickAccounts } from './accounts/one-click.mjs';
|
|
28
|
+
import { delegatedAdministration } from './accounts/delegated.mjs';
|
|
28
29
|
|
|
29
30
|
export { STEP_UP_ACTIONS, STEP_UP_SECONDS } from './identity/email-link/index.mjs';
|
|
30
31
|
export function createOperatorAuth(options) {
|
|
@@ -80,6 +81,7 @@ export function createOperatorAuth(options) {
|
|
|
80
81
|
const external = legacyAdmission({ admission, config });
|
|
81
82
|
return Object.freeze({
|
|
82
83
|
...admin,
|
|
84
|
+
delegatedAdministration: input => delegatedAdministration(adminContext, input),
|
|
83
85
|
businessTeam: businessTeam(adminContext),
|
|
84
86
|
...businessSettingsControls({ businessSettings: options.businessSettings, config, accounts, authenticate, requireFreshProof, store, clock }),
|
|
85
87
|
...(options.scheduledPolicies ? { scheduledPolicies: scheduledPolicies({ definitions: options.scheduledPolicies, store, config, clock, authenticate, requireFreshProof, rolePolicy }) } : {}),
|
|
@@ -67,8 +67,11 @@ belong to the current runtime or environment and never travel:
|
|
|
67
67
|
| `rer_erasure_blobs`, `rer_erasure_guard`, `rer_erasure_scope`, `rer_erasure_rates` | Erasure work queues, transaction guards, working scope and local rate limits. |
|
|
68
68
|
| `rer_demo` | Local demo setup markers. |
|
|
69
69
|
|
|
70
|
-
`excludedTables` combines this list with the
|
|
71
|
-
|
|
70
|
+
`excludedTables` combines this list with `oa_%` and the exact Base owner-claim
|
|
71
|
+
identities `oc_owner_claims` and `oc_idp_grants`. Other `oc_` names must be
|
|
72
|
+
explicitly declared in `includeTables` or `excludeTables`; transfers refuse
|
|
73
|
+
`identity_table_undeclared:<name>` rather than silently dropping product rows.
|
|
74
|
+
Policy may override identity exclusions through `includeTables`,
|
|
72
75
|
but naming a mandatory platform table there refuses construction with
|
|
73
76
|
`platform_table:<name>` and a message identifying the table.
|
|
74
77
|
`excludedTable(name, policy)` always returns true for mandatory platform tables,
|
|
@@ -237,11 +240,12 @@ provider operation.
|
|
|
237
240
|
| Compatible `d1_migrations`, every recorded name exactly equal to its checkout filename | `{nativeApply:true}`; Wrangler may apply its pending files. Plain Wrangler names remain supported; tracked history must also match hashes and applied states. |
|
|
238
241
|
| Native alias-only or hash-only relocation, or an unmapped native data-only row | `migration_ledger:incompatible`; restore the matching checkout or reconcile through the owning runner before native apply. |
|
|
239
242
|
| Sole, fully applied matching `rer_migrations` | `{nativeApply:false}`; preserve Platform's ledger and skip Wrangler. |
|
|
240
|
-
|
|
|
241
|
-
|
|
|
243
|
+
| Fully applied matching `_rer_deploy_migrations` plus plain Wrangler `d1_migrations` bookkeeping | `{nativeApply:false}`; preserve the deploy history and skip Wrangler. Bookkeeping names must belong to that history. A tracked D1 ledger must match the deploy history's names, hashes and order. |
|
|
244
|
+
| Any pending checkout file with Platform history or the legacy pair | `migration_ledger:unapplied`, naming the file (`error.migration`); apply it through the owning runner first. |
|
|
245
|
+
| Other multiple ledgers, or disagreeing tracked native histories | `migration_ledger:multiple`; reconcile history through its owning runner. |
|
|
242
246
|
| Legacy `_rer_deploy_migrations` alone | `migration_ledger:runner`; use its owning runner, which can adopt the history. |
|
|
243
247
|
| Invalid ledger shape, row or binding | `migration_ledger:incompatible` or `migration_ledger:binding`. |
|
|
244
|
-
| Partial Platform batch or non-applied tracked row | `migration_ledger:uncertain`; resolve the incomplete operation first. |
|
|
248
|
+
| Partial Platform batch or non-applied tracked or legacy row | `migration_ledger:uncertain`; resolve the incomplete operation first. |
|
|
245
249
|
| Unknown hash/name, ambiguous hash/alias or conflicting name/hash | `migration_ledger:unknown`, `:ambiguous` or `:conflict`; use the matching checkout and declaration. |
|
|
246
250
|
|
|
247
251
|
Refusals throw `PortabilityError` with status 409 and a constant `code`;
|
|
@@ -275,8 +279,10 @@ owner claim. Such a destination keeps that claim and recovers access through
|
|
|
275
279
|
ordinary native sign-in; setup does not grant another owner. Other tables are
|
|
276
280
|
discovered automatically. Exclusion rules follow SQLite's ASCII identifier case matching.
|
|
277
281
|
Unlisted virtual tables, hidden virtual-table columns and foreign keys into
|
|
278
|
-
excluded tables fail by name.
|
|
279
|
-
|
|
282
|
+
excluded tables fail by name. Restore rebuilds policy-declared external-content
|
|
283
|
+
FTS5 indexes from their content tables in the same transaction as the restored
|
|
284
|
+
rows. The product must explicitly regenerate other derived data. A schema
|
|
285
|
+
upgrade may change columns but cannot silently omit tables.
|
|
280
286
|
|
|
281
287
|
Provider link keys and transient provider sessions never travel. Export marks
|
|
282
288
|
retained dependency links as needing re-link and turns provider sign-in and
|
|
@@ -433,7 +439,7 @@ Re-export from the original installation to carry the complete definitions.
|
|
|
433
439
|
A new archive explicitly records even an empty object inventory, so later
|
|
434
440
|
additive migrations can still be placed normally. The separate acknowledged
|
|
435
441
|
v1 recovery path remains an explicitly unverified recovery, as documented below.
|
|
436
|
-
Version 2 backups without that inventory
|
|
442
|
+
Version 2 backups without that inventory use recorded migration replay when it proves the complete destination schema, or the acknowledged recovery below.
|
|
437
443
|
|
|
438
444
|
New exports use archive version 2. The closing `archiveHash` is SHA-256 of
|
|
439
445
|
canonical JSON `{manifest,parts}`, where `manifest` is the complete manifest
|
|
@@ -468,20 +474,30 @@ authenticate it. If the original installation is unavailable, use the explicit
|
|
|
468
474
|
[backup-only v1 recovery](#backup-only-v1-recovery) below. Normal import still
|
|
469
475
|
requires version 2 integrity.
|
|
470
476
|
|
|
471
|
-
##
|
|
477
|
+
## Older version 2 backups and acknowledged recovery
|
|
472
478
|
|
|
473
479
|
A fresh export from a current rer is preferred whenever the original installation
|
|
474
480
|
is available. Current archives carry the complete schema inventory and restore
|
|
475
481
|
without any acknowledgment. Version 2 backups written by rer 0.2.79 or earlier
|
|
476
|
-
can lack `schemaObjects`.
|
|
477
|
-
|
|
482
|
+
can lack `schemaObjects`. Ordinary import verifies such a backup without an
|
|
483
|
+
acknowledgment when its nonempty recorded migration history, resolved against the
|
|
484
|
+
destination's own applied files in order, replays to the complete live destination
|
|
485
|
+
schema identity, including indexes, views and triggers. The same replay's tables
|
|
486
|
+
must match the archive's table definitions. The archive's ledger, when present,
|
|
487
|
+
must agree with its recorded names, and available hashes must match. Missing
|
|
488
|
+
history, failed replay, table drift or a different complete destination identity
|
|
489
|
+
still refuses `schema_mismatch:legacy_schema` before staging. Source SQL is never
|
|
490
|
+
installed. This verified path records no `schemaUnverified` receipt.
|
|
491
|
+
|
|
492
|
+
When that proof is unavailable, the owner can explicitly accept that its schema
|
|
493
|
+
objects are unverified:
|
|
478
494
|
|
|
479
495
|
```sh
|
|
480
496
|
rer import --input exports/retained.rer --yes --acknowledge-unverified-schema-objects
|
|
481
497
|
```
|
|
482
498
|
|
|
483
|
-
This accepts only the missing inventory
|
|
484
|
-
|
|
499
|
+
This accepts only the missing inventory and preserves the existing recovery path,
|
|
500
|
+
even when ordinary import could verify the backup. The acknowledgment never accepts
|
|
485
501
|
version 1 metadata; that separate recovery still needs both v1 flags below.
|
|
486
502
|
The destination must be empty under the existing product emptiness rule:
|
|
487
503
|
non-migration rows in product tables refuse `target_not_empty:<table>` before
|
|
@@ -994,6 +1010,7 @@ modules/portability/sqlite-tokens.mjs
|
|
|
994
1010
|
modules/portability/bookkeeping.mjs
|
|
995
1011
|
modules/portability/storage.mjs
|
|
996
1012
|
modules/portability/copies.mjs
|
|
1013
|
+
modules/portability/derived.mjs
|
|
997
1014
|
modules/portability/dev-data.mjs
|
|
998
1015
|
modules/portability/provider-data.mjs
|
|
999
1016
|
modules/portability/policy-data.mjs
|
|
@@ -1109,6 +1126,13 @@ in destination migrations, including objects attached to excluded tables. Intern
|
|
|
1109
1126
|
prefixes are compared literally. A scratch native import preflight checks the
|
|
1110
1127
|
projected archive before native restore can open the destination.
|
|
1111
1128
|
|
|
1129
|
+
Policy-declared derived virtual tables omitted from a Managed dump are created
|
|
1130
|
+
in the sandbox from the destination's migrated definitions. Their triggers must
|
|
1131
|
+
still be present and compatible; omitting those triggers remains a schema
|
|
1132
|
+
refusal. The dump statement allowlist still refuses all `CREATE VIRTUAL TABLE`
|
|
1133
|
+
statements, including declared names. A native copy-normalization SQLite failure
|
|
1134
|
+
is reported as `copy_normalization_failed`, without SQL diagnostics or row values.
|
|
1135
|
+
|
|
1112
1136
|
The current intake supports one database and declared buckets, local Workers
|
|
1113
1137
|
transport, stored ZIP members, at most 10,000 entries and statements, a 128 MiB
|
|
1114
1138
|
archive, 64 MiB members, 4 MiB metadata members and 16 MiB of SQL, with each SQL
|
|
@@ -34,8 +34,8 @@ async function placement(db,manifest,cat,replay,ledger,history,legacyRecovery,un
|
|
|
34
34
|
const recorded=historyEntries && matchMigrationLedger(historyEntries,files,replay);
|
|
35
35
|
// Only explicitly acknowledged v1 recovery may use the old projection for
|
|
36
36
|
// archive placement. The live destination check above remains complete, and
|
|
37
|
-
//
|
|
38
|
-
//
|
|
37
|
+
// current v2 imports use their authenticated object inventory. Verified legacy
|
|
38
|
+
// v2 uses the replayed complete identity; acknowledged recovery places by tables only.
|
|
39
39
|
const schemaAfter=names=>replay.schemaAfter(names,legacyRecovery && manifest.schemaObjects===undefined?{legacyExcludedObjects:true}:unverified?{tablesOnly:true}:undefined);
|
|
40
40
|
if(unverified && archived && manifest.migrations)insist(canonicalJson(matchMigrationLedger(archived,files,replay))===canonicalJson(recorded),'schema_mismatch:migration_history',409);
|
|
41
41
|
let earlier,unapplied;
|
|
@@ -69,6 +69,26 @@ async function placement(db,manifest,cat,replay,ledger,history,legacyRecovery,un
|
|
|
69
69
|
const {replays,rebuilt}=laterData({applied,unapplied,replay,catalogue,archived:archivedTables,empty,tables,secrets:manifest.excludedColumns??{},manifest:manifest.tables});
|
|
70
70
|
return {applied,earlier,replays,rebuilt};
|
|
71
71
|
}
|
|
72
|
+
// Old v2 writers recorded tables and applied migration names, but no behavioral
|
|
73
|
+
// object inventory. Verify both projections: the recorded files must reproduce
|
|
74
|
+
// the complete live schema, and their tables must reproduce the archive. Never
|
|
75
|
+
// guess an unrecorded prefix or install source SQL to fill missing evidence.
|
|
76
|
+
export async function verifiedLegacySchema(db,manifest,cat,migrations,history) {
|
|
77
|
+
if(!migrations)return false;
|
|
78
|
+
const replay=await migrations(),ledger=await destinationLedger(db)??[];
|
|
79
|
+
try {
|
|
80
|
+
const files=replay.names.map(name=>({name,sha256:replay.sha256?.(name),aliases:replay.aliases?.(name)}));
|
|
81
|
+
const archived=history(),entries=manifest.migrations?.map(name=>archived?.find(entry=>entry.name===name)??{name})??archived;
|
|
82
|
+
if(!entries?.length)return false;
|
|
83
|
+
const applied=matchMigrationLedger(ledger,files,replay),recorded=matchMigrationLedger(entries,files,replay);
|
|
84
|
+
if(!recorded.length || canonicalJson(applied)!==canonicalJson(replay.names)
|
|
85
|
+
|| !recorded.every((name,i)=>applied.indexOf(name)>(i?applied.indexOf(recorded[i-1]):-1)))return false;
|
|
86
|
+
if(archived && manifest.migrations && canonicalJson(matchMigrationLedger(archived,files,replay))!==canonicalJson(recorded))return false;
|
|
87
|
+
return await replay.schemaAfter(applied)===cat.identity
|
|
88
|
+
&& await replay.schemaAfter(recorded)===cat.identity
|
|
89
|
+
&& await replay.schemaAfter(recorded,{tablesOnly:true})===manifest.schema;
|
|
90
|
+
}catch{return false;} // Unknown history or a failed replay is not verification.
|
|
91
|
+
}
|
|
72
92
|
// An archive with the destination's schema identity can still predate later
|
|
73
93
|
// migrations that changed only data (a purge or a backfill).
|
|
74
94
|
// Those that change restorable data are refused like any other. Without a
|
|
@@ -3,7 +3,7 @@ import { canonicalJson, base64, unbase64, utf8 } from './hash.mjs';
|
|
|
3
3
|
import { schemaIdentityOf } from './schema-identity.mjs';
|
|
4
4
|
import { platformTables, platformTable, identifier, matches } from './bookkeeping.mjs';
|
|
5
5
|
/** Platform bookkeeping is mandatory; operator identity remains a seed choice. */
|
|
6
|
-
export const excludedTables=Object.freeze([...platformTables,'oa_%','
|
|
6
|
+
export const excludedTables=Object.freeze([...platformTables,'oa_%','oc_owner_claims','oc_idp_grants']);
|
|
7
7
|
const fields=['product','excludeTables','includeTables','derivedTables','secretColumns','exportRow','importSafety','importRow','replaceableTables','requiredConfiguration','validateStaged','acceptedSchemas','buckets','extraPayloads','partBytes'];
|
|
8
8
|
const name=value=>typeof value==='string' && value.length>0 && value.length<=512 && !/[\x00-\x1f]/.test(value);
|
|
9
9
|
const names=value=>Array.isArray(value) && value.every(name) && new Set(value).size===value.length;
|
|
@@ -51,7 +51,17 @@ export function policy(input) {
|
|
|
51
51
|
return {...result,excludeTables:[...excludedTables,...result.excludeTables]};
|
|
52
52
|
}
|
|
53
53
|
/** Platform tables are always excluded; explicit includes override only optional exclusions. */
|
|
54
|
-
export
|
|
54
|
+
export function excludedTable(table,input={}) {
|
|
55
|
+
if(platformTable(table))return true;
|
|
56
|
+
if((input.includeTables??[]).includes(table))return false;
|
|
57
|
+
if([...excludedTables,...(input.excludeTables??[])].some(pattern=>matches(table,pattern)))return true;
|
|
58
|
+
if(matches(table,'oc_%')) {
|
|
59
|
+
const error=new PortabilityError('identity_table_undeclared:'+table,409);
|
|
60
|
+
error.message='Table "'+table+'" shares the owner-claim prefix. Declare it in includeTables to transfer its rows or excludeTables to omit them.';
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
55
65
|
async function archived(db,config) {
|
|
56
66
|
const objects=await all(db,"SELECT name,sql,type,tbl_name FROM sqlite_master WHERE sql IS NOT NULL AND substr(lower(name),1,7) <> 'sqlite_' AND substr(lower(name),1,4) <> '_cf_' ORDER BY name");
|
|
57
67
|
const kinds=await all(db,'PRAGMA table_list');
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { all,statement,quote,insist } from './storage.mjs';
|
|
1
|
+
import { all,statement,quote,insist,PortabilityError } from './storage.mjs';
|
|
2
2
|
import { projectedColumns,encodedRow,mapRow,bindCell,writableColumns } from './catalogue.mjs';
|
|
3
3
|
import { canonicalJson, utf8 } from './hash.mjs';
|
|
4
4
|
import { generatedCopySQL } from './generated.mjs';
|
|
@@ -43,6 +43,13 @@ export async function readCopy(db,table,copy,offset,limit,encoded=false) {
|
|
|
43
43
|
return raw.map((row,i)=>({row,meta:meta[i]}));
|
|
44
44
|
}
|
|
45
45
|
export async function normalizeCopy(context,table,copy) {
|
|
46
|
+
try { return await normalize(context,table,copy); }
|
|
47
|
+
catch(error) {
|
|
48
|
+
if(error instanceof PortabilityError)throw error;
|
|
49
|
+
throw new PortabilityError('copy_normalization_failed',409);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
async function normalize(context,table,copy) {
|
|
46
53
|
const {db,config}=context,secrets=config.secretColumns[table.name]??[];
|
|
47
54
|
// Generated reads must reflect exactly the base cells a restore will receive.
|
|
48
55
|
if(table.columns.some(c=>c.generated)&&secrets.length)await db.prepare(`UPDATE ${quote(copy)} SET ${secrets.map(name=>quote(name)+'=NULL').join(',')}`).run();
|