@venturekit/runtime 0.0.48 → 0.0.51
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/config/cache-connection.d.ts +23 -0
- package/dist/config/cache-connection.d.ts.map +1 -0
- package/dist/config/cache-connection.js +33 -0
- package/dist/config/cache-connection.js.map +1 -0
- package/dist/handler/context.d.ts +8 -0
- package/dist/handler/context.d.ts.map +1 -1
- package/dist/handler/context.js +10 -1
- package/dist/handler/context.js.map +1 -1
- package/dist/handler/errors.d.ts +8 -0
- package/dist/handler/errors.d.ts.map +1 -1
- package/dist/handler/errors.js +11 -0
- package/dist/handler/errors.js.map +1 -1
- package/dist/handler/handler.d.ts +8 -0
- package/dist/handler/handler.d.ts.map +1 -1
- package/dist/handler/handler.js +42 -1
- package/dist/handler/handler.js.map +1 -1
- package/dist/index.d.ts +14 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -2
- package/dist/index.js.map +1 -1
- package/dist/logging/logger.d.ts +0 -14
- package/dist/logging/logger.d.ts.map +1 -1
- package/dist/logging/logger.js +20 -21
- package/dist/logging/logger.js.map +1 -1
- package/dist/middleware/default-rate-limit.d.ts +25 -0
- package/dist/middleware/default-rate-limit.d.ts.map +1 -0
- package/dist/middleware/default-rate-limit.js +27 -0
- package/dist/middleware/default-rate-limit.js.map +1 -0
- package/dist/middleware/middleware.d.ts +67 -20
- package/dist/middleware/middleware.d.ts.map +1 -1
- package/dist/middleware/middleware.js +83 -7
- package/dist/middleware/middleware.js.map +1 -1
- package/dist/patterns/internal-fetch.d.ts +33 -0
- package/dist/patterns/internal-fetch.d.ts.map +1 -0
- package/dist/patterns/internal-fetch.js +120 -0
- package/dist/patterns/internal-fetch.js.map +1 -0
- package/dist/patterns/invoke.d.ts +6 -0
- package/dist/patterns/invoke.d.ts.map +1 -1
- package/dist/patterns/invoke.js +12 -3
- package/dist/patterns/invoke.js.map +1 -1
- package/dist/patterns.d.ts +2 -0
- package/dist/patterns.d.ts.map +1 -1
- package/dist/patterns.js +1 -0
- package/dist/patterns.js.map +1 -1
- package/dist/secrets.d.ts +2 -0
- package/dist/secrets.d.ts.map +1 -1
- package/dist/secrets.js +1 -0
- package/dist/secrets.js.map +1 -1
- package/dist/security/credential-cookies.d.ts +87 -0
- package/dist/security/credential-cookies.d.ts.map +1 -0
- package/dist/security/credential-cookies.js +139 -0
- package/dist/security/credential-cookies.js.map +1 -0
- package/dist/security/http-security.d.ts +72 -0
- package/dist/security/http-security.d.ts.map +1 -0
- package/dist/security/http-security.js +96 -0
- package/dist/security/http-security.js.map +1 -0
- package/dist/security/internal-callers.d.ts +41 -0
- package/dist/security/internal-callers.d.ts.map +1 -0
- package/dist/security/internal-callers.js +164 -0
- package/dist/security/internal-callers.js.map +1 -0
- package/dist/security/internal-hmac.d.ts +53 -5
- package/dist/security/internal-hmac.d.ts.map +1 -1
- package/dist/security/internal-hmac.js +91 -9
- package/dist/security/internal-hmac.js.map +1 -1
- package/dist/ws/ws-origin.d.ts +30 -0
- package/dist/ws/ws-origin.d.ts.map +1 -0
- package/dist/ws/ws-origin.js +55 -0
- package/dist/ws/ws-origin.js.map +1 -0
- package/dist/ws/ws.d.ts +25 -2
- package/dist/ws/ws.d.ts.map +1 -1
- package/dist/ws/ws.js +50 -29
- package/dist/ws/ws.js.map +1 -1
- package/dist/ws.d.ts +3 -1
- package/dist/ws.d.ts.map +1 -1
- package/dist/ws.js +2 -1
- package/dist/ws.js.map +1 -1
- package/package.json +5 -5
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Internal routes between ventures — the caller's identity.
|
|
3
|
+
*
|
|
4
|
+
* A venture's `routes/internal/**` are never on its public API: other
|
|
5
|
+
* ventures (and its own containers) invoke them through the Lambda API
|
|
6
|
+
* (`internalFetch`). Every call is signed (scheme v2: method, path, query,
|
|
7
|
+
* body, propagated identity, time) with the PAIR secret the callee keeps for
|
|
8
|
+
* that caller (`internal.callers` in `vk.config.ts`), so the callee knows
|
|
9
|
+
* which venture is calling, and only the callee decides who may: a venture
|
|
10
|
+
* it did not list holds no secret it would accept.
|
|
11
|
+
*
|
|
12
|
+
* Pair secrets rotate (`internal.rotationDays`): the secret is a keyring
|
|
13
|
+
* `{"current","previous"}`. A caller signs with `current`; a callee accepts
|
|
14
|
+
* either. Both re-read the secret every {@link KEY_TTL_MS}, and a callee
|
|
15
|
+
* re-reads it at once when a declared caller's signature does not verify —
|
|
16
|
+
* so a rotation never refuses a call, whichever side learns of it first.
|
|
17
|
+
*/
|
|
18
|
+
import { internalCallerSecretName } from '@venturekit/core';
|
|
19
|
+
import { fetchSecretString, signRequestWithKey, verifyRequestWithKey } from './internal-hmac.js';
|
|
20
|
+
/** The header naming the calling venture. */
|
|
21
|
+
export const INTERNAL_CALLER_HEADER = 'x-venturekit-caller';
|
|
22
|
+
/** How long a read keyring is trusted before it is read again. */
|
|
23
|
+
export const KEY_TTL_MS = 15 * 60 * 1000;
|
|
24
|
+
/** A callee re-reads a caller's keyring after a failed signature at most this often. */
|
|
25
|
+
const REFETCH_ON_FAILURE_MS = 30 * 1000;
|
|
26
|
+
const isLocal = (env) => env.VENTURE_LOCAL === 'true';
|
|
27
|
+
/**
|
|
28
|
+
* Under `vk dev` both ventures derive the same per-pair key: there is no
|
|
29
|
+
* Secrets Manager, and the call never leaves the developer's machine.
|
|
30
|
+
*/
|
|
31
|
+
function localPairKey(callee, caller) {
|
|
32
|
+
return `venturekit-local-internal:${callee}:${caller}`;
|
|
33
|
+
}
|
|
34
|
+
/** What a pair signature binds besides the request: the callee venture and stage. */
|
|
35
|
+
export function internalTarget(callee, stage) {
|
|
36
|
+
return `internal:${callee}:${stage}`;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The keys in a pair secret, signing key first: a rotated keyring
|
|
40
|
+
* `{"current","previous"}`, a fresh `{"value"}`, or a raw string.
|
|
41
|
+
*/
|
|
42
|
+
export function parseKeyring(secretString) {
|
|
43
|
+
try {
|
|
44
|
+
const parsed = JSON.parse(secretString);
|
|
45
|
+
if (parsed && typeof parsed === 'object') {
|
|
46
|
+
const keys = [parsed.current, parsed.previous, parsed.value].filter((k) => typeof k === 'string' && k.length > 0);
|
|
47
|
+
if (keys.length > 0)
|
|
48
|
+
return keys;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
// not JSON — the whole string is the key
|
|
53
|
+
}
|
|
54
|
+
return [secretString];
|
|
55
|
+
}
|
|
56
|
+
let readSecret = fetchSecretString;
|
|
57
|
+
// ─── Callee: the keyrings of the callers it accepts ─────────────────
|
|
58
|
+
const callerKeys = new Map();
|
|
59
|
+
const inFlight = new Map();
|
|
60
|
+
function callerSecretArns(env) {
|
|
61
|
+
try {
|
|
62
|
+
return JSON.parse(env.VENTURE_INTERNAL_CALLER_SECRET_ARNS || '{}');
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return {};
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** Read one caller's keyring (deduplicated); a failure leaves the old one in place. */
|
|
69
|
+
function readCallerKeys(caller, arn) {
|
|
70
|
+
let pending = inFlight.get(caller);
|
|
71
|
+
if (!pending) {
|
|
72
|
+
pending = readSecret(arn)
|
|
73
|
+
.then((secret) => {
|
|
74
|
+
callerKeys.set(caller, { keys: parseKeyring(secret), at: Date.now() });
|
|
75
|
+
})
|
|
76
|
+
.catch((err) => {
|
|
77
|
+
console.warn(`[venturekit] Could not read the internal caller secret of '${caller}': its calls are refused until it can be read. ${err instanceof Error ? err.message : String(err)}`);
|
|
78
|
+
})
|
|
79
|
+
.finally(() => inFlight.delete(caller));
|
|
80
|
+
inFlight.set(caller, pending);
|
|
81
|
+
}
|
|
82
|
+
return pending;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Read the keyrings of every declared caller that is missing or older than
|
|
86
|
+
* {@link KEY_TTL_MS}. Never throws: an unreadable caller is not accepted
|
|
87
|
+
* (fail closed) and retried on the next request.
|
|
88
|
+
*/
|
|
89
|
+
export async function primeInternalCallerKeys(env = process.env, now = Date.now()) {
|
|
90
|
+
if (isLocal(env))
|
|
91
|
+
return;
|
|
92
|
+
const stale = Object.entries(callerSecretArns(env)).filter(([caller]) => {
|
|
93
|
+
const ring = callerKeys.get(caller);
|
|
94
|
+
return !ring || now - ring.at > KEY_TTL_MS;
|
|
95
|
+
});
|
|
96
|
+
await Promise.all(stale.map(([caller, arn]) => readCallerKeys(caller, arn)));
|
|
97
|
+
}
|
|
98
|
+
function keysFor(callee, caller, env) {
|
|
99
|
+
return isLocal(env) ? [localPairKey(callee, caller)] : (callerKeys.get(caller)?.keys ?? []);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* The verified caller of this invocation from the keyrings already read, or
|
|
103
|
+
* `null` (no caller header, an undeclared caller, or no key that verifies).
|
|
104
|
+
*/
|
|
105
|
+
export function verifyInternalCaller(headers, request, env = process.env, nowMs = Date.now()) {
|
|
106
|
+
const caller = headers?.[INTERNAL_CALLER_HEADER];
|
|
107
|
+
const callee = env.VENTURE_PROJECT_NAME;
|
|
108
|
+
if (!caller || !callee)
|
|
109
|
+
return null;
|
|
110
|
+
const target = internalTarget(callee, env.VENTURE_STAGE || 'dev');
|
|
111
|
+
return keysFor(callee, caller, env).some((key) => verifyRequestWithKey(headers, key, target, request, nowMs).valid)
|
|
112
|
+
? { project: caller }
|
|
113
|
+
: null;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* {@link verifyInternalCaller}, reading keyrings as needed: stale ones first,
|
|
117
|
+
* and a declared caller's again when its signature fails (its pair may just
|
|
118
|
+
* have rotated).
|
|
119
|
+
*/
|
|
120
|
+
export async function resolveInternalCaller(headers, request, env = process.env) {
|
|
121
|
+
await primeInternalCallerKeys(env);
|
|
122
|
+
const verified = verifyInternalCaller(headers, request, env);
|
|
123
|
+
if (verified || isLocal(env))
|
|
124
|
+
return verified;
|
|
125
|
+
const caller = headers?.[INTERNAL_CALLER_HEADER];
|
|
126
|
+
const arn = caller ? callerSecretArns(env)[caller] : undefined;
|
|
127
|
+
const ring = caller ? callerKeys.get(caller) : undefined;
|
|
128
|
+
if (!caller || !arn || (ring && Date.now() - ring.at < REFETCH_ON_FAILURE_MS))
|
|
129
|
+
return null;
|
|
130
|
+
await readCallerKeys(caller, arn);
|
|
131
|
+
return verifyInternalCaller(headers, request, env);
|
|
132
|
+
}
|
|
133
|
+
// ─── Caller: the key it signs with ──────────────────────────────────
|
|
134
|
+
const pairKeys = new Map();
|
|
135
|
+
/** The key this venture signs its calls to `callee` with (the keyring's current). */
|
|
136
|
+
export function pairKeyFor(callee, env = process.env, now = Date.now()) {
|
|
137
|
+
const self = env.VENTURE_PROJECT_NAME || 'app';
|
|
138
|
+
if (isLocal(env))
|
|
139
|
+
return Promise.resolve(localPairKey(callee, self));
|
|
140
|
+
const name = internalCallerSecretName(callee, env.VENTURE_STAGE || 'dev', self);
|
|
141
|
+
const cached = pairKeys.get(name);
|
|
142
|
+
if (cached && now - cached.at <= KEY_TTL_MS)
|
|
143
|
+
return cached.key;
|
|
144
|
+
const key = readSecret(name)
|
|
145
|
+
.then((secret) => parseKeyring(secret)[0])
|
|
146
|
+
.catch((err) => {
|
|
147
|
+
pairKeys.delete(name);
|
|
148
|
+
throw new Error(`[venturekit] Cannot call '${callee}': its internal caller secret for '${self}' (${name}) is unreadable — does '${callee}' list '${self}' in internal.callers, and this venture '${callee}' in internal.calls?`, { cause: err });
|
|
149
|
+
});
|
|
150
|
+
pairKeys.set(name, { key, at: now });
|
|
151
|
+
return key;
|
|
152
|
+
}
|
|
153
|
+
/** Sign a call to `callee`'s internal route. */
|
|
154
|
+
export async function signInternalRouteCall(callee, request, env = process.env) {
|
|
155
|
+
return signRequestWithKey(await pairKeyFor(callee, env), internalTarget(callee, env.VENTURE_STAGE || 'dev'), request);
|
|
156
|
+
}
|
|
157
|
+
/** Test-only: reset the caches, and optionally replace the Secrets Manager read. */
|
|
158
|
+
export function __resetInternalCallersForTests(reader) {
|
|
159
|
+
callerKeys.clear();
|
|
160
|
+
inFlight.clear();
|
|
161
|
+
pairKeys.clear();
|
|
162
|
+
readSecret = reader ?? fetchSecretString;
|
|
163
|
+
}
|
|
164
|
+
//# sourceMappingURL=internal-callers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"internal-callers.js","sourceRoot":"","sources":["../../src/security/internal-callers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,oBAAoB,EAAsB,MAAM,oBAAoB,CAAC;AAErH,6CAA6C;AAC7C,MAAM,CAAC,MAAM,sBAAsB,GAAG,qBAAqB,CAAC;AAQ5D,kEAAkE;AAClE,MAAM,CAAC,MAAM,UAAU,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AACzC,wFAAwF;AACxF,MAAM,qBAAqB,GAAG,EAAE,GAAG,IAAI,CAAC;AAExC,MAAM,OAAO,GAAG,CAAC,GAAsB,EAAE,EAAE,CAAC,GAAG,CAAC,aAAa,KAAK,MAAM,CAAC;AAEzE;;;GAGG;AACH,SAAS,YAAY,CAAC,MAAc,EAAE,MAAc;IAClD,OAAO,6BAA6B,MAAM,IAAI,MAAM,EAAE,CAAC;AACzD,CAAC;AAED,qFAAqF;AACrF,MAAM,UAAU,cAAc,CAAC,MAAc,EAAE,KAAa;IAC1D,OAAO,YAAY,MAAM,IAAI,KAAK,EAAE,CAAC;AACvC,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,YAAY,CAAC,YAAoB;IAC/C,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAA+D,CAAC;QACtG,IAAI,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;YACzC,MAAM,IAAI,GAA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Y,EAAE,EAAE;QACtB,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QACtB,MAAM,IAAI,KAAK,CACb,6BAA6B,MAAM,sCAAsC,IAAI,MAAM,IAAI,2BAA2B,MAAM,WAAW,IAAI,4CAA4C,MAAM,sBAAsB,EAC/M,EAAE,KAAK,EAAE,GAAG,EAAE,CACf,CAAC;IACJ,CAAC,CAAC,CAAC;IACL,QAAQ,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAE,CAAC,CAAC;IACrC,OAAO,GAAG,CAAC;AACb,CAAC;AAED,gDAAgD;AAChD,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,MAAc,EACd,OAAsB,EACtB,MAAyB,OAAO,CAAC,GAAG;IAEpC,OAAO,kBAAkB,CAAC,MAAM,UAAU,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,cAAc,CAAC,MAAM,EAAE,GAAG,CAAC,aAAa,IAAI,KAAK,CAAC,EAAE,OAAO,CAAC,CAAC;AACxH,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU,8BAA8B,CAAC,MAA+C;IAC5F,UAAU,CAAC,KAAK,EAAE,CAAC;IACnB,QAAQ,CAAC,KAAK,EAAE,CAAC;IACjB,QAAQ,CAAC,KAAK,EAAE,CAAC;IACjB,UAAU,GAAG,MAAM,IAAI,iBAAiB,CAAC;AAC3C,CAAC"}
|
|
@@ -41,7 +41,30 @@ export declare const INTERNAL_HMAC_HEADERS: {
|
|
|
41
41
|
readonly SIGNATURE: "x-venturekit-signature";
|
|
42
42
|
/** Unique invoke ID (opaque, purely for tracing) */
|
|
43
43
|
readonly INVOKE_ID: "x-venturekit-invoke-id";
|
|
44
|
+
/** Signature scheme version (`2`: the request itself is signed) */
|
|
45
|
+
readonly VERSION: "x-venturekit-signature-version";
|
|
44
46
|
};
|
|
47
|
+
/**
|
|
48
|
+
* What a v2 signature covers besides the target and the time: the request
|
|
49
|
+
* itself. v1 signed only `function:timestamp`, so a captured call could be
|
|
50
|
+
* replayed for five minutes with any body, path, or propagated identity.
|
|
51
|
+
*/
|
|
52
|
+
export interface SignedRequest {
|
|
53
|
+
method: string;
|
|
54
|
+
/** Path, as invoked (`/orders/123`). */
|
|
55
|
+
path: string;
|
|
56
|
+
/** Raw query string, without `?`. */
|
|
57
|
+
query?: string;
|
|
58
|
+
/** The body exactly as sent (`undefined` for none). */
|
|
59
|
+
body?: string;
|
|
60
|
+
/** The propagated `x-tenant-id` / `x-user-id` the receiver will trust. */
|
|
61
|
+
tenantId?: string;
|
|
62
|
+
userId?: string;
|
|
63
|
+
}
|
|
64
|
+
/** Read a key from Secrets Manager (`{"value":…}` or raw), with a timeout. */
|
|
65
|
+
export declare function fetchSecretKeyMaterial(arn: string): Promise<string>;
|
|
66
|
+
/** The secret's whole `SecretString` (a keyring, …), with a timeout. */
|
|
67
|
+
export declare function fetchSecretString(arn: string): Promise<string>;
|
|
45
68
|
/**
|
|
46
69
|
* Resolve the HMAC key from Secrets Manager when the deployment supplies it
|
|
47
70
|
* by ARN (`VENTURE_INTERNAL_HMAC_SECRET_ARN`). No-op when an inline
|
|
@@ -56,22 +79,45 @@ export declare const INTERNAL_HMAC_HEADERS: {
|
|
|
56
79
|
*/
|
|
57
80
|
export declare function primeInternalHmacSecret(): Promise<void>;
|
|
58
81
|
/**
|
|
59
|
-
*
|
|
60
|
-
*
|
|
82
|
+
* A key for ONE purpose, derived from the internal HMAC secret
|
|
83
|
+
* (`HMAC(secret, "venturekit:<purpose>:v1")`), so features that need a
|
|
84
|
+
* signing key (impersonation grants, …) never sign with the internal-call
|
|
85
|
+
* key itself and a leak of one derived key does not forge another. Uses
|
|
86
|
+
* the inline secret or the one {@link primeInternalHmacSecret} fetched;
|
|
87
|
+
* `null` when neither is available (the caller decides about local dev).
|
|
88
|
+
*/
|
|
89
|
+
export declare function deriveInternalKey(purpose: string): string | null;
|
|
90
|
+
/**
|
|
91
|
+
* Sign a request (scheme v2) with an explicit key and target — the primitive
|
|
92
|
+
* behind calls signed with something other than the venture's own internal
|
|
93
|
+
* key (the pair secrets of internal routes, `internalFetch`).
|
|
94
|
+
*/
|
|
95
|
+
export declare function signRequestWithKey(key: string, target: string, request: SignedRequest, timestampMs?: number): {
|
|
96
|
+
timestamp: string;
|
|
97
|
+
signature: string;
|
|
98
|
+
version: '2';
|
|
99
|
+
};
|
|
100
|
+
/** Verify a v2 signature made with {@link signRequestWithKey} (v1 is never accepted here). */
|
|
101
|
+
export declare function verifyRequestWithKey(headers: Record<string, string | undefined> | undefined, key: string, target: string, request: SignedRequest, nowMs?: number): VerifyResult;
|
|
102
|
+
/**
|
|
103
|
+
* Sign an internal invocation (scheme v2: target, time AND request). Returns
|
|
104
|
+
* the values for the {@link INTERNAL_HMAC_HEADERS} the caller attaches.
|
|
61
105
|
*
|
|
62
106
|
* @param functionName - The resolved target Lambda function name.
|
|
107
|
+
* @param request - The request being sent — see {@link SignedRequest}.
|
|
63
108
|
* @param timestampMs - Caller timestamp. Defaults to `Date.now()`; pass an
|
|
64
109
|
* explicit value for deterministic tests.
|
|
65
110
|
*/
|
|
66
|
-
export declare function signInternalCall(functionName: string, timestampMs?: number): {
|
|
111
|
+
export declare function signInternalCall(functionName: string, request: SignedRequest, timestampMs?: number): {
|
|
67
112
|
timestamp: string;
|
|
68
113
|
signature: string;
|
|
114
|
+
version: '2';
|
|
69
115
|
};
|
|
70
116
|
export type VerifyResult = {
|
|
71
117
|
valid: true;
|
|
72
118
|
} | {
|
|
73
119
|
valid: false;
|
|
74
|
-
reason: 'missing-headers' | 'bad-timestamp' | 'expired' | 'bad-signature' | 'no-secret';
|
|
120
|
+
reason: 'missing-headers' | 'bad-timestamp' | 'expired' | 'bad-signature' | 'no-secret' | 'unsupported-version';
|
|
75
121
|
};
|
|
76
122
|
/**
|
|
77
123
|
* Verify an internal-call signature against the current function's name.
|
|
@@ -82,9 +128,11 @@ export type VerifyResult = {
|
|
|
82
128
|
* @param headers - Lowercased header map from the Lambda event.
|
|
83
129
|
* @param functionName - Usually `process.env.AWS_LAMBDA_FUNCTION_NAME`. Callers
|
|
84
130
|
* may pass an explicit name for tests.
|
|
131
|
+
* @param request - The received request (method, path, query, body and
|
|
132
|
+
* the propagated identity headers) — what v2 signs.
|
|
85
133
|
* @param nowMs - Override for "now" in tests.
|
|
86
134
|
*/
|
|
87
|
-
export declare function verifyInternalCall(headers: Record<string, string | undefined> | undefined, functionName: string | undefined, nowMs?: number): VerifyResult;
|
|
135
|
+
export declare function verifyInternalCall(headers: Record<string, string | undefined> | undefined, functionName: string | undefined, request: SignedRequest, nowMs?: number): VerifyResult;
|
|
88
136
|
/** Reset the warned-about-fallback flag and the primed secret. Test-only helper. */
|
|
89
137
|
export declare function __resetHmacWarningForTests(): void;
|
|
90
138
|
//# sourceMappingURL=internal-hmac.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal-hmac.d.ts","sourceRoot":"","sources":["../../src/security/internal-hmac.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAIH,eAAO,MAAM,qBAAqB;IAChC,8DAA8D;;IAE9D,gDAAgD;;IAEhD,wCAAwC;;IAExC,oDAAoD;;
|
|
1
|
+
{"version":3,"file":"internal-hmac.d.ts","sourceRoot":"","sources":["../../src/security/internal-hmac.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAIH,eAAO,MAAM,qBAAqB;IAChC,8DAA8D;;IAE9D,gDAAgD;;IAEhD,wCAAwC;;IAExC,oDAAoD;;IAEpD,mEAAmE;;CAE3D,CAAC;AAEX;;;;GAIG;AACH,MAAM,WAAW,aAAa;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,wCAAwC;IACxC,IAAI,EAAE,MAAM,CAAC;IACb,qCAAqC;IACrC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,uDAAuD;IACvD,IAAI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,KAAK,EAAE,IAAI,CAAA;CAAE,GACf;IACE,KAAK,EAAE,KAAK,CAAC;IACb,MAAM,EAAE,iBAAiB,GAAG,eAAe,GAAG,SAAS,GAAG,eAAe,GAAG,WAAW,GAAG,qBAAqB,CAAC;CACjH,CAAC;AAEN;;;;;;;;;;;;GAYG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,GAAG,SAAS,EACvD,YAAY,EAAE,MAAM,GAAG,SAAS,EAChC,OAAO,EAAE,aAAa,EACtB,KAAK,GAAE,MAAmB,GACzB,YAAY,CAyCd;AAED,oFAAoF;AACpF,wBAAgB,0BAA0B,IAAI,IAAI,CAKjD"}
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
* Replay window is 5 minutes (configurable via `VENTURE_INTERNAL_HMAC_TTL_MS`).
|
|
33
33
|
* Signatures outside that window are rejected.
|
|
34
34
|
*/
|
|
35
|
-
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
35
|
+
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
|
|
36
36
|
export const INTERNAL_HMAC_HEADERS = {
|
|
37
37
|
/** Marker that this is an internal invocation ("internal") */
|
|
38
38
|
SOURCE: 'x-venturekit-source',
|
|
@@ -42,7 +42,26 @@ export const INTERNAL_HMAC_HEADERS = {
|
|
|
42
42
|
SIGNATURE: 'x-venturekit-signature',
|
|
43
43
|
/** Unique invoke ID (opaque, purely for tracing) */
|
|
44
44
|
INVOKE_ID: 'x-venturekit-invoke-id',
|
|
45
|
+
/** Signature scheme version (`2`: the request itself is signed) */
|
|
46
|
+
VERSION: 'x-venturekit-signature-version',
|
|
45
47
|
};
|
|
48
|
+
function sha256Hex(value) {
|
|
49
|
+
return createHash('sha256').update(value, 'utf8').digest('hex');
|
|
50
|
+
}
|
|
51
|
+
/** The exact bytes a v2 signature covers. */
|
|
52
|
+
function canonicalV2(functionName, ts, req) {
|
|
53
|
+
return [
|
|
54
|
+
'v2',
|
|
55
|
+
functionName,
|
|
56
|
+
ts,
|
|
57
|
+
req.method.toUpperCase(),
|
|
58
|
+
req.path,
|
|
59
|
+
req.query ?? '',
|
|
60
|
+
sha256Hex(req.body ?? ''),
|
|
61
|
+
req.tenantId ?? '',
|
|
62
|
+
req.userId ?? '',
|
|
63
|
+
].join('\n');
|
|
64
|
+
}
|
|
46
65
|
const DEFAULT_TTL_MS = 5 * 60 * 1000;
|
|
47
66
|
const LOCAL_DEV_SECRET = 'venturekit-local-dev-secret';
|
|
48
67
|
let warnedAboutFallback = false;
|
|
@@ -80,7 +99,15 @@ function extractKeyMaterial(secretString) {
|
|
|
80
99
|
}
|
|
81
100
|
return secretString;
|
|
82
101
|
}
|
|
102
|
+
/** Read a key from Secrets Manager (`{"value":…}` or raw), with a timeout. */
|
|
103
|
+
export async function fetchSecretKeyMaterial(arn) {
|
|
104
|
+
return fetchSecret(arn);
|
|
105
|
+
}
|
|
83
106
|
async function fetchSecret(arn) {
|
|
107
|
+
return extractKeyMaterial(await fetchSecretString(arn));
|
|
108
|
+
}
|
|
109
|
+
/** The secret's whole `SecretString` (a keyring, …), with a timeout. */
|
|
110
|
+
export async function fetchSecretString(arn) {
|
|
84
111
|
// Lazy import — keeps the SDK out of the require graph for local runs
|
|
85
112
|
// and test suites; Lambda's Node runtimes ship the v3 SDK regardless.
|
|
86
113
|
const sm = await import('@aws-sdk/client-secrets-manager');
|
|
@@ -97,7 +124,7 @@ async function fetchSecret(arn) {
|
|
|
97
124
|
if (!result.SecretString) {
|
|
98
125
|
throw new Error('secret has no SecretString');
|
|
99
126
|
}
|
|
100
|
-
return
|
|
127
|
+
return result.SecretString;
|
|
101
128
|
}
|
|
102
129
|
finally {
|
|
103
130
|
clearTimeout(timer);
|
|
@@ -162,6 +189,18 @@ function getSecret() {
|
|
|
162
189
|
}
|
|
163
190
|
return LOCAL_DEV_SECRET;
|
|
164
191
|
}
|
|
192
|
+
/**
|
|
193
|
+
* A key for ONE purpose, derived from the internal HMAC secret
|
|
194
|
+
* (`HMAC(secret, "venturekit:<purpose>:v1")`), so features that need a
|
|
195
|
+
* signing key (impersonation grants, …) never sign with the internal-call
|
|
196
|
+
* key itself and a leak of one derived key does not forge another. Uses
|
|
197
|
+
* the inline secret or the one {@link primeInternalHmacSecret} fetched;
|
|
198
|
+
* `null` when neither is available (the caller decides about local dev).
|
|
199
|
+
*/
|
|
200
|
+
export function deriveInternalKey(purpose) {
|
|
201
|
+
const secret = configuredSecret();
|
|
202
|
+
return secret ? hmacHex(secret, `venturekit:${purpose}:v1`) : null;
|
|
203
|
+
}
|
|
165
204
|
/** TTL window in ms beyond which signatures are rejected. */
|
|
166
205
|
function getTtlMs() {
|
|
167
206
|
const raw = process.env.VENTURE_INTERNAL_HMAC_TTL_MS;
|
|
@@ -174,17 +213,54 @@ function hmacHex(secret, payload) {
|
|
|
174
213
|
return createHmac('sha256', secret).update(payload).digest('hex');
|
|
175
214
|
}
|
|
176
215
|
/**
|
|
177
|
-
* Sign
|
|
178
|
-
*
|
|
216
|
+
* Sign a request (scheme v2) with an explicit key and target — the primitive
|
|
217
|
+
* behind calls signed with something other than the venture's own internal
|
|
218
|
+
* key (the pair secrets of internal routes, `internalFetch`).
|
|
219
|
+
*/
|
|
220
|
+
export function signRequestWithKey(key, target, request, timestampMs = Date.now()) {
|
|
221
|
+
const ts = String(timestampMs);
|
|
222
|
+
return { timestamp: ts, signature: hmacHex(key, canonicalV2(target, ts, request)), version: '2' };
|
|
223
|
+
}
|
|
224
|
+
/** Verify a v2 signature made with {@link signRequestWithKey} (v1 is never accepted here). */
|
|
225
|
+
export function verifyRequestWithKey(headers, key, target, request, nowMs = Date.now()) {
|
|
226
|
+
const ts = headers?.[INTERNAL_HMAC_HEADERS.TIMESTAMP];
|
|
227
|
+
const sig = headers?.[INTERNAL_HMAC_HEADERS.SIGNATURE];
|
|
228
|
+
if (!ts || !sig)
|
|
229
|
+
return { valid: false, reason: 'missing-headers' };
|
|
230
|
+
if (headers?.[INTERNAL_HMAC_HEADERS.VERSION] !== '2')
|
|
231
|
+
return { valid: false, reason: 'unsupported-version' };
|
|
232
|
+
const tsNum = Number(ts);
|
|
233
|
+
if (!Number.isFinite(tsNum))
|
|
234
|
+
return { valid: false, reason: 'bad-timestamp' };
|
|
235
|
+
if (Math.abs(nowMs - tsNum) > getTtlMs())
|
|
236
|
+
return { valid: false, reason: 'expired' };
|
|
237
|
+
const expected = Buffer.from(hmacHex(key, canonicalV2(target, ts, request)), 'hex');
|
|
238
|
+
const actual = Buffer.from(/^[0-9a-f]+$/i.test(sig) ? sig : '', 'hex');
|
|
239
|
+
return expected.length === actual.length && timingSafeEqual(expected, actual)
|
|
240
|
+
? { valid: true }
|
|
241
|
+
: { valid: false, reason: 'bad-signature' };
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Sign an internal invocation (scheme v2: target, time AND request). Returns
|
|
245
|
+
* the values for the {@link INTERNAL_HMAC_HEADERS} the caller attaches.
|
|
179
246
|
*
|
|
180
247
|
* @param functionName - The resolved target Lambda function name.
|
|
248
|
+
* @param request - The request being sent — see {@link SignedRequest}.
|
|
181
249
|
* @param timestampMs - Caller timestamp. Defaults to `Date.now()`; pass an
|
|
182
250
|
* explicit value for deterministic tests.
|
|
183
251
|
*/
|
|
184
|
-
export function signInternalCall(functionName, timestampMs = Date.now()) {
|
|
252
|
+
export function signInternalCall(functionName, request, timestampMs = Date.now()) {
|
|
185
253
|
const ts = String(timestampMs);
|
|
186
|
-
const signature = hmacHex(getSecret(),
|
|
187
|
-
return { timestamp: ts, signature };
|
|
254
|
+
const signature = hmacHex(getSecret(), canonicalV2(functionName, ts, request));
|
|
255
|
+
return { timestamp: ts, signature, version: '2' };
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Accept v1 signatures (`function:timestamp` only) — a transition switch
|
|
259
|
+
* for a deployment whose callers still run a release older than v2.
|
|
260
|
+
* Off unless `VENTURE_INTERNAL_HMAC_ACCEPT_V1=true`.
|
|
261
|
+
*/
|
|
262
|
+
function acceptsV1() {
|
|
263
|
+
return process.env.VENTURE_INTERNAL_HMAC_ACCEPT_V1 === 'true';
|
|
188
264
|
}
|
|
189
265
|
/**
|
|
190
266
|
* Verify an internal-call signature against the current function's name.
|
|
@@ -195,11 +271,17 @@ export function signInternalCall(functionName, timestampMs = Date.now()) {
|
|
|
195
271
|
* @param headers - Lowercased header map from the Lambda event.
|
|
196
272
|
* @param functionName - Usually `process.env.AWS_LAMBDA_FUNCTION_NAME`. Callers
|
|
197
273
|
* may pass an explicit name for tests.
|
|
274
|
+
* @param request - The received request (method, path, query, body and
|
|
275
|
+
* the propagated identity headers) — what v2 signs.
|
|
198
276
|
* @param nowMs - Override for "now" in tests.
|
|
199
277
|
*/
|
|
200
|
-
export function verifyInternalCall(headers, functionName, nowMs = Date.now()) {
|
|
278
|
+
export function verifyInternalCall(headers, functionName, request, nowMs = Date.now()) {
|
|
201
279
|
if (!headers || !functionName)
|
|
202
280
|
return { valid: false, reason: 'missing-headers' };
|
|
281
|
+
const version = headers[INTERNAL_HMAC_HEADERS.VERSION] ?? '1';
|
|
282
|
+
if (version !== '2' && !(version === '1' && acceptsV1())) {
|
|
283
|
+
return { valid: false, reason: 'unsupported-version' };
|
|
284
|
+
}
|
|
203
285
|
const source = headers[INTERNAL_HMAC_HEADERS.SOURCE];
|
|
204
286
|
const ts = headers[INTERNAL_HMAC_HEADERS.TIMESTAMP];
|
|
205
287
|
const sig = headers[INTERNAL_HMAC_HEADERS.SIGNATURE];
|
|
@@ -216,7 +298,7 @@ export function verifyInternalCall(headers, functionName, nowMs = Date.now()) {
|
|
|
216
298
|
if (!configuredSecret() && isLambdaRuntime()) {
|
|
217
299
|
return { valid: false, reason: 'no-secret' };
|
|
218
300
|
}
|
|
219
|
-
const expected = hmacHex(getSecret(), `${functionName}:${ts}`);
|
|
301
|
+
const expected = hmacHex(getSecret(), version === '2' ? canonicalV2(functionName, ts, request) : `${functionName}:${ts}`);
|
|
220
302
|
// Hex strings of the same byte length → safe for timingSafeEqual after buffering.
|
|
221
303
|
let expectedBuf;
|
|
222
304
|
let actualBuf;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal-hmac.js","sourceRoot":"","sources":["../../src/security/internal-hmac.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAEH,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"internal-hmac.js","sourceRoot":"","sources":["../../src/security/internal-hmac.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAEH,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEtE,MAAM,CAAC,MAAM,qBAAqB,GAAG;IACnC,8DAA8D;IAC9D,MAAM,EAAE,qBAAqB;IAC7B,gDAAgD;IAChD,SAAS,EAAE,wBAAwB;IACnC,wCAAwC;IACxC,SAAS,EAAE,wBAAwB;IACnC,oDAAoD;IACpD,SAAS,EAAE,wBAAwB;IACnC,mEAAmE;IACnE,OAAO,EAAE,gCAAgC;CACjC,CAAC;AAoBX,SAAS,SAAS,CAAC,KAAa;IAC9B,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAClE,CAAC;AAED,6CAA6C;AAC7C,SAAS,WAAW,CAAC,YAAoB,EAAE,EAAU,EAAE,GAAkB;IACvE,OAAO;QACL,IAAI;QACJ,YAAY;QACZ,EAAE;QACF,GAAG,CAAC,MAAM,CAAC,WAAW,EAAE;QACxB,GAAG,CAAC,IAAI;QACR,GAAG,CAAC,KAAK,IAAI,EAAE;QACf,SAAS,CAAC,GAAG,CAAC,IAAI,IAAI,EAAE,CAAC;QACzB,GAAG,CAAC,QAA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AAW,CAAC,MAAM,KAAK,CAAC,IAAI,WAAW,CAAC,MAAM,KAAK,SAAS,CAAC,MAAM,EAAE,CAAC;QACxE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,CAAC;IACnD,CAAC;IACD,OAAO,eAAe,CAAC,WAAW,EAAE,SAAS,CAAC;QAC5C,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE;QACjB,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,CAAC;AAChD,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU,0BAA0B;IACxC,mBAAmB,GAAG,KAAK,CAAC;IAC5B,uBAAuB,GAAG,KAAK,CAAC;IAChC,aAAa,GAAG,IAAI,CAAC;IACrB,OAAO,GAAG,IAAI,CAAC;AACjB,CAAC"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The WebSocket `$connect` twin of `originCheckMiddleware`.
|
|
3
|
+
*
|
|
4
|
+
* A browser attaches cookies to a WebSocket handshake whatever page opened
|
|
5
|
+
* it, and the handshake is a GET no CSRF rule covers — so a socket that
|
|
6
|
+
* authenticates by cookie must refuse a handshake from any page that is not
|
|
7
|
+
* one of the app's own (cross-site WebSocket hijacking). Browsers always
|
|
8
|
+
* send `Origin` on a handshake; native clients and servers usually do not,
|
|
9
|
+
* and carry a bearer token instead — they pass.
|
|
10
|
+
*/
|
|
11
|
+
export interface WebSocketOriginOptions {
|
|
12
|
+
/**
|
|
13
|
+
* Origins (`https://app.example.com`) allowed to open a cookie-authenticated
|
|
14
|
+
* socket, or a predicate over the lower-cased origin. A `.apex` entry
|
|
15
|
+
* (`.example.com`) matches every https subdomain.
|
|
16
|
+
*/
|
|
17
|
+
allowedOrigins: readonly string[] | ((origin: string) => boolean);
|
|
18
|
+
/** The cookie names that authenticate the socket. Default: any cookie counts. */
|
|
19
|
+
credentialCookies?: readonly string[];
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* May this `$connect` proceed? `false` only for a handshake that carries a
|
|
23
|
+
* credential cookie and comes from a page outside `allowedOrigins` (or names
|
|
24
|
+
* no origin at all while carrying one — a browser never does that).
|
|
25
|
+
*/
|
|
26
|
+
export declare function webSocketOriginAllowed(event: {
|
|
27
|
+
headers?: Record<string, string | undefined>;
|
|
28
|
+
cookies?: string[];
|
|
29
|
+
}, options: WebSocketOriginOptions): boolean;
|
|
30
|
+
//# sourceMappingURL=ws-origin.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ws-origin.d.ts","sourceRoot":"","sources":["../../src/ws/ws-origin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,MAAM,WAAW,sBAAsB;IACrC;;;;OAIG;IACH,cAAc,EAAE,SAAS,MAAM,EAAE,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC;IAClE,iFAAiF;IACjF,iBAAiB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACvC;AAoBD;;;;GAIG;AACH,wBAAgB,sBAAsB,CACpC,KAAK,EAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,EAC3E,OAAO,EAAE,sBAAsB,GAC9B,OAAO,CAiBT"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The WebSocket `$connect` twin of `originCheckMiddleware`.
|
|
3
|
+
*
|
|
4
|
+
* A browser attaches cookies to a WebSocket handshake whatever page opened
|
|
5
|
+
* it, and the handshake is a GET no CSRF rule covers — so a socket that
|
|
6
|
+
* authenticates by cookie must refuse a handshake from any page that is not
|
|
7
|
+
* one of the app's own (cross-site WebSocket hijacking). Browsers always
|
|
8
|
+
* send `Origin` on a handshake; native clients and servers usually do not,
|
|
9
|
+
* and carry a bearer token instead — they pass.
|
|
10
|
+
*/
|
|
11
|
+
function lower(headers, name) {
|
|
12
|
+
if (!headers)
|
|
13
|
+
return undefined;
|
|
14
|
+
return headers[name] ?? Object.entries(headers).find(([k]) => k.toLowerCase() === name)?.[1];
|
|
15
|
+
}
|
|
16
|
+
function originAllowed(origin, allowed) {
|
|
17
|
+
if (typeof allowed === 'function')
|
|
18
|
+
return allowed(origin);
|
|
19
|
+
const host = origin.replace(/^https?:\/\//, '').replace(/:\d+$/, '');
|
|
20
|
+
return allowed.some((entry) => {
|
|
21
|
+
const e = entry.toLowerCase().replace(/\/+$/, '');
|
|
22
|
+
if (e.startsWith('.')) {
|
|
23
|
+
const apex = e.slice(1);
|
|
24
|
+
return origin.startsWith('https://') && (host === apex || host.endsWith(`.${apex}`));
|
|
25
|
+
}
|
|
26
|
+
return origin === e;
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* May this `$connect` proceed? `false` only for a handshake that carries a
|
|
31
|
+
* credential cookie and comes from a page outside `allowedOrigins` (or names
|
|
32
|
+
* no origin at all while carrying one — a browser never does that).
|
|
33
|
+
*/
|
|
34
|
+
export function webSocketOriginAllowed(event, options) {
|
|
35
|
+
const cookieHeader = lower(event.headers, 'cookie') ?? '';
|
|
36
|
+
const pairs = event.cookies?.length ? event.cookies : cookieHeader ? cookieHeader.split(';') : [];
|
|
37
|
+
const names = pairs.map((p) => p.split('=')[0].trim()).filter(Boolean);
|
|
38
|
+
const credentialed = options.credentialCookies
|
|
39
|
+
? names.some((n) => options.credentialCookies.includes(n))
|
|
40
|
+
: names.length > 0;
|
|
41
|
+
if (!credentialed)
|
|
42
|
+
return true;
|
|
43
|
+
const raw = lower(event.headers, 'origin');
|
|
44
|
+
if (!raw || raw === 'null')
|
|
45
|
+
return false;
|
|
46
|
+
let origin;
|
|
47
|
+
try {
|
|
48
|
+
origin = new URL(raw).origin.toLowerCase();
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
return originAllowed(origin, options.allowedOrigins);
|
|
54
|
+
}
|
|
55
|
+
//# sourceMappingURL=ws-origin.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ws-origin.js","sourceRoot":"","sources":["../../src/ws/ws-origin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAaH,SAAS,KAAK,CAAC,OAAuD,EAAE,IAAY;IAClF,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IAC/B,OAAO,OAAO,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,KAAK,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AAC/F,CAAC;AAED,SAAS,aAAa,CAAC,MAAc,EAAE,OAAiD;IACtF,IAAI,OAAO,OAAO,KAAK,UAAU;QAAE,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC;IAC1D,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,cAAc,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;IACrE,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE;QAC5B,MAAM,CAAC,GAAG,KAAK,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QAClD,IAAI,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;YACtB,MAAM,IAAI,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YACxB,OAAO,MAAM,CAAC,UAAU,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,C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,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC;AACvD,CAAC"}
|
package/dist/ws/ws.d.ts
CHANGED
|
@@ -57,6 +57,10 @@ export interface ConnectionRecord {
|
|
|
57
57
|
email?: string;
|
|
58
58
|
connectedAt: number;
|
|
59
59
|
authenticatedAt?: number;
|
|
60
|
+
/** When the authenticating credential expires (ms epoch). */
|
|
61
|
+
authExpiresAt?: number;
|
|
62
|
+
/** The audience the connection was authenticated for (see `ConnectionMetadata.audience`). */
|
|
63
|
+
audience?: string;
|
|
60
64
|
ttl: number;
|
|
61
65
|
[key: string]: unknown;
|
|
62
66
|
}
|
|
@@ -64,8 +68,24 @@ export interface ConnectionMetadata {
|
|
|
64
68
|
userId: string;
|
|
65
69
|
tenantId?: string;
|
|
66
70
|
email?: string;
|
|
71
|
+
/**
|
|
72
|
+
* When the credential that authenticated the connection expires (ms
|
|
73
|
+
* epoch — the verified token's `exp * 1000`). The connection stops
|
|
74
|
+
* receiving messages at that moment; the client re-sends a fresh token
|
|
75
|
+
* over the socket to keep it. Default: {@link DEFAULT_AUTH_LIFETIME_SECONDS}.
|
|
76
|
+
*/
|
|
77
|
+
expiresAt?: number;
|
|
78
|
+
/**
|
|
79
|
+
* Which audience inside the tenant this connection belongs to (`desk`,
|
|
80
|
+
* `driver`, …). `sendToTenant(…, { audience })` reaches only connections
|
|
81
|
+
* authenticated with that audience — the filter is the store's, so a
|
|
82
|
+
* caller cannot forget it.
|
|
83
|
+
*/
|
|
84
|
+
audience?: string;
|
|
67
85
|
[key: string]: unknown;
|
|
68
86
|
}
|
|
87
|
+
/** True while the connection is authenticated and its credential unexpired. */
|
|
88
|
+
export declare function isConnectionAuthenticated(record: ConnectionRecord | null, now?: number): boolean;
|
|
69
89
|
/**
|
|
70
90
|
* Process-local WebSocket hub interface — installed by `@venturekit/cli`'s
|
|
71
91
|
* `vk dev` server on `globalThis.__VK_LOCAL_WS_HUB__`. Every method on
|
|
@@ -167,10 +187,13 @@ export declare const connectionStore: {
|
|
|
167
187
|
*/
|
|
168
188
|
sendToUser(domainName: string, stage: string, userId: string, data: unknown): Promise<number>;
|
|
169
189
|
/**
|
|
170
|
-
* Send data to all connections within a specific tenant
|
|
190
|
+
* Send data to all connections within a specific tenant — or, with
|
|
191
|
+
* `audience`, only to those authenticated for that audience.
|
|
171
192
|
* Returns the number of connections that received the message.
|
|
172
193
|
*/
|
|
173
|
-
sendToTenant(domainName: string, stage: string, tenantId: string, data: unknown
|
|
194
|
+
sendToTenant(domainName: string, stage: string, tenantId: string, data: unknown, options?: {
|
|
195
|
+
audience?: string;
|
|
196
|
+
}): Promise<number>;
|
|
174
197
|
/**
|
|
175
198
|
* Broadcast data to all authenticated connections.
|
|
176
199
|
* Returns the number of clients that received the message.
|
package/dist/ws/ws.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ws.d.ts","sourceRoot":"","sources":["../../src/ws/ws.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkDG;AAKH,MAAM,WAAW,gBAAgB;IAC/B,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,OAAO,CAAC;IACvB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,kBAAkB;IACjC,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,CAAC,GAAG,EAAE,MAAM,GAAG,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