@wervt/core 0.0.6 → 0.0.8
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/dist/image.js +2 -2
- package/dist/index.d.ts +4 -1
- package/dist/index.js +4 -1
- package/dist/manifest.d.ts +3 -0
- package/dist/profile.d.ts +25 -0
- package/dist/profile.js +47 -0
- package/dist/service.d.ts +26 -0
- package/dist/service.js +57 -0
- package/dist/services.d.ts +63 -0
- package/dist/services.js +84 -0
- package/dist/user.d.ts +6 -0
- package/package.json +1 -1
package/dist/image.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { WervtError } from "./errors.js";
|
|
2
2
|
import { appHeaders, runtimeUrl } from "./runtime.js";
|
|
3
|
-
import
|
|
3
|
+
import * as crypto from "node:crypto";
|
|
4
4
|
// src/image.ts
|
|
5
5
|
const IMAGE_FORMATS = [
|
|
6
6
|
"jpg",
|
|
@@ -63,7 +63,7 @@ function imageSourceKey(source) {
|
|
|
63
63
|
function signImagePath(key, source, options = {}) {
|
|
64
64
|
const encoded = Buffer.from(imageSourceKey(source), "utf8").toString("base64url");
|
|
65
65
|
const signed = [...imageProcessingOptions(options), `${encoded}.${options.format ?? "webp"}`].join("/");
|
|
66
|
-
return `/_wervt/image/${createHmac("sha256", key).update(signed).digest("base64url")}/${signed}`;
|
|
66
|
+
return `/_wervt/image/${crypto.createHmac("sha256", key).update(signed).digest("base64url")}/${signed}`;
|
|
67
67
|
}
|
|
68
68
|
/**
|
|
69
69
|
* The URL of a resized or converted version of an image in the app's bucket, as a path on the
|
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
import { WervtAccess, WervtInvite, appAccess } from "./access.js";
|
|
2
|
+
import { WervtProfile, WervtProfileResult, appProfile } from "./profile.js";
|
|
2
3
|
import { WervtError, errorResponse } from "./errors.js";
|
|
3
4
|
import { WorkloadIdentity, workloadIdentity } from "./identity.js";
|
|
4
5
|
import { IMAGE_FORMATS, ImageFormat, ImageGravity, ImageOptions, ImageSource, fetchImage, imageProcessingOptions, imageSourceKey, imageUrl, signImagePath } from "./image.js";
|
|
5
6
|
import { MailMessage, sendMail } from "./mail.js";
|
|
7
|
+
import { SERVICE_NAME_PATTERN, ServiceManifest, ServiceOptions, serviceManifests } from "./services.js";
|
|
6
8
|
import { BUNDLE_MANIFEST, BrandManifest, BundleManifest, CACHE_CONTROL_PATTERN, PUBLIC_PATH_PATTERN, PreviewManifest, PublicCacheRule, PublicCacheRules, TaskSchedule, TasksManifest, matchesPublicPath } from "./manifest.js";
|
|
7
9
|
import { appHeaders, callRuntime, runtimeUrl } from "./runtime.js";
|
|
10
|
+
import { SERVICE_ERROR_HEADER, WervtService, serviceUrlVar, useService } from "./service.js";
|
|
8
11
|
import { PUBLIC_FILE_SERVICE, publicFileResponse } from "./public-files.js";
|
|
9
12
|
import { ShapeRequest, ShapeResponse, ShapeRowOf, parseTimestamp, proxyShape, shapeParser } from "./shape.js";
|
|
10
13
|
import { ACCOUNT_MERGED_TASK, AccountMergedPayload, TASK_HEADER, Task, TaskEvent, TaskResult, createTaskHandler, defineTask, isTaskRequest, taskRunResponse } from "./tasks.js";
|
|
11
14
|
import { AGENT_TOKEN_HEADER, AgentToken, USER_HEADER, USER_PROOF_HEADER, WervtRole, WervtUser, checkRole, getAgentToken, getUser, parseAgentToken, parseWervtUser, requireRole, userFromClaims } from "./user.js";
|
|
12
|
-
export { ACCOUNT_MERGED_TASK, AGENT_TOKEN_HEADER, type AccountMergedPayload, type AgentToken, BUNDLE_MANIFEST, type BrandManifest, type BundleManifest, CACHE_CONTROL_PATTERN, IMAGE_FORMATS, type ImageFormat, type ImageGravity, type ImageOptions, type ImageSource, type MailMessage, PUBLIC_FILE_SERVICE, PUBLIC_PATH_PATTERN, type PreviewManifest, type PublicCacheRule, type PublicCacheRules, type ShapeRequest, type ShapeResponse, type ShapeRowOf, TASK_HEADER, type Task, type TaskEvent, type TaskResult, type TaskSchedule, type TasksManifest, USER_HEADER, USER_PROOF_HEADER, type WervtAccess, WervtError, type WervtInvite, type WervtRole, type WervtUser, type WorkloadIdentity, appAccess, appHeaders, callRuntime, checkRole, createTaskHandler, defineTask, errorResponse, fetchImage, getAgentToken, getUser, imageProcessingOptions, imageSourceKey, imageUrl, isTaskRequest, matchesPublicPath, parseAgentToken, parseTimestamp, parseWervtUser, proxyShape, publicFileResponse, requireRole, runtimeUrl, sendMail, shapeParser, signImagePath, taskRunResponse, userFromClaims, workloadIdentity };
|
|
15
|
+
export { ACCOUNT_MERGED_TASK, AGENT_TOKEN_HEADER, type AccountMergedPayload, type AgentToken, BUNDLE_MANIFEST, type BrandManifest, type BundleManifest, CACHE_CONTROL_PATTERN, IMAGE_FORMATS, type ImageFormat, type ImageGravity, type ImageOptions, type ImageSource, type MailMessage, PUBLIC_FILE_SERVICE, PUBLIC_PATH_PATTERN, type PreviewManifest, type PublicCacheRule, type PublicCacheRules, SERVICE_ERROR_HEADER, SERVICE_NAME_PATTERN, type ServiceManifest, type ServiceOptions, type ShapeRequest, type ShapeResponse, type ShapeRowOf, TASK_HEADER, type Task, type TaskEvent, type TaskResult, type TaskSchedule, type TasksManifest, USER_HEADER, USER_PROOF_HEADER, type WervtAccess, WervtError, type WervtInvite, type WervtProfile, type WervtProfileResult, type WervtRole, type WervtService, type WervtUser, type WorkloadIdentity, appAccess, appHeaders, appProfile, callRuntime, checkRole, createTaskHandler, defineTask, errorResponse, fetchImage, getAgentToken, getUser, imageProcessingOptions, imageSourceKey, imageUrl, isTaskRequest, matchesPublicPath, parseAgentToken, parseTimestamp, parseWervtUser, proxyShape, publicFileResponse, requireRole, runtimeUrl, sendMail, serviceManifests, serviceUrlVar, shapeParser, signImagePath, taskRunResponse, useService, userFromClaims, workloadIdentity };
|
package/dist/index.js
CHANGED
|
@@ -2,11 +2,14 @@ import { WervtError, errorResponse } from "./errors.js";
|
|
|
2
2
|
import { appHeaders, callRuntime, runtimeUrl } from "./runtime.js";
|
|
3
3
|
import { AGENT_TOKEN_HEADER, USER_HEADER, USER_PROOF_HEADER, checkRole, getAgentToken, getUser, parseAgentToken, parseWervtUser, requireRole, userFromClaims } from "./user.js";
|
|
4
4
|
import { appAccess } from "./access.js";
|
|
5
|
+
import { appProfile } from "./profile.js";
|
|
5
6
|
import { workloadIdentity } from "./identity.js";
|
|
6
7
|
import { IMAGE_FORMATS, fetchImage, imageProcessingOptions, imageSourceKey, imageUrl, signImagePath } from "./image.js";
|
|
7
8
|
import { sendMail } from "./mail.js";
|
|
8
9
|
import { BUNDLE_MANIFEST, CACHE_CONTROL_PATTERN, PUBLIC_PATH_PATTERN, matchesPublicPath } from "./manifest.js";
|
|
10
|
+
import { SERVICE_NAME_PATTERN, serviceManifests } from "./services.js";
|
|
11
|
+
import { SERVICE_ERROR_HEADER, serviceUrlVar, useService } from "./service.js";
|
|
9
12
|
import { PUBLIC_FILE_SERVICE, publicFileResponse } from "./public-files.js";
|
|
10
13
|
import { parseTimestamp, proxyShape, shapeParser } from "./shape.js";
|
|
11
14
|
import { ACCOUNT_MERGED_TASK, TASK_HEADER, createTaskHandler, defineTask, isTaskRequest, taskRunResponse } from "./tasks.js";
|
|
12
|
-
export { ACCOUNT_MERGED_TASK, AGENT_TOKEN_HEADER, BUNDLE_MANIFEST, CACHE_CONTROL_PATTERN, IMAGE_FORMATS, PUBLIC_FILE_SERVICE, PUBLIC_PATH_PATTERN, TASK_HEADER, USER_HEADER, USER_PROOF_HEADER, WervtError, appAccess, appHeaders, callRuntime, checkRole, createTaskHandler, defineTask, errorResponse, fetchImage, getAgentToken, getUser, imageProcessingOptions, imageSourceKey, imageUrl, isTaskRequest, matchesPublicPath, parseAgentToken, parseTimestamp, parseWervtUser, proxyShape, publicFileResponse, requireRole, runtimeUrl, sendMail, shapeParser, signImagePath, taskRunResponse, userFromClaims, workloadIdentity };
|
|
15
|
+
export { ACCOUNT_MERGED_TASK, AGENT_TOKEN_HEADER, BUNDLE_MANIFEST, CACHE_CONTROL_PATTERN, IMAGE_FORMATS, PUBLIC_FILE_SERVICE, PUBLIC_PATH_PATTERN, SERVICE_ERROR_HEADER, SERVICE_NAME_PATTERN, TASK_HEADER, USER_HEADER, USER_PROOF_HEADER, WervtError, appAccess, appHeaders, appProfile, callRuntime, checkRole, createTaskHandler, defineTask, errorResponse, fetchImage, getAgentToken, getUser, imageProcessingOptions, imageSourceKey, imageUrl, isTaskRequest, matchesPublicPath, parseAgentToken, parseTimestamp, parseWervtUser, proxyShape, publicFileResponse, requireRole, runtimeUrl, sendMail, serviceManifests, serviceUrlVar, shapeParser, signImagePath, taskRunResponse, useService, userFromClaims, workloadIdentity };
|
package/dist/manifest.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ServiceManifest } from "./services.js";
|
|
1
2
|
export interface TaskSchedule {
|
|
2
3
|
/** Cron expression, in `timezone`. */
|
|
3
4
|
cron: string;
|
|
@@ -94,4 +95,6 @@ export interface BundleManifest {
|
|
|
94
95
|
* those with 403 everywhere else, since the browser sends the visitor's login along.
|
|
95
96
|
*/
|
|
96
97
|
crossApp?: string[];
|
|
98
|
+
/** Containers next to the isolate, by name, reached through `useService(name)`. */
|
|
99
|
+
services?: Record<string, ServiceManifest>;
|
|
97
100
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** The signed-in user's name and picture after a change. */
|
|
2
|
+
export interface WervtProfileResult {
|
|
3
|
+
name: string;
|
|
4
|
+
/** The picture's URL, missing without one. */
|
|
5
|
+
image?: string;
|
|
6
|
+
}
|
|
7
|
+
export interface WervtProfile {
|
|
8
|
+
/** Sets the name (trimmed, at most 100 characters). */
|
|
9
|
+
setName(name: string): Promise<WervtProfileResult>;
|
|
10
|
+
/** Sets the picture: a JPEG, PNG or WebP image of at most 2 MB. Shrink it in the browser first. */
|
|
11
|
+
setImage(image: Uint8Array | ArrayBuffer | Blob): Promise<WervtProfileResult>;
|
|
12
|
+
/** Removes the picture. */
|
|
13
|
+
removeImage(): Promise<WervtProfileResult>;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Changes the name and picture of the user of `request`, without sending them to the account page.
|
|
17
|
+
* Only for apps an admin allowed it (dashboard, the app's settings). Never someone else's
|
|
18
|
+
* account, and never the address: link to `/_wervt/account` for that. The app sees the change
|
|
19
|
+
* from the next request on, in `useWervtUser` too.
|
|
20
|
+
*
|
|
21
|
+
* Throws a WervtError with the platform's status: 401 without a signed-in user, 403 when the app
|
|
22
|
+
* isn't allowed or is a preview, 400 for a name it can't take, 413 for a picture over 2 MB, 415
|
|
23
|
+
* for one that isn't JPEG, PNG or WebP, 503 in local dev.
|
|
24
|
+
*/
|
|
25
|
+
export declare function appProfile(request: Request): WervtProfile;
|
package/dist/profile.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { callRuntime } from "./runtime.js";
|
|
2
|
+
import { USER_HEADER, USER_PROOF_HEADER } from "./user.js";
|
|
3
|
+
// src/profile.ts
|
|
4
|
+
/** Base64 in chunks: spreading a 2 MB array into one call overflows the stack. */
|
|
5
|
+
function toBase64(bytes) {
|
|
6
|
+
let binary = "";
|
|
7
|
+
for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
|
|
8
|
+
return btoa(binary);
|
|
9
|
+
}
|
|
10
|
+
async function bytesOf(image) {
|
|
11
|
+
if (image instanceof Uint8Array) return image;
|
|
12
|
+
if (image instanceof ArrayBuffer) return new Uint8Array(image);
|
|
13
|
+
return new Uint8Array(await image.arrayBuffer());
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Changes the name and picture of the user of `request`, without sending them to the account page.
|
|
17
|
+
* Only for apps an admin allowed it (dashboard, the app's settings). Never someone else's
|
|
18
|
+
* account, and never the address: link to `/_wervt/account` for that. The app sees the change
|
|
19
|
+
* from the next request on, in `useWervtUser` too.
|
|
20
|
+
*
|
|
21
|
+
* Throws a WervtError with the platform's status: 401 without a signed-in user, 403 when the app
|
|
22
|
+
* isn't allowed or is a preview, 400 for a name it can't take, 413 for a picture over 2 MB, 415
|
|
23
|
+
* for one that isn't JPEG, PNG or WebP, 503 in local dev.
|
|
24
|
+
*/
|
|
25
|
+
function appProfile(request) {
|
|
26
|
+
const headers = {
|
|
27
|
+
[USER_HEADER]: request.headers.get("x-wervt-user") ?? "",
|
|
28
|
+
[USER_PROOF_HEADER]: request.headers.get("x-wervt-user-proof") ?? ""
|
|
29
|
+
};
|
|
30
|
+
const change = async (body) => {
|
|
31
|
+
const result = await callRuntime("/_wervt/profile", {
|
|
32
|
+
method: "PATCH",
|
|
33
|
+
body,
|
|
34
|
+
headers
|
|
35
|
+
});
|
|
36
|
+
return {
|
|
37
|
+
name: result.name,
|
|
38
|
+
...result.image ? { image: result.image } : {}
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
return {
|
|
42
|
+
setName: (name) => change({ name }),
|
|
43
|
+
setImage: async (image) => change({ image: toBase64(await bytesOf(image)) }),
|
|
44
|
+
removeImage: () => change({ image: null })
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
export { appProfile };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Marks the platform's own errors on the way to a service (runtime gateway and runner). */
|
|
2
|
+
export declare const SERVICE_ERROR_HEADER = "x-wervt-proxy-error";
|
|
3
|
+
export interface WervtService {
|
|
4
|
+
/**
|
|
5
|
+
* Whether the app has the service here: in its active release on wervt, or running next to the
|
|
6
|
+
* dev server. Without it, `fetch` throws a WervtError with 503.
|
|
7
|
+
*/
|
|
8
|
+
readonly available: boolean;
|
|
9
|
+
/**
|
|
10
|
+
* A request to the service, `path` from its root (`/detect?min=0.5`). The answer is the
|
|
11
|
+
* service's own, whatever its status. Throws a WervtError when the platform couldn't deliver
|
|
12
|
+
* it: 404 (no such service in the release), 502/503 (not running, didn't start).
|
|
13
|
+
*
|
|
14
|
+
* Its `authorization` header doesn't reach the service, which needs none: only the app does.
|
|
15
|
+
*/
|
|
16
|
+
fetch(path: string, init?: RequestInit): Promise<Response>;
|
|
17
|
+
}
|
|
18
|
+
/** `WERVT_SERVICE_FACES_URL` for `faces`: the dev setup's address of the service. */
|
|
19
|
+
export declare function serviceUrlVar(name: string): string;
|
|
20
|
+
/**
|
|
21
|
+
* One of the app's service containers.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* const res = await useService('faces').fetch('/detect', { method: 'POST', body: image })
|
|
25
|
+
*/
|
|
26
|
+
export declare function useService(name: string): WervtService;
|
package/dist/service.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { WervtError } from "./errors.js";
|
|
2
|
+
import { appHeaders, runtimeUrl } from "./runtime.js";
|
|
3
|
+
import { SERVICE_NAME_PATTERN } from "./services.js";
|
|
4
|
+
// src/service.ts
|
|
5
|
+
/** Marks the platform's own errors on the way to a service (runtime gateway and runner). */
|
|
6
|
+
const SERVICE_ERROR_HEADER = "x-wervt-proxy-error";
|
|
7
|
+
/** `WERVT_SERVICE_FACES_URL` for `faces`: the dev setup's address of the service. */
|
|
8
|
+
function serviceUrlVar(name) {
|
|
9
|
+
return `WERVT_SERVICE_${name.toUpperCase().replaceAll("-", "_")}_URL`;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* One of the app's service containers.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* const res = await useService('faces').fetch('/detect', { method: 'POST', body: image })
|
|
16
|
+
*/
|
|
17
|
+
function useService(name) {
|
|
18
|
+
if (!SERVICE_NAME_PATTERN.test(name)) throw new Error(`Invalid service name ${JSON.stringify(name)}`);
|
|
19
|
+
const target = () => {
|
|
20
|
+
const local = process.env[serviceUrlVar(name)];
|
|
21
|
+
if (local) return {
|
|
22
|
+
base: local.replace(/\/+$/, ""),
|
|
23
|
+
headers: {}
|
|
24
|
+
};
|
|
25
|
+
const runtime = runtimeUrl();
|
|
26
|
+
const deployed = (process.env.WERVT_SERVICES ?? "").split(",").includes(name);
|
|
27
|
+
if (runtime && deployed) return {
|
|
28
|
+
base: new URL(`/_wervt/services/${name}`, runtime).href,
|
|
29
|
+
headers: appHeaders()
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
return {
|
|
33
|
+
get available() {
|
|
34
|
+
return target() !== void 0;
|
|
35
|
+
},
|
|
36
|
+
async fetch(path, init = {}) {
|
|
37
|
+
if (!path.startsWith("/")) throw new Error(`Service paths start with /, not ${path}`);
|
|
38
|
+
const to = target();
|
|
39
|
+
if (!to) throw new WervtError(503, runtimeUrl() ? `The app has no service "${name}": add it to \`services\` and deploy` : `Service "${name}" isn't running: the dev server starts it with Docker, or set ${serviceUrlVar(name)}`);
|
|
40
|
+
const headers = new Headers(init.headers);
|
|
41
|
+
for (const [key, value] of Object.entries(to.headers)) headers.set(key, value);
|
|
42
|
+
const options = {
|
|
43
|
+
...init,
|
|
44
|
+
headers,
|
|
45
|
+
...init.body ? { duplex: "half" } : {}
|
|
46
|
+
};
|
|
47
|
+
const res = await fetch(`${to.base}${path}`, options).catch((e) => {
|
|
48
|
+
if (init.signal?.aborted) throw e;
|
|
49
|
+
throw new WervtError(502, `Service "${name}" is not reachable: ${e.message}`);
|
|
50
|
+
});
|
|
51
|
+
if (!res.headers.has("x-wervt-proxy-error")) return res;
|
|
52
|
+
const data = await res.json().catch(() => ({}));
|
|
53
|
+
throw new WervtError(res.status, data.error ?? `Service "${name}" failed (${res.status})`);
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
export { SERVICE_ERROR_HEADER, serviceUrlVar, useService };
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/** A service as the app configures it (`wervt.services` in nuxt.config, or @wervt/nitro's options). */
|
|
2
|
+
export interface ServiceOptions {
|
|
3
|
+
/**
|
|
4
|
+
* A directory with a Dockerfile, relative to the app (`'./face-service'`), built on the
|
|
5
|
+
* server with every deploy that changed it. Or `{ context, dockerfile }` for another file,
|
|
6
|
+
* its path relative to the context.
|
|
7
|
+
*/
|
|
8
|
+
build?: string | {
|
|
9
|
+
context: string;
|
|
10
|
+
dockerfile?: string;
|
|
11
|
+
};
|
|
12
|
+
/** A registry image with a tag or digest, `ghcr.io/org/image:1.2`, instead of `build`. */
|
|
13
|
+
image?: string;
|
|
14
|
+
/** The port the service listens on; it also gets it as `PORT`. */
|
|
15
|
+
port: number;
|
|
16
|
+
/** A path answering 2xx once the service is ready, `/healthz`. Without, an open port is enough. */
|
|
17
|
+
health?: string;
|
|
18
|
+
/** Its memory limit, like `512MB` or `2GB` (at least 64 MB). 512 MB when missing. */
|
|
19
|
+
memory?: string | number;
|
|
20
|
+
/** CPU cores, like `0.5` or `2`. 1 when missing. */
|
|
21
|
+
cpus?: number;
|
|
22
|
+
/** Keeps it running. By default it starts on the first request and stops when it idles. */
|
|
23
|
+
alwaysOn?: boolean;
|
|
24
|
+
/** How long without requests until it stops, 1m to 24h like `10m` (seconds as a number). */
|
|
25
|
+
idle?: string | number;
|
|
26
|
+
/** Lets it reach the internet. Off by default: it only answers the app. */
|
|
27
|
+
egress?: boolean;
|
|
28
|
+
/** Its environment. Fixed at build time and visible in the bundle, so no secrets. */
|
|
29
|
+
env?: Record<string, string>;
|
|
30
|
+
/** Writable directories besides `/tmp` (the root filesystem is read-only), up to 4. */
|
|
31
|
+
tmpfs?: string[];
|
|
32
|
+
}
|
|
33
|
+
/** A service in the bundle's manifest (`services` in wervt-bundle.json). */
|
|
34
|
+
export interface ServiceManifest {
|
|
35
|
+
/**
|
|
36
|
+
* The build context relative to the app, the Dockerfile in it, and the context's SHA-256,
|
|
37
|
+
* which `wervt deploy` fills in once it uploaded the context.
|
|
38
|
+
*/
|
|
39
|
+
build?: {
|
|
40
|
+
context: string;
|
|
41
|
+
dockerfile?: string;
|
|
42
|
+
hash?: string;
|
|
43
|
+
};
|
|
44
|
+
image?: string;
|
|
45
|
+
port: number;
|
|
46
|
+
health?: string;
|
|
47
|
+
/** Bytes. */
|
|
48
|
+
memory: number;
|
|
49
|
+
cpus: number;
|
|
50
|
+
alwaysOn?: boolean;
|
|
51
|
+
/** Seconds. */
|
|
52
|
+
idle?: number;
|
|
53
|
+
egress?: boolean;
|
|
54
|
+
env?: Record<string, string>;
|
|
55
|
+
tmpfs?: string[];
|
|
56
|
+
}
|
|
57
|
+
/** What a service may be called: it's part of URLs (`useService('faces')`) and container names. */
|
|
58
|
+
export declare const SERVICE_NAME_PATTERN: RegExp;
|
|
59
|
+
/**
|
|
60
|
+
* The manifest's `services` from the app's options. Throws on what the platform would refuse
|
|
61
|
+
* anyway, so a mistake shows at build time, not on deploy.
|
|
62
|
+
*/
|
|
63
|
+
export declare function serviceManifests(options: Record<string, ServiceOptions> | undefined): Record<string, ServiceManifest> | undefined;
|
package/dist/services.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// src/services.ts
|
|
2
|
+
/** What a service may be called: it's part of URLs (`useService('faces')`) and container names. */
|
|
3
|
+
const SERVICE_NAME_PATTERN = /^[a-z](?:[a-z0-9-]{0,30}[a-z0-9])?$/;
|
|
4
|
+
const DEFAULT_MEMORY = 512 * 1024 ** 2;
|
|
5
|
+
const MIN_MEMORY = 64 * 1024 ** 2;
|
|
6
|
+
const MIN_IDLE = 60;
|
|
7
|
+
const MAX_IDLE = 86400;
|
|
8
|
+
const MAX_ENV = 50;
|
|
9
|
+
const SIZE_UNITS = {
|
|
10
|
+
b: 1,
|
|
11
|
+
kb: 1024,
|
|
12
|
+
mb: 1024 ** 2,
|
|
13
|
+
gb: 1024 ** 3
|
|
14
|
+
};
|
|
15
|
+
const DURATION_UNITS = {
|
|
16
|
+
s: 1,
|
|
17
|
+
m: 60,
|
|
18
|
+
h: 3600
|
|
19
|
+
};
|
|
20
|
+
function bytes(name, value) {
|
|
21
|
+
const match = String(value).trim().match(/^(\d+(?:\.\d+)?)\s*([kmg]?b)$/i);
|
|
22
|
+
const size = typeof value === "number" && Number.isInteger(value) ? value : match && Math.round(Number(match[1]) * SIZE_UNITS[match[2].toLowerCase()]);
|
|
23
|
+
if (!size || size < MIN_MEMORY) throw new Error(`services.${name}.memory must be a size of at least 64MB, like 512MB or 2GB`);
|
|
24
|
+
return size;
|
|
25
|
+
}
|
|
26
|
+
function seconds(name, value) {
|
|
27
|
+
const match = String(value).trim().match(/^(\d+)\s*([smh])$/);
|
|
28
|
+
const duration = typeof value === "number" && Number.isInteger(value) ? value : match && Number(match[1]) * DURATION_UNITS[match[2]];
|
|
29
|
+
if (!duration || duration < MIN_IDLE || duration > MAX_IDLE) throw new Error(`services.${name}.idle must be a duration from 1m to 24h, like 10m`);
|
|
30
|
+
return duration;
|
|
31
|
+
}
|
|
32
|
+
/** A relative path below `inside`, with `/` separators, or an error naming the field. */
|
|
33
|
+
function relativePath(name, field, path, inside, example) {
|
|
34
|
+
const parts = path.replaceAll("\\", "/").split("/");
|
|
35
|
+
if (path.startsWith("/") || /^[a-z]:/i.test(path) || parts.includes("..")) throw new Error(`services.${name}.${field} must be a path inside ${inside}, like ${example}`);
|
|
36
|
+
return parts.filter((part) => part && part !== ".").join("/") || ".";
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The manifest's `services` from the app's options. Throws on what the platform would refuse
|
|
40
|
+
* anyway, so a mistake shows at build time, not on deploy.
|
|
41
|
+
*/
|
|
42
|
+
function serviceManifests(options) {
|
|
43
|
+
if (!options || !Object.keys(options).length) return void 0;
|
|
44
|
+
const services = {};
|
|
45
|
+
for (const [name, service] of Object.entries(options)) {
|
|
46
|
+
if (!SERVICE_NAME_PATTERN.test(name)) throw new Error(`Service name ${JSON.stringify(name)}: lowercase letters, digits and dashes, starting with a letter`);
|
|
47
|
+
if (!service.build === !service.image) throw new Error(`services.${name} needs either build (a directory) or image`);
|
|
48
|
+
if (!Number.isInteger(service.port) || service.port < 1 || service.port > 65535) throw new Error(`services.${name}.port must be a port number`);
|
|
49
|
+
if (service.health !== void 0 && !/^\/\S*$/.test(service.health)) throw new Error(`services.${name}.health must be a path like /healthz`);
|
|
50
|
+
const cpus = service.cpus ?? 1;
|
|
51
|
+
if (typeof cpus !== "number" || !(cpus >= .1)) throw new Error(`services.${name}.cpus must be a number like 0.5 or 2`);
|
|
52
|
+
const manifest = {
|
|
53
|
+
port: service.port,
|
|
54
|
+
memory: service.memory === void 0 ? DEFAULT_MEMORY : bytes(name, service.memory),
|
|
55
|
+
cpus
|
|
56
|
+
};
|
|
57
|
+
if (service.build) {
|
|
58
|
+
const build = typeof service.build === "string" ? { context: service.build } : { ...service.build };
|
|
59
|
+
manifest.build = { context: relativePath(name, "build", build.context, "the app", `./${name}`) };
|
|
60
|
+
if (build.dockerfile) manifest.build.dockerfile = relativePath(name, "build.dockerfile", build.dockerfile, "the build context", "docker/Dockerfile");
|
|
61
|
+
} else {
|
|
62
|
+
const last = service.image.split("/").pop();
|
|
63
|
+
if (!service.image.includes("@sha256:") && !/:[^:]+$/.test(last)) throw new Error(`services.${name}.image needs a tag or digest, like ${service.image}:1.0, so a deploy runs what it was tested with`);
|
|
64
|
+
manifest.image = service.image;
|
|
65
|
+
}
|
|
66
|
+
if (service.health) manifest.health = service.health;
|
|
67
|
+
if (service.alwaysOn) manifest.alwaysOn = true;
|
|
68
|
+
if (service.idle !== void 0) manifest.idle = seconds(name, service.idle);
|
|
69
|
+
if (service.egress) manifest.egress = true;
|
|
70
|
+
if (service.env && Object.keys(service.env).length) {
|
|
71
|
+
if (Object.keys(service.env).length > MAX_ENV) throw new Error(`services.${name}.env takes up to ${MAX_ENV} variables`);
|
|
72
|
+
for (const key of Object.keys(service.env)) if (/^wervt_/i.test(key)) throw new Error(`services.${name}.env.${key}: WERVT_ variables are the platform's`);
|
|
73
|
+
manifest.env = { ...service.env };
|
|
74
|
+
}
|
|
75
|
+
if (service.tmpfs?.length) {
|
|
76
|
+
const clean = (path) => /^(?:\/[\w.-]+)+$/.test(path) && !path.split("/").some((p) => p === "." || p === "..");
|
|
77
|
+
if (service.tmpfs.length > 4 || !service.tmpfs.every(clean)) throw new Error(`services.${name}.tmpfs takes up to 4 absolute paths, like /cache`);
|
|
78
|
+
manifest.tmpfs = [...service.tmpfs];
|
|
79
|
+
}
|
|
80
|
+
services[name] = manifest;
|
|
81
|
+
}
|
|
82
|
+
return services;
|
|
83
|
+
}
|
|
84
|
+
export { SERVICE_NAME_PATTERN, serviceManifests };
|
package/dist/user.d.ts
CHANGED
|
@@ -18,6 +18,12 @@ export interface WervtUser {
|
|
|
18
18
|
role?: WervtRole;
|
|
19
19
|
/** An admin of the wervt server, whatever their `role` in this app. */
|
|
20
20
|
admin?: boolean;
|
|
21
|
+
/**
|
|
22
|
+
* The address was confirmed: by a code, or by a login provider that vouches for it. Missing
|
|
23
|
+
* when nobody did (a Spotify sign-up can carry any address) and for requests with a token
|
|
24
|
+
* (MCP, native apps, `wervt token`). Check it before matching accounts by email.
|
|
25
|
+
*/
|
|
26
|
+
emailVerified?: true;
|
|
21
27
|
}
|
|
22
28
|
/** Parses the `x-wervt-user` header the runtime sets. */
|
|
23
29
|
export declare function parseWervtUser(header: string | null | undefined): WervtUser | undefined;
|
package/package.json
CHANGED