@moss-dev/moss-web 1.0.1 → 1.3.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/README.md +94 -4
- package/dist/auth/authenticator.interface.d.ts +14 -0
- package/dist/auth/authenticator.interface.js +1 -0
- package/dist/auth/caching.authenticator.d.ts +12 -0
- package/dist/auth/caching.authenticator.js +49 -0
- package/dist/client.d.ts +50 -6
- package/dist/client.js +230 -75
- package/dist/embedder.d.ts +13 -11
- package/dist/embedder.js +86 -66
- package/dist/index.d.ts +4 -2
- package/dist/index.js +2 -1
- package/dist/model-artifact-ownership.d.ts +18 -0
- package/dist/model-artifact-ownership.js +106 -0
- package/dist/model-config.d.ts +3 -0
- package/dist/model-config.js +8 -0
- package/dist/model-delivery.d.ts +81 -0
- package/dist/model-delivery.js +521 -0
- package/dist/sha256.d.ts +14 -0
- package/dist/sha256.js +152 -0
- package/dist/types.d.ts +53 -1
- package/dist/wasm-runtime-capability.d.ts +20 -0
- package/dist/wasm-runtime-capability.js +75 -0
- package/package.json +7 -7
- package/dist/query-model.d.ts +0 -9
- package/dist/query-model.js +0 -17
|
@@ -0,0 +1,521 @@
|
|
|
1
|
+
import { sha256Hex } from "./sha256.js";
|
|
2
|
+
import { exactModelArtifactIdentity } from "./wasm-runtime-capability.js";
|
|
3
|
+
export const DEFAULT_INDEX_BASE_URL = "https://service.usemoss.dev/index";
|
|
4
|
+
export const DEFAULT_MODEL_ARTIFACT_ORIGIN = "https://models.moss.link";
|
|
5
|
+
const ARTIFACTS_PREFIX = "/artifacts/v1";
|
|
6
|
+
const RELEASE_FILE = "release.json";
|
|
7
|
+
const MODEL_FILE = "model.mossml";
|
|
8
|
+
const SUPPORTED_RELEASE_SCHEMA_VERSIONS = [1, 2];
|
|
9
|
+
const MAX_RELEASE_MANIFEST_BYTES = 1024 * 1024;
|
|
10
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 30000;
|
|
11
|
+
const ARTIFACT_REQUEST_ATTEMPTS = 2;
|
|
12
|
+
const ARTIFACT_CACHE_NAME = "moss-model-artifacts-v1";
|
|
13
|
+
const ARTIFACT_CACHE_PATH = "/.moss-artifact-cache";
|
|
14
|
+
export class ModelDeliveryError extends Error {
|
|
15
|
+
constructor(message, status, code) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = "ModelDeliveryError";
|
|
18
|
+
this.status = status;
|
|
19
|
+
this.code = code;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/** A transport failure worth one more attempt: a stall, a dropped connection, a short body, a 408, a 429 or a 5xx. */
|
|
23
|
+
class ArtifactTransferError extends ModelDeliveryError {
|
|
24
|
+
}
|
|
25
|
+
function isCanonicalSha256(value) {
|
|
26
|
+
return /^[0-9a-f]{64}$/.test(value);
|
|
27
|
+
}
|
|
28
|
+
function isSafeRelativePath(value) {
|
|
29
|
+
if (!value || value.startsWith("/") || value.includes("\\"))
|
|
30
|
+
return false;
|
|
31
|
+
const parts = value.split("/");
|
|
32
|
+
return parts.every((part) => part.length > 0 && part !== "." && part !== "..");
|
|
33
|
+
}
|
|
34
|
+
export function parseArtifactOrigin(value) {
|
|
35
|
+
let url;
|
|
36
|
+
try {
|
|
37
|
+
url = new URL(value);
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
throw new ModelDeliveryError(`Model artifact origin is not a valid URL: ${String(error)}`);
|
|
41
|
+
}
|
|
42
|
+
const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1";
|
|
43
|
+
if (!(url.protocol === "https:" || (url.protocol === "http:" && loopback))) {
|
|
44
|
+
throw new ModelDeliveryError(`Model artifact origin scheme '${url.protocol}' is not allowed for host '${url.hostname}'`);
|
|
45
|
+
}
|
|
46
|
+
if (url.pathname !== "/" || url.search || url.hash || url.username || url.password) {
|
|
47
|
+
throw new ModelDeliveryError("Model artifact origin must be scheme://host[:port] only");
|
|
48
|
+
}
|
|
49
|
+
return { protocol: url.protocol, host: url.host.toLowerCase() };
|
|
50
|
+
}
|
|
51
|
+
function validateGrantedUrl(url, origin, sku, version, object) {
|
|
52
|
+
let parsed;
|
|
53
|
+
try {
|
|
54
|
+
parsed = new URL(url);
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
throw new ModelDeliveryError(`${object} url is not valid: ${String(error)}`);
|
|
58
|
+
}
|
|
59
|
+
const expectedPath = `${ARTIFACTS_PREFIX}/${sku}/${version}/${object}`;
|
|
60
|
+
if (parsed.protocol !== origin.protocol
|
|
61
|
+
|| parsed.host.toLowerCase() !== origin.host
|
|
62
|
+
|| parsed.pathname !== expectedPath
|
|
63
|
+
|| parsed.search
|
|
64
|
+
|| parsed.hash
|
|
65
|
+
|| parsed.username
|
|
66
|
+
|| parsed.password) {
|
|
67
|
+
throw new ModelDeliveryError(`${object} url on ${parsed.host} is outside ${origin.protocol}//${origin.host}${expectedPath}`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function grantedObject(value, name) {
|
|
71
|
+
if (!value || typeof value !== "object") {
|
|
72
|
+
throw new ModelDeliveryError(`Model grant is missing '${name}'`);
|
|
73
|
+
}
|
|
74
|
+
const object = value;
|
|
75
|
+
if (typeof object.url !== "string"
|
|
76
|
+
|| typeof object.capability !== "string"
|
|
77
|
+
|| object.capability.trim() === ""
|
|
78
|
+
|| typeof object.expiresAtMs !== "number") {
|
|
79
|
+
throw new ModelDeliveryError(`Model grant '${name}' has an unsupported shape`);
|
|
80
|
+
}
|
|
81
|
+
return { url: object.url, capability: object.capability, expiresAtMs: object.expiresAtMs };
|
|
82
|
+
}
|
|
83
|
+
export function parseModelDeliveryGrant(json, sku, artifactOrigin = DEFAULT_MODEL_ARTIFACT_ORIGIN) {
|
|
84
|
+
let decoded;
|
|
85
|
+
try {
|
|
86
|
+
decoded = JSON.parse(json);
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
throw new ModelDeliveryError(`Model grant is not valid JSON: ${String(error)}`);
|
|
90
|
+
}
|
|
91
|
+
if (!decoded || typeof decoded !== "object") {
|
|
92
|
+
throw new ModelDeliveryError("Model grant must be an object");
|
|
93
|
+
}
|
|
94
|
+
const body = decoded;
|
|
95
|
+
const artifact = body.modelArtifact;
|
|
96
|
+
const identity = artifact && typeof artifact === "object"
|
|
97
|
+
? exactModelArtifactIdentity(sku, typeof artifact.version === "string" ? artifact.version : undefined, typeof artifact.manifestSha256 === "string" ? artifact.manifestSha256 : undefined)
|
|
98
|
+
: null;
|
|
99
|
+
if (!identity) {
|
|
100
|
+
throw new ModelDeliveryError("Model grant carries an invalid model artifact identity");
|
|
101
|
+
}
|
|
102
|
+
const accepted = body.acceptedArtifactVersions ?? [];
|
|
103
|
+
if (!Array.isArray(accepted)
|
|
104
|
+
|| !accepted.every((version) => typeof version === "string" && exactModelArtifactIdentity(sku, version, identity.manifestSha256) !== null)) {
|
|
105
|
+
throw new ModelDeliveryError("Model grant carries an unsafe accepted artifact version");
|
|
106
|
+
}
|
|
107
|
+
const origin = parseArtifactOrigin(artifactOrigin);
|
|
108
|
+
const release = grantedObject(body.release, "release");
|
|
109
|
+
const model = grantedObject(body.model, "model");
|
|
110
|
+
validateGrantedUrl(release.url, origin, sku, identity.version, RELEASE_FILE);
|
|
111
|
+
validateGrantedUrl(model.url, origin, sku, identity.version, MODEL_FILE);
|
|
112
|
+
return {
|
|
113
|
+
modelId: sku,
|
|
114
|
+
identity,
|
|
115
|
+
release,
|
|
116
|
+
model,
|
|
117
|
+
acceptedArtifactVersions: accepted,
|
|
118
|
+
json,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
export function grantAcceptsStamp(grant, stamped) {
|
|
122
|
+
return ((stamped.version === grant.identity.version
|
|
123
|
+
&& stamped.manifestSha256 === grant.identity.manifestSha256)
|
|
124
|
+
|| grant.acceptedArtifactVersions.includes(stamped.version));
|
|
125
|
+
}
|
|
126
|
+
function issuerErrorCode(body) {
|
|
127
|
+
try {
|
|
128
|
+
const decoded = JSON.parse(body);
|
|
129
|
+
return typeof decoded.error === "string" ? decoded.error : "";
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
return "";
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
export async function requestModelDeliveryGrant(options, sku, capabilityQuery) {
|
|
136
|
+
const fetchFn = options.fetch ?? fetch;
|
|
137
|
+
const baseUrl = (options.baseUrl ?? DEFAULT_INDEX_BASE_URL).replace(/\/+$/, "");
|
|
138
|
+
const url = `${baseUrl}/model-artifacts/download?${capabilityQuery}`;
|
|
139
|
+
const timeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
140
|
+
let deadline;
|
|
141
|
+
let timer;
|
|
142
|
+
const send = (authHeader) => {
|
|
143
|
+
clearTimeout(timer);
|
|
144
|
+
const controller = new AbortController();
|
|
145
|
+
deadline = controller;
|
|
146
|
+
timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
147
|
+
return fetchFn(url, {
|
|
148
|
+
method: "GET",
|
|
149
|
+
headers: { Authorization: authHeader, "x-project-id": options.projectId },
|
|
150
|
+
credentials: "omit",
|
|
151
|
+
signal: controller.signal,
|
|
152
|
+
});
|
|
153
|
+
};
|
|
154
|
+
let response;
|
|
155
|
+
let body;
|
|
156
|
+
try {
|
|
157
|
+
response = await send(await options.auth.getAuthHeader());
|
|
158
|
+
if (response.status === 401) {
|
|
159
|
+
response.body?.cancel().catch(() => undefined);
|
|
160
|
+
await options.auth.invalidate();
|
|
161
|
+
response = await send(await options.auth.getAuthHeader());
|
|
162
|
+
}
|
|
163
|
+
body = response.ok
|
|
164
|
+
? await response.text()
|
|
165
|
+
: await response.text().catch((error) => {
|
|
166
|
+
if (deadline?.signal.aborted)
|
|
167
|
+
throw error;
|
|
168
|
+
return "";
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
catch (error) {
|
|
172
|
+
if (!deadline?.signal.aborted)
|
|
173
|
+
throw error;
|
|
174
|
+
throw new ModelDeliveryError(`Model grant request for '${sku}' got no answer within ${timeoutMs} ms`);
|
|
175
|
+
}
|
|
176
|
+
finally {
|
|
177
|
+
clearTimeout(timer);
|
|
178
|
+
}
|
|
179
|
+
if (!response.ok) {
|
|
180
|
+
const code = issuerErrorCode(body);
|
|
181
|
+
const hint = code === "MODEL_ARTIFACT_UNAVAILABLE" || code === "MODEL_ARTIFACT_ENCRYPTED_UNAVAILABLE"
|
|
182
|
+
? "; no sealed model artifact is published for this model yet"
|
|
183
|
+
: "";
|
|
184
|
+
throw new ModelDeliveryError(`Issuer refused the sealed model grant for '${sku}' (HTTP ${response.status} ${code})${hint}; no plaintext fallback`, response.status, code);
|
|
185
|
+
}
|
|
186
|
+
return parseModelDeliveryGrant(body, sku, options.artifactOrigin);
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Streams one granted artifact into memory.
|
|
190
|
+
*
|
|
191
|
+
* Each attempt aborts when the response or the next chunk takes longer than
|
|
192
|
+
* the deadline. A stall, a network error, a 408, a 429 or a 5xx is retried once.
|
|
193
|
+
*/
|
|
194
|
+
export async function fetchGrantedBytes(fetchFn, object, transfer) {
|
|
195
|
+
for (let attempt = 1;; attempt += 1) {
|
|
196
|
+
try {
|
|
197
|
+
return await fetchGrantedBytesOnce(fetchFn, object, transfer);
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
if (!(error instanceof ArtifactTransferError) || attempt >= ARTIFACT_REQUEST_ATTEMPTS) {
|
|
201
|
+
throw error;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
async function fetchGrantedBytesOnce(fetchFn, object, transfer) {
|
|
207
|
+
const timeoutMs = transfer.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
208
|
+
const controller = new AbortController();
|
|
209
|
+
const network = async (step, failure) => {
|
|
210
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
211
|
+
try {
|
|
212
|
+
return await step();
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
throw new ArtifactTransferError(controller.signal.aborted
|
|
216
|
+
? `Fetching '${object.url}' stalled: nothing arrived for ${timeoutMs} ms`
|
|
217
|
+
: `${failure}: ${String(error)}`);
|
|
218
|
+
}
|
|
219
|
+
finally {
|
|
220
|
+
clearTimeout(timer);
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
const response = await network(() => fetchFn(object.url, {
|
|
224
|
+
method: "GET",
|
|
225
|
+
headers: { Authorization: `Bearer ${object.capability}` },
|
|
226
|
+
credentials: "omit",
|
|
227
|
+
signal: controller.signal,
|
|
228
|
+
}), `Failed to fetch '${object.url}'`);
|
|
229
|
+
if (!response.ok) {
|
|
230
|
+
response.body?.cancel().catch(() => undefined);
|
|
231
|
+
const message = `Failed to fetch '${object.url}': ${response.status}`;
|
|
232
|
+
const transient = response.status >= 500 || response.status === 408 || response.status === 429;
|
|
233
|
+
throw transient
|
|
234
|
+
? new ArtifactTransferError(message, response.status)
|
|
235
|
+
: new ModelDeliveryError(message, response.status);
|
|
236
|
+
}
|
|
237
|
+
return await readArtifactBody(response, object.url, transfer, network);
|
|
238
|
+
}
|
|
239
|
+
async function readArtifactBody(response, url, transfer, network) {
|
|
240
|
+
const target = transfer.preallocate ? new Uint8Array(transfer.maxBytes) : null;
|
|
241
|
+
const chunks = [];
|
|
242
|
+
let loaded = 0;
|
|
243
|
+
const finish = () => {
|
|
244
|
+
if (target && loaded < transfer.maxBytes) {
|
|
245
|
+
throw new ArtifactTransferError(`'${url}' has an unexpected size: the transfer ended after ${loaded} of ${transfer.maxBytes} bytes`);
|
|
246
|
+
}
|
|
247
|
+
return target ?? joinChunks(chunks, loaded);
|
|
248
|
+
};
|
|
249
|
+
if (!response.body)
|
|
250
|
+
return finish();
|
|
251
|
+
const reader = response.body.getReader();
|
|
252
|
+
try {
|
|
253
|
+
for (;;) {
|
|
254
|
+
const next = await network(() => reader.read(), `Transfer of '${url}' failed`);
|
|
255
|
+
if (next.done)
|
|
256
|
+
break;
|
|
257
|
+
const chunk = next.value;
|
|
258
|
+
if (loaded + chunk.byteLength > transfer.maxBytes) {
|
|
259
|
+
throw new ModelDeliveryError(`'${url}' exceeds ${transfer.maxBytes} bytes`);
|
|
260
|
+
}
|
|
261
|
+
if (target)
|
|
262
|
+
target.set(chunk, loaded);
|
|
263
|
+
else
|
|
264
|
+
chunks.push(chunk);
|
|
265
|
+
loaded += chunk.byteLength;
|
|
266
|
+
transfer.onBytes?.(loaded);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
catch (error) {
|
|
270
|
+
reader.cancel().catch(() => undefined);
|
|
271
|
+
throw error;
|
|
272
|
+
}
|
|
273
|
+
return finish();
|
|
274
|
+
}
|
|
275
|
+
function joinChunks(chunks, length) {
|
|
276
|
+
if (chunks.length === 1)
|
|
277
|
+
return chunks[0];
|
|
278
|
+
const joined = new Uint8Array(length);
|
|
279
|
+
let offset = 0;
|
|
280
|
+
for (const chunk of chunks) {
|
|
281
|
+
joined.set(chunk, offset);
|
|
282
|
+
offset += chunk.byteLength;
|
|
283
|
+
}
|
|
284
|
+
return joined;
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Verified model files in the Cache API, keyed by the release manifest digest.
|
|
288
|
+
*
|
|
289
|
+
* Every read is verified again by the caller. Caching is best effort: storage that
|
|
290
|
+
* is missing, as in Node or an insecure context, or that fails, turns into a miss.
|
|
291
|
+
*/
|
|
292
|
+
class ArtifactCache {
|
|
293
|
+
constructor(storage, origin) {
|
|
294
|
+
this.cache = null;
|
|
295
|
+
this.storage = storage;
|
|
296
|
+
this.prefix = `${origin.protocol}//${origin.host}${ARTIFACT_CACHE_PATH}/`;
|
|
297
|
+
}
|
|
298
|
+
key(sku, manifestSha256) {
|
|
299
|
+
return `${this.prefix}${sku}/${manifestSha256}/${MODEL_FILE}`;
|
|
300
|
+
}
|
|
301
|
+
async read(key) {
|
|
302
|
+
try {
|
|
303
|
+
const response = await (await this.open())?.match(key);
|
|
304
|
+
return response ? new Uint8Array(await response.arrayBuffer()) : null;
|
|
305
|
+
}
|
|
306
|
+
catch {
|
|
307
|
+
return null;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
async write(key, bytes) {
|
|
311
|
+
if (!this.storage)
|
|
312
|
+
return;
|
|
313
|
+
try {
|
|
314
|
+
const response = new Response(bytes, {
|
|
315
|
+
headers: { "content-type": "application/octet-stream" },
|
|
316
|
+
});
|
|
317
|
+
await (await this.open())?.put(key, response);
|
|
318
|
+
}
|
|
319
|
+
catch {
|
|
320
|
+
// A full or unavailable cache only costs a download on the next page load.
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
async remove(key) {
|
|
324
|
+
try {
|
|
325
|
+
await (await this.open())?.delete(key);
|
|
326
|
+
}
|
|
327
|
+
catch {
|
|
328
|
+
// A stale entry that cannot be removed fails verification again on the next read.
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
/** Drops the artifacts of every other release of this model. */
|
|
332
|
+
async pruneOtherReleases(sku, manifestSha256) {
|
|
333
|
+
try {
|
|
334
|
+
const cache = await this.open();
|
|
335
|
+
if (!cache)
|
|
336
|
+
return;
|
|
337
|
+
const modelPrefix = `${this.prefix}${sku}/`;
|
|
338
|
+
const keep = `${modelPrefix}${manifestSha256}/`;
|
|
339
|
+
for (const request of await cache.keys()) {
|
|
340
|
+
if (request.url.startsWith(modelPrefix) && !request.url.startsWith(keep)) {
|
|
341
|
+
await cache.delete(request);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
catch {
|
|
346
|
+
// Leftover releases are only a storage cost.
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
open() {
|
|
350
|
+
if (!this.storage)
|
|
351
|
+
return Promise.resolve(null);
|
|
352
|
+
this.cache ?? (this.cache = this.storage.open(ARTIFACT_CACHE_NAME).catch(() => null));
|
|
353
|
+
return this.cache;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
function defaultCacheStorage() {
|
|
357
|
+
try {
|
|
358
|
+
return globalThis.caches ?? undefined;
|
|
359
|
+
}
|
|
360
|
+
catch {
|
|
361
|
+
return undefined;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
function parseReleaseFiles(value) {
|
|
365
|
+
if (!Array.isArray(value)) {
|
|
366
|
+
throw new ModelDeliveryError("Model release manifest has an unsupported shape");
|
|
367
|
+
}
|
|
368
|
+
return value.map((entry) => {
|
|
369
|
+
if (!entry || typeof entry !== "object") {
|
|
370
|
+
throw new ModelDeliveryError("Model release manifest contains an invalid file entry");
|
|
371
|
+
}
|
|
372
|
+
const file = entry;
|
|
373
|
+
if (typeof file.relativePath !== "string"
|
|
374
|
+
|| !isSafeRelativePath(file.relativePath)
|
|
375
|
+
|| typeof file.sha256 !== "string"
|
|
376
|
+
|| !isCanonicalSha256(file.sha256)
|
|
377
|
+
|| typeof file.sizeBytes !== "number"
|
|
378
|
+
|| !Number.isSafeInteger(file.sizeBytes)
|
|
379
|
+
|| file.sizeBytes < 0) {
|
|
380
|
+
throw new ModelDeliveryError("Model release manifest contains an invalid file identity");
|
|
381
|
+
}
|
|
382
|
+
return { relativePath: file.relativePath, sha256: file.sha256, sizeBytes: file.sizeBytes };
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
export async function verifyReleaseManifest(releaseBytes, grant) {
|
|
386
|
+
const digest = await sha256Hex(releaseBytes);
|
|
387
|
+
if (digest !== grant.identity.manifestSha256) {
|
|
388
|
+
throw new ModelDeliveryError(`Model release manifest digest mismatch: expected ${grant.identity.manifestSha256}, got ${digest}`);
|
|
389
|
+
}
|
|
390
|
+
let decoded;
|
|
391
|
+
try {
|
|
392
|
+
decoded = JSON.parse(new TextDecoder().decode(releaseBytes));
|
|
393
|
+
}
|
|
394
|
+
catch (error) {
|
|
395
|
+
throw new ModelDeliveryError(`Model release manifest is invalid JSON: ${String(error)}`);
|
|
396
|
+
}
|
|
397
|
+
if (!decoded || typeof decoded !== "object") {
|
|
398
|
+
throw new ModelDeliveryError("Model release manifest must be an object");
|
|
399
|
+
}
|
|
400
|
+
const manifest = decoded;
|
|
401
|
+
if (typeof manifest.schemaVersion !== "number"
|
|
402
|
+
|| !SUPPORTED_RELEASE_SCHEMA_VERSIONS.includes(manifest.schemaVersion)) {
|
|
403
|
+
throw new ModelDeliveryError(`Unsupported model release manifest schema ${String(manifest.schemaVersion)}`);
|
|
404
|
+
}
|
|
405
|
+
if (manifest.modelId !== grant.modelId || manifest.artifactVersion !== grant.identity.version) {
|
|
406
|
+
throw new ModelDeliveryError("Model release manifest does not match the server-owned artifact identity");
|
|
407
|
+
}
|
|
408
|
+
const files = parseReleaseFiles(manifest.files);
|
|
409
|
+
const byPath = new Map();
|
|
410
|
+
for (const file of files) {
|
|
411
|
+
if (file.relativePath !== MODEL_FILE) {
|
|
412
|
+
throw new ModelDeliveryError(`Model release manifest declares unexpected file '${file.relativePath}'`);
|
|
413
|
+
}
|
|
414
|
+
if (byPath.has(file.relativePath)) {
|
|
415
|
+
throw new ModelDeliveryError(`Model release manifest repeats '${file.relativePath}'`);
|
|
416
|
+
}
|
|
417
|
+
byPath.set(file.relativePath, file);
|
|
418
|
+
}
|
|
419
|
+
const record = byPath.get(MODEL_FILE);
|
|
420
|
+
if (!record) {
|
|
421
|
+
throw new ModelDeliveryError(`Model release manifest is missing '${MODEL_FILE}'`);
|
|
422
|
+
}
|
|
423
|
+
return record;
|
|
424
|
+
}
|
|
425
|
+
export async function verifyModelBytes(bytes, record) {
|
|
426
|
+
if (bytes.byteLength !== record.sizeBytes) {
|
|
427
|
+
throw new ModelDeliveryError(`Model file '${record.relativePath}' has an unexpected size`);
|
|
428
|
+
}
|
|
429
|
+
const digest = await sha256Hex(bytes);
|
|
430
|
+
if (digest !== record.sha256) {
|
|
431
|
+
throw new ModelDeliveryError(`Model file '${record.relativePath}' failed SHA-256 verification`);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
export async function loadSealedModel(options, stamped) {
|
|
435
|
+
const sku = stamped.modelId;
|
|
436
|
+
const fetchFn = options.fetch ?? fetch;
|
|
437
|
+
const exchange = options.runtime.newKeyExchange();
|
|
438
|
+
let grant;
|
|
439
|
+
let keys;
|
|
440
|
+
let consumed = false;
|
|
441
|
+
try {
|
|
442
|
+
grant = await requestModelDeliveryGrant(options, sku, exchange.capabilityQuery(sku));
|
|
443
|
+
if (!grantAcceptsStamp(grant, stamped)) {
|
|
444
|
+
throw new ModelDeliveryError(`Index model artifact ${stamped.version} is not served by the issuer's grant ${grant.identity.version}`);
|
|
445
|
+
}
|
|
446
|
+
consumed = true;
|
|
447
|
+
try {
|
|
448
|
+
keys = exchange.unwrap(grant.json, sku, options.projectId);
|
|
449
|
+
}
|
|
450
|
+
catch (error) {
|
|
451
|
+
throw new ModelDeliveryError(`Issuer grant for '${sku}' cannot be unwrapped: ${String(error)}`);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
finally {
|
|
455
|
+
if (!consumed)
|
|
456
|
+
exchange.free();
|
|
457
|
+
}
|
|
458
|
+
try {
|
|
459
|
+
const cache = new ArtifactCache(options.caches === undefined ? defaultCacheStorage() : options.caches ?? undefined, parseArtifactOrigin(options.artifactOrigin ?? DEFAULT_MODEL_ARTIFACT_ORIGIN));
|
|
460
|
+
const releaseBytes = await fetchGrantedBytes(fetchFn, grant.release, {
|
|
461
|
+
maxBytes: MAX_RELEASE_MANIFEST_BYTES,
|
|
462
|
+
timeoutMs: options.requestTimeoutMs,
|
|
463
|
+
});
|
|
464
|
+
const record = await verifyReleaseManifest(releaseBytes, grant);
|
|
465
|
+
const model = await loadModelFile(options, fetchFn, cache, grant, record);
|
|
466
|
+
const sealed = options.runtime.openSealedModel(model.bytes, keys, sku);
|
|
467
|
+
let bundle;
|
|
468
|
+
try {
|
|
469
|
+
const graph = sealed.takeGraph();
|
|
470
|
+
const tokenizer = sealed.takeTokenizer();
|
|
471
|
+
bundle = { grant, graph, tokenizer };
|
|
472
|
+
}
|
|
473
|
+
finally {
|
|
474
|
+
sealed.free();
|
|
475
|
+
}
|
|
476
|
+
model.persist?.();
|
|
477
|
+
return bundle;
|
|
478
|
+
}
|
|
479
|
+
finally {
|
|
480
|
+
keys.free();
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
async function loadModelFile(options, fetchFn, cache, grant, record) {
|
|
484
|
+
const report = (loadedBytes, fromCache) => {
|
|
485
|
+
try {
|
|
486
|
+
options.onProgress?.({
|
|
487
|
+
modelId: grant.modelId,
|
|
488
|
+
loadedBytes,
|
|
489
|
+
totalBytes: record.sizeBytes,
|
|
490
|
+
fromCache,
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
catch {
|
|
494
|
+
// A failing progress callback must not fail the model load.
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
const manifestSha256 = grant.identity.manifestSha256;
|
|
498
|
+
const key = cache.key(grant.modelId, manifestSha256);
|
|
499
|
+
const cached = await cache.read(key);
|
|
500
|
+
if (cached) {
|
|
501
|
+
try {
|
|
502
|
+
await verifyModelBytes(cached, record);
|
|
503
|
+
report(cached.byteLength, true);
|
|
504
|
+
return { bytes: cached };
|
|
505
|
+
}
|
|
506
|
+
catch {
|
|
507
|
+
await cache.remove(key);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
const bytes = await fetchGrantedBytes(fetchFn, grant.model, {
|
|
511
|
+
maxBytes: record.sizeBytes,
|
|
512
|
+
preallocate: true,
|
|
513
|
+
timeoutMs: options.requestTimeoutMs,
|
|
514
|
+
onBytes: (loaded) => report(loaded, false),
|
|
515
|
+
});
|
|
516
|
+
await verifyModelBytes(bytes, record);
|
|
517
|
+
const persist = () => {
|
|
518
|
+
void cache.write(key, bytes).then(() => cache.pruneOtherReleases(grant.modelId, manifestSha256));
|
|
519
|
+
};
|
|
520
|
+
return { bytes, persist };
|
|
521
|
+
}
|
package/dist/sha256.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SHA-256 helpers for verifying downloaded model artifacts.
|
|
3
|
+
*
|
|
4
|
+
* Web Crypto is preferred, but `crypto.subtle` only exists in secure
|
|
5
|
+
* contexts (HTTPS or localhost). Apps served over plain HTTP on a LAN or
|
|
6
|
+
* intranet host would otherwise lose model loading entirely, so a pure-JS
|
|
7
|
+
* implementation backs it up. Verification is never skipped, and the
|
|
8
|
+
* fallback hashes the model bytes in place without a padded full copy.
|
|
9
|
+
*/
|
|
10
|
+
export declare function sha256Hex(bytes: Uint8Array): Promise<string>;
|
|
11
|
+
/** Incremental SHA-256 over disjoint views. Does not concatenate the parts. */
|
|
12
|
+
export declare function sha256HexParts(parts: Uint8Array[]): Promise<string>;
|
|
13
|
+
/** Pure-JS SHA-256 (FIPS 180-4). Exported for direct testing. */
|
|
14
|
+
export declare function sha256FallbackHex(bytes: Uint8Array): Promise<string>;
|
package/dist/sha256.js
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SHA-256 helpers for verifying downloaded model artifacts.
|
|
3
|
+
*
|
|
4
|
+
* Web Crypto is preferred, but `crypto.subtle` only exists in secure
|
|
5
|
+
* contexts (HTTPS or localhost). Apps served over plain HTTP on a LAN or
|
|
6
|
+
* intranet host would otherwise lose model loading entirely, so a pure-JS
|
|
7
|
+
* implementation backs it up. Verification is never skipped, and the
|
|
8
|
+
* fallback hashes the model bytes in place without a padded full copy.
|
|
9
|
+
*/
|
|
10
|
+
export async function sha256Hex(bytes) {
|
|
11
|
+
const subtle = globalThis.crypto?.subtle;
|
|
12
|
+
if (subtle) {
|
|
13
|
+
// `digest` accepts an ArrayBufferView and respects its offset/length,
|
|
14
|
+
// so the bytes are hashed in place without an extra full-size copy.
|
|
15
|
+
// Only a SharedArrayBuffer-backed view (which Web Crypto rejects)
|
|
16
|
+
// needs a copy first.
|
|
17
|
+
const input = bytes.buffer instanceof ArrayBuffer
|
|
18
|
+
? bytes
|
|
19
|
+
: bytes.slice();
|
|
20
|
+
const digest = new Uint8Array(await subtle.digest("SHA-256", input));
|
|
21
|
+
return toHex(digest);
|
|
22
|
+
}
|
|
23
|
+
return sha256FallbackHex(bytes);
|
|
24
|
+
}
|
|
25
|
+
/** Incremental SHA-256 over disjoint views. Does not concatenate the parts. */
|
|
26
|
+
export async function sha256HexParts(parts) {
|
|
27
|
+
const h = new Uint32Array(INITIAL_HASH);
|
|
28
|
+
const w = new Uint32Array(64);
|
|
29
|
+
const remainder = new Uint8Array(64);
|
|
30
|
+
let remainderLen = 0;
|
|
31
|
+
let totalLength = 0;
|
|
32
|
+
let blocks = 0;
|
|
33
|
+
const blocksPerSlice = 16384;
|
|
34
|
+
const compressBlock = async (view, offset) => {
|
|
35
|
+
compress(h, w, view, offset);
|
|
36
|
+
blocks += 1;
|
|
37
|
+
if (blocks % blocksPerSlice === 0) {
|
|
38
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
for (const part of parts) {
|
|
42
|
+
totalLength += part.length;
|
|
43
|
+
let offset = 0;
|
|
44
|
+
if (remainderLen > 0) {
|
|
45
|
+
const need = 64 - remainderLen;
|
|
46
|
+
if (part.length < need) {
|
|
47
|
+
remainder.set(part, remainderLen);
|
|
48
|
+
remainderLen += part.length;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
remainder.set(part.subarray(0, need), remainderLen);
|
|
52
|
+
await compressBlock(new DataView(remainder.buffer), 0);
|
|
53
|
+
remainderLen = 0;
|
|
54
|
+
offset = need;
|
|
55
|
+
}
|
|
56
|
+
const remaining = part.length - offset;
|
|
57
|
+
const fullBlocks = Math.floor(remaining / 64);
|
|
58
|
+
if (fullBlocks > 0) {
|
|
59
|
+
const data = new DataView(part.buffer, part.byteOffset + offset, fullBlocks * 64);
|
|
60
|
+
for (let block = 0; block < fullBlocks; block++) {
|
|
61
|
+
await compressBlock(data, block * 64);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
const tail = offset + fullBlocks * 64;
|
|
65
|
+
remainderLen = part.length - tail;
|
|
66
|
+
if (remainderLen > 0) {
|
|
67
|
+
remainder.set(part.subarray(tail));
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const padded = new Uint8Array(remainderLen + 8 >= 64 ? 128 : 64);
|
|
71
|
+
padded.set(remainder.subarray(0, remainderLen));
|
|
72
|
+
padded[remainderLen] = 0x80;
|
|
73
|
+
const paddedView = new DataView(padded.buffer);
|
|
74
|
+
const bitLength = totalLength * 8;
|
|
75
|
+
paddedView.setUint32(padded.length - 8, Math.floor(bitLength / 4294967296), false);
|
|
76
|
+
paddedView.setUint32(padded.length - 4, bitLength >>> 0, false);
|
|
77
|
+
for (let offset = 0; offset < padded.length; offset += 64) {
|
|
78
|
+
compress(h, w, paddedView, offset);
|
|
79
|
+
}
|
|
80
|
+
const digest = new Uint8Array(32);
|
|
81
|
+
const digestView = new DataView(digest.buffer);
|
|
82
|
+
for (let i = 0; i < 8; i++)
|
|
83
|
+
digestView.setUint32(i * 4, h[i], false);
|
|
84
|
+
return toHex(digest);
|
|
85
|
+
}
|
|
86
|
+
/** Pure-JS SHA-256 (FIPS 180-4). Exported for direct testing. */
|
|
87
|
+
export async function sha256FallbackHex(bytes) {
|
|
88
|
+
return sha256HexParts([bytes]);
|
|
89
|
+
}
|
|
90
|
+
function compress(h, w, data, offset) {
|
|
91
|
+
for (let i = 0; i < 16; i++)
|
|
92
|
+
w[i] = data.getUint32(offset + i * 4, false);
|
|
93
|
+
for (let i = 16; i < 64; i++) {
|
|
94
|
+
const x = w[i - 15];
|
|
95
|
+
const y = w[i - 2];
|
|
96
|
+
const s0 = (rotr(x, 7) ^ rotr(x, 18) ^ (x >>> 3)) >>> 0;
|
|
97
|
+
const s1 = (rotr(y, 17) ^ rotr(y, 19) ^ (y >>> 10)) >>> 0;
|
|
98
|
+
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
|
|
99
|
+
}
|
|
100
|
+
let a = h[0];
|
|
101
|
+
let b = h[1];
|
|
102
|
+
let c = h[2];
|
|
103
|
+
let d = h[3];
|
|
104
|
+
let e = h[4];
|
|
105
|
+
let f = h[5];
|
|
106
|
+
let g = h[6];
|
|
107
|
+
let hh = h[7];
|
|
108
|
+
for (let i = 0; i < 64; i++) {
|
|
109
|
+
const s1 = (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) >>> 0;
|
|
110
|
+
const ch = ((e & f) ^ (~e & g)) >>> 0;
|
|
111
|
+
const t1 = (hh + s1 + ch + ROUND_CONSTANTS[i] + w[i]) >>> 0;
|
|
112
|
+
const s0 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) >>> 0;
|
|
113
|
+
const maj = ((a & b) ^ (a & c) ^ (b & c)) >>> 0;
|
|
114
|
+
const t2 = (s0 + maj) >>> 0;
|
|
115
|
+
hh = g;
|
|
116
|
+
g = f;
|
|
117
|
+
f = e;
|
|
118
|
+
e = (d + t1) >>> 0;
|
|
119
|
+
d = c;
|
|
120
|
+
c = b;
|
|
121
|
+
b = a;
|
|
122
|
+
a = (t1 + t2) >>> 0;
|
|
123
|
+
}
|
|
124
|
+
h[0] = (h[0] + a) >>> 0;
|
|
125
|
+
h[1] = (h[1] + b) >>> 0;
|
|
126
|
+
h[2] = (h[2] + c) >>> 0;
|
|
127
|
+
h[3] = (h[3] + d) >>> 0;
|
|
128
|
+
h[4] = (h[4] + e) >>> 0;
|
|
129
|
+
h[5] = (h[5] + f) >>> 0;
|
|
130
|
+
h[6] = (h[6] + g) >>> 0;
|
|
131
|
+
h[7] = (h[7] + hh) >>> 0;
|
|
132
|
+
}
|
|
133
|
+
function rotr(value, bits) {
|
|
134
|
+
return ((value >>> bits) | (value << (32 - bits))) >>> 0;
|
|
135
|
+
}
|
|
136
|
+
function toHex(digest) {
|
|
137
|
+
return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
138
|
+
}
|
|
139
|
+
const INITIAL_HASH = [
|
|
140
|
+
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
|
|
141
|
+
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
|
|
142
|
+
];
|
|
143
|
+
const ROUND_CONSTANTS = new Uint32Array([
|
|
144
|
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
|
145
|
+
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
|
146
|
+
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
|
147
|
+
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
|
148
|
+
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
|
149
|
+
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
|
150
|
+
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
|
151
|
+
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
|
152
|
+
]);
|