File size: 7,823 Bytes
76289e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
// Shared validation for plugin-owned keyed JSON and blob stores.
const MAX_PLUGIN_STORE_NAMESPACE_BYTES = 128;
const MAX_PLUGIN_STORE_KEY_BYTES = 512;
const MAX_PLUGIN_STORE_JSON_BYTES = 65_536;
const MAX_PLUGIN_STORE_JSON_DEPTH = 64;

const NAMESPACE_PATTERN = /^[a-z0-9][a-z0-9._-]*$/iu;
const textEncoder = new TextEncoder();

type PluginStoreValidationErrors = {
  invalid(message: string): Error;
  limit(message: string): Error;
};

type PluginStoreOptionSignature = Record<string, string | number | undefined>;

type PluginStoreOptionPolicy<T extends PluginStoreOptionSignature> = {
  resolveOverflowPolicy(value: unknown): "evict-oldest" | "reject-new";
  assertConsistent(pluginId: string, namespace: string, signature: T): void;
  clear(): void;
};

export function createPluginStoreOptionPolicy<T extends PluginStoreOptionSignature>(params: {
  label: string;
  invalid(message: string): Error;
}): PluginStoreOptionPolicy<T> {
  const signatures = new Map<string, T>();

  return {
    resolveOverflowPolicy(value) {
      if (value === undefined || value === "evict-oldest") {
        return "evict-oldest";
      }
      if (value === "reject-new") {
        return value;
      }
      throw params.invalid(`${params.label} overflowPolicy must be evict-oldest or reject-new`);
    },
    assertConsistent(pluginId, namespace, signature) {
      const key = `${pluginId}\0${namespace}`;
      const existing = signatures.get(key);
      if (!existing) {
        signatures.set(key, signature);
        return;
      }
      const compatible =
        Object.entries(existing).every(([name, value]) => signature[name] === value) &&
        Object.entries(signature).every(([name, value]) => existing[name] === value);
      if (!compatible) {
        throw params.invalid(
          `${params.label} namespace ${namespace} for ${pluginId} was reopened with incompatible options`,
        );
      }
    },
    clear() {
      signatures.clear();
    },
  };
}

function assertMaxUtf8Bytes(params: {
  label: string;
  value: string;
  maxBytes: number;
  errors: PluginStoreValidationErrors;
}): void {
  if (textEncoder.encode(params.value).byteLength > params.maxBytes) {
    throw params.errors.invalid(`${params.label} must be <= ${params.maxBytes} bytes`);
  }
}

export function validatePluginStoreNamespace(params: {
  value: string;
  label: string;
  errors: PluginStoreValidationErrors;
}): string {
  const trimmed = params.value.trim();
  if (!NAMESPACE_PATTERN.test(trimmed)) {
    throw params.errors.invalid(
      `${params.label} namespace must be a safe path segment: ${params.value}`,
    );
  }
  assertMaxUtf8Bytes({
    label: `${params.label} namespace`,
    value: trimmed,
    maxBytes: MAX_PLUGIN_STORE_NAMESPACE_BYTES,
    errors: params.errors,
  });
  return trimmed;
}

export function validatePluginStoreKey(params: {
  value: string;
  label: string;
  errors: PluginStoreValidationErrors;
}): string {
  const trimmed = params.value.trim();
  if (!trimmed) {
    throw params.errors.invalid(`${params.label} entry key must not be empty`);
  }
  assertMaxUtf8Bytes({
    label: `${params.label} entry key`,
    value: trimmed,
    maxBytes: MAX_PLUGIN_STORE_KEY_BYTES,
    errors: params.errors,
  });
  return trimmed;
}

export function validatePluginStorePositiveInteger(params: {
  value: number;
  label: string;
  errors: PluginStoreValidationErrors;
}): number {
  if (!Number.isSafeInteger(params.value) || params.value < 1) {
    throw params.errors.invalid(`${params.label} must be a positive safe integer`);
  }
  return params.value;
}

export function validateOptionalPluginStoreTtlMs(params: {
  value: number | undefined;
  label: string;
  errors: PluginStoreValidationErrors;
}): number | undefined {
  const value = params.value;
  if (value == null) {
    return undefined;
  }
  return validatePluginStorePositiveInteger({ ...params, value });
}

function assertPlainJsonValue(
  value: unknown,
  params: {
    label: string;
    errors: PluginStoreValidationErrors;
    seen: WeakSet<object>;
    path: string;
    depth: number;
  },
): void {
  if (params.depth > MAX_PLUGIN_STORE_JSON_DEPTH) {
    throw params.errors.limit(
      `${params.label} nesting exceeds maximum depth of ${MAX_PLUGIN_STORE_JSON_DEPTH}`,
    );
  }
  if (value === null) {
    return;
  }
  const valueType = typeof value;
  if (valueType === "string" || valueType === "boolean") {
    return;
  }
  if (valueType === "number") {
    if (!Number.isFinite(value)) {
      throw params.errors.invalid(`${params.label} at ${params.path} must be a finite number`);
    }
    return;
  }
  if (valueType !== "object") {
    throw params.errors.invalid(`${params.label} at ${params.path} must be JSON-serializable`);
  }

  const objectValue = value as object;
  if (params.seen.has(objectValue)) {
    throw params.errors.invalid(
      `${params.label} at ${params.path} must not contain circular references`,
    );
  }
  params.seen.add(objectValue);
  try {
    if (Array.isArray(value)) {
      for (let index = 0; index < value.length; index += 1) {
        if (!(index in value)) {
          throw params.errors.invalid(`${params.label} array at ${params.path} must not be sparse`);
        }
        assertPlainJsonValue(value[index], {
          ...params,
          path: `${params.path}[${index}]`,
          depth: params.depth + 1,
        });
      }
      return;
    }

    // Source-plugin realms have their own Object.prototype; class and custom prototypes stay invalid.
    const prototype = Object.getPrototypeOf(objectValue);
    const constructor =
      prototype && Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
    if (
      !prototype ||
      Object.getPrototypeOf(prototype) !== null ||
      typeof constructor !== "function" ||
      Object.getOwnPropertyDescriptor(constructor, "prototype")?.value !== prototype ||
      Function.prototype.toString.call(constructor) !== Function.prototype.toString.call(Object)
    ) {
      throw params.errors.invalid(
        `${params.label} object at ${params.path} must be a plain object`,
      );
    }
    const descriptorEntries = Object.entries(Object.getOwnPropertyDescriptors(objectValue));
    if (Object.getOwnPropertySymbols(objectValue).length > 0) {
      throw params.errors.invalid(
        `${params.label} object at ${params.path} must not use symbol keys`,
      );
    }
    if (descriptorEntries.length !== Object.keys(objectValue).length) {
      throw params.errors.invalid(
        `${params.label} object at ${params.path} must not use non-enumerable properties`,
      );
    }
    for (const [key, descriptor] of descriptorEntries) {
      if (descriptor.get || descriptor.set || !("value" in descriptor)) {
        throw params.errors.invalid(
          `${params.label} object at ${params.path}.${key} must use data properties`,
        );
      }
      assertPlainJsonValue(descriptor.value, {
        ...params,
        path: `${params.path}.${key}`,
        depth: params.depth + 1,
      });
    }
  } finally {
    params.seen.delete(objectValue);
  }
}

export function serializePluginStoreJson(params: {
  value: unknown;
  label: string;
  errors: PluginStoreValidationErrors;
  maxBytes?: number;
}): string {
  assertPlainJsonValue(params.value, {
    label: params.label,
    errors: params.errors,
    seen: new WeakSet<object>(),
    path: "value",
    depth: 0,
  });
  const json = JSON.stringify(params.value);
  if (json === undefined) {
    throw params.errors.invalid(`${params.label} must be JSON-serializable`);
  }
  const maxBytes = params.maxBytes ?? MAX_PLUGIN_STORE_JSON_BYTES;
  if (textEncoder.encode(json).byteLength > maxBytes) {
    throw params.errors.limit(`${params.label} exceeds ${maxBytes} byte limit`);
  }
  return json;
}