New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@casual-simulation/aux-records

Package Overview
Dependencies
Maintainers
2
Versions
198
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@casual-simulation/aux-records - npm Package Compare versions

Comparing version 3.2.6 to 3.2.7-alpha.6226622763

RecordsServer.d.ts

2

AIController.d.ts

@@ -1,2 +0,2 @@

import { InvalidSubscriptionTierError, NotAuthorizedError, NotLoggedInError, NotSubscribedError, NotSupportedError, ServerError, SubscriptionLimitReached } from './Errors';
import { InvalidSubscriptionTierError, NotAuthorizedError, NotLoggedInError, NotSubscribedError, NotSupportedError, ServerError, SubscriptionLimitReached } from '@casual-simulation/aux-common/Errors';
import { AIChatInterface, AIChatMessage } from './AIChatInterface';

@@ -3,0 +3,0 @@ import { AIGenerateSkyboxInterface, AIGenerateSkyboxInterfaceBlockadeLabsOptions } from './AIGenerateSkyboxInterface';

@@ -1,2 +0,2 @@

import { ServerError } from './Errors';
import { ServerError } from '@casual-simulation/aux-common/Errors';
/**

@@ -3,0 +3,0 @@ * Defines an interface that is able to send and receive AI chat messages.

import { AddressType, AuthStore, AuthUser } from './AuthStore';
import { ServerError } from './Errors';
import { ServerError } from '@casual-simulation/aux-common/Errors';
import { AuthMessenger } from './AuthMessenger';

@@ -39,2 +39,6 @@ import { RegexRule } from './Utils';

/**
* The error message that should be used for invalid_token error messages.
*/
export declare const INVALID_TOKEN_ERROR_MESSAGE = "The connection token is invalid.";
/**
* The maximum allowed length for an email address.

@@ -64,2 +68,3 @@ */

validateSessionKey(key: string): Promise<ValidateSessionKeyResult>;
validateConnectionToken(token: string): Promise<ValidateConnectionTokenResult>;
revokeSession(request: RevokeSessionRequest): Promise<RevokeSessionResult>;

@@ -184,2 +189,6 @@ /**

/**
* The connection key that provides websocket access for the session.
*/
connectionKey: string;
/**
* The unix timestamp in miliseconds that the session will expire at.

@@ -221,2 +230,41 @@ */

}
export type ValidateConnectionTokenResult = ValidateConnectionTokenSuccess | ValidateConnectionTokenFailure;
export interface ValidateConnectionTokenSuccess {
success: true;
/**
* The ID of the user that owns the connection token.
*/
userId: string;
/**
* The ID of the session that the connection token is for.
*/
sessionId: string;
/**
* The ID that the client wants for the connection.
*/
connectionId: string;
/**
* The name of the record that the connection token was generated for.
*/
recordName: string;
/**
* The instance that the connection token was generated for.
*/
inst: string;
allSessionsRevokedTimeMs?: number;
/**
* The subscription ID for the user.
*/
subscriptionTier?: string;
/**
* The ID of the subscription that the user is subscribed to.
*/
subscriptionId?: string;
}
export interface ValidateConnectionTokenFailure {
success: false;
errorCode: 'unacceptable_connection_token' | 'invalid_token' | 'session_expired' | 'user_is_banned' | ServerError;
errorMessage: string;
banReason?: AuthUser['banReason'];
}
export interface RevokeSessionRequest {

@@ -350,2 +398,6 @@ /**

/**
* The connection key that provides websocket access for the session.
*/
connectionKey: string;
/**
* The unix timestamp in miliseconds that the session will expire at.

@@ -352,0 +404,0 @@ */

@@ -15,3 +15,4 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

import { cleanupObject, isActiveSubscription, isStringValid, } from './Utils';
import { formatV1SessionKey, parseSessionKey, randomCode, } from './AuthUtils';
import { formatV1ConnectionKey, formatV1SessionKey, parseSessionKey, randomCode, verifyConnectionToken, } from './AuthUtils';
import { parseConnectionToken } from '@casual-simulation/aux-common';
/**

@@ -50,2 +51,6 @@ * The number of miliseconds that a login request should be valid for before expiration.

/**
* The error message that should be used for invalid_token error messages.
*/
export const INVALID_TOKEN_ERROR_MESSAGE = 'The connection token is invalid.';
/**
* The maximum allowed length for an email address.

@@ -335,2 +340,3 @@ */

const sessionSecret = fromByteArray(randomBytes(SESSION_SECRET_BYTE_LENGTH));
const connectionSecret = fromByteArray(randomBytes(SESSION_SECRET_BYTE_LENGTH));
const now = Date.now();

@@ -344,2 +350,3 @@ const session = {

secretHash: hashHighEntropyPasswordWithSalt(sessionSecret, sessionId),
connectionSecret: connectionSecret,
grantedTimeMs: now,

@@ -358,2 +365,3 @@ revokeTimeMs: null,

sessionKey: formatV1SessionKey(loginRequest.userId, sessionId, sessionSecret, session.expireTimeMs),
connectionKey: formatV1ConnectionKey(loginRequest.userId, sessionId, connectionSecret, session.expireTimeMs),
expireTimeMs: session.expireTimeMs,

@@ -476,2 +484,107 @@ };

}
validateConnectionToken(token) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof token !== 'string' || token === '') {
return {
success: false,
errorCode: 'unacceptable_connection_token',
errorMessage: 'The given connection token is invalid. It must be a correctly formatted string.',
};
}
try {
const tokenValues = parseConnectionToken(token);
if (!tokenValues) {
console.log('[AuthController] [validateConnectionToken] Could not parse token.');
return {
success: false,
errorCode: 'unacceptable_connection_token',
errorMessage: 'The given connection token is invalid. It must be a correctly formatted string.',
};
}
const [userId, sessionId, connectionId, recordName, inst, hash] = tokenValues;
const session = yield this._store.findSession(userId, sessionId);
if (!session) {
console.log('[AuthController] [validateConnectionToken] Could not find session.');
return {
success: false,
errorCode: 'invalid_token',
errorMessage: INVALID_TOKEN_ERROR_MESSAGE,
};
}
if (!verifyConnectionToken(token, session.connectionSecret)) {
console.log('[AuthController] [validateConnectionToken] Connection token was invalid.');
return {
success: false,
errorCode: 'invalid_token',
errorMessage: INVALID_TOKEN_ERROR_MESSAGE,
};
}
const now = Date.now();
if (session.revokeTimeMs && now >= session.revokeTimeMs) {
console.log('[AuthController] [validateConnectionToken] Session has been revoked.');
return {
success: false,
errorCode: 'invalid_token',
errorMessage: INVALID_TOKEN_ERROR_MESSAGE,
};
}
if (now >= session.expireTimeMs) {
console.log('[AuthController] [validateConnectionToken] Session has expired.');
return {
success: false,
errorCode: 'session_expired',
errorMessage: 'The session has expired.',
};
}
const userInfo = yield this._store.findUser(userId);
if (!userInfo) {
console.log('[AuthController] [validateConnectionToken] Unable to find user!');
return {
success: false,
errorCode: 'invalid_token',
errorMessage: INVALID_TOKEN_ERROR_MESSAGE,
};
}
else {
if (typeof userInfo.allSessionRevokeTimeMs === 'number') {
if (userInfo.allSessionRevokeTimeMs >= session.grantedTimeMs) {
return {
success: false,
errorCode: 'invalid_token',
errorMessage: INVALID_TOKEN_ERROR_MESSAGE,
};
}
}
if (userInfo.banTimeMs > 0) {
return {
success: false,
errorCode: 'user_is_banned',
errorMessage: 'The user has been banned.',
banReason: userInfo.banReason,
};
}
}
const { subscriptionId, subscriptionTier } = yield this._getSubscriptionInfo(userInfo);
return {
success: true,
userId: session.userId,
sessionId: session.sessionId,
connectionId: connectionId,
recordName: recordName,
inst: inst,
allSessionsRevokedTimeMs: userInfo.allSessionRevokeTimeMs,
subscriptionId: subscriptionId !== null && subscriptionId !== void 0 ? subscriptionId : undefined,
subscriptionTier: subscriptionTier !== null && subscriptionTier !== void 0 ? subscriptionTier : undefined,
};
}
catch (err) {
console.error('[AuthController] Error ocurred while validating a connection token', err);
return {
success: false,
errorCode: 'server_error',
errorMessage: 'A server error occurred.',
};
}
});
}
revokeSession(request) {

@@ -624,2 +737,3 @@ return __awaiter(this, void 0, void 0, function* () {

const newSessionSecret = fromByteArray(randomBytes(SESSION_SECRET_BYTE_LENGTH));
const newConnectionSecret = fromByteArray(randomBytes(SESSION_SECRET_BYTE_LENGTH));
const newSession = {

@@ -630,2 +744,3 @@ userId: userId,

secretHash: hashPasswordWithSalt(newSessionSecret, newSessionId),
connectionSecret: newConnectionSecret,
grantedTimeMs: now,

@@ -652,2 +767,3 @@ revokeTimeMs: null,

sessionKey: formatV1SessionKey(userId, newSessionId, newSessionSecret, newSession.expireTimeMs),
connectionKey: formatV1ConnectionKey(userId, newSessionId, newConnectionSecret, newSession.expireTimeMs),
expireTimeMs: newSession.expireTimeMs,

@@ -654,0 +770,0 @@ };

import { AddressType } from './AuthStore';
import { ServerError } from './Errors';
import { ServerError } from '@casual-simulation/aux-common/Errors';
/**

@@ -4,0 +4,0 @@ * Defines an interface for a service that is able to send messages to addresses for login requests.

import { RegexRule } from './Utils';
import { ServerError } from './Errors';
import { ServerError } from '@casual-simulation/aux-common/Errors';
/**

@@ -275,2 +275,6 @@ * Defines an interface that represents an auth store.

/**
* The secret of the token that provides connection access to this session.
*/
connectionSecret: string;
/**
* The unix timestamp in miliseconds that the session was granted at.

@@ -277,0 +281,0 @@ */

@@ -18,3 +18,3 @@ /**

/**
* Parses the given session token into a user ID and session ID, and session secret array.
* Parses the given session key into a user ID and session ID, and session secret array.
* Returns null if the key cannot be parsed.

@@ -41,2 +41,32 @@ * @param key The key to parse.

/**
* Formats the given user ID, session ID, connection secret, and expiration time into a key that is used to generate connection tokens.
* @param userId The ID of the user.
* @param sessionId The ID of the session.
* @param sessionSecret The secret for the connections.
* @param expireTimeMs The unix timestamp that the key expires at.
*/
export declare function formatV1ConnectionKey(userId: string, sessionId: string, connectionSecret: string, expireTimeMs: number): string;
/**
* Parses the given connection key into a user ID and session ID, and connection secret array.
* Returns null if the key cannot be parsed.
* @param key The key to parse.
*/
export declare function parseConnectionKey(key: string | null): [
userId: string,
sessionId: string,
connectionSecret: string,
expireTimeMs: number
];
/**
* Parses a version 1 session key into a user ID, session ID, session secret, and expiration time.
* Returns null if the key cannot be parsed or if it is not a V1 key.
* @param key The key to parse.
*/
export declare function parseV1ConnectionKey(key: string): [
userId: string,
sessionId: string,
connectionSecret: string,
expireTimeMs: number
];
/**
* Formats the given OpenAI Key into a string that is detectable as an OpenAI Key.

@@ -56,2 +86,26 @@ * @param apiKey The API Key that should be formatted.

export declare function parseOpenAiKey(key: string): [key: string];
/**
* Generates a new connection token from the given key, connection ID, and device ID.
*
* Returns null if the key cannot be parsed.
* @param key The connection key that should be used to generate the token.
* @param connectionId The connection ID.
* @param deviceId The device ID.
* @param inst The ID of the instance that the connection is for.
*/
export declare function generateV1ConnectionToken(key: string, connectionId: string, recordName: string, inst: string): string;
/**
* Calculates the SHA-256 HMAC of the given connection ID, record name, and inst using the given connection secret.
* @param connectionSecret The connection secret.
* @param connectionId The ID of the connection.
* @param recordName The name of the record.
* @param inst The inst.
*/
export declare function v1ConnectionTokenHmac(connectionSecret: string, connectionId: string, recordName: string, inst: string): string;
/**
* Validates whether the given connection token is valid and was generated from the given connection key.
* @param connectionToken The connection token to validate.
* @param connectionSecret The secret for the connection.
*/
export declare function verifyConnectionToken(connectionToken: string, connectionSecret: string): boolean;
//# sourceMappingURL=AuthUtils.d.ts.map
import { padStart } from 'lodash';
import { randomBytes } from 'tweetnacl';
import { fromBase64String, toBase64String } from './Utils';
import { fromBase64String, toBase64String, parseV1ConnectionToken, formatV1ConnectionToken, } from '@casual-simulation/aux-common';
import { sha256, hmac } from 'hash.js';
import { toByteArray } from 'base64-js';
/**

@@ -28,3 +30,3 @@ * The number of characters that random codes should contain.

/**
* Parses the given session token into a user ID and session ID, and session secret array.
* Parses the given session key into a user ID and session ID, and session secret array.
* Returns null if the key cannot be parsed.

@@ -88,2 +90,71 @@ * @param key The key to parse.

/**
* Formats the given user ID, session ID, connection secret, and expiration time into a key that is used to generate connection tokens.
* @param userId The ID of the user.
* @param sessionId The ID of the session.
* @param sessionSecret The secret for the connections.
* @param expireTimeMs The unix timestamp that the key expires at.
*/
export function formatV1ConnectionKey(userId, sessionId, connectionSecret, expireTimeMs) {
return `vCK1.${toBase64String(userId)}.${toBase64String(sessionId)}.${toBase64String(connectionSecret)}.${toBase64String(expireTimeMs.toString())}`;
}
/**
* Parses the given connection key into a user ID and session ID, and connection secret array.
* Returns null if the key cannot be parsed.
* @param key The key to parse.
*/
export function parseConnectionKey(key) {
return parseV1ConnectionKey(key);
}
/**
* Parses a version 1 session key into a user ID, session ID, session secret, and expiration time.
* Returns null if the key cannot be parsed or if it is not a V1 key.
* @param key The key to parse.
*/
export function parseV1ConnectionKey(key) {
if (!key) {
return null;
}
if (!key.startsWith('vCK1.')) {
return null;
}
const withoutVersion = key.slice('vCK1.'.length);
let periodAfterUserId = withoutVersion.indexOf('.');
if (periodAfterUserId < 0) {
return null;
}
const userIdBase64 = withoutVersion.slice(0, periodAfterUserId);
const sessionIdPlusPassword = withoutVersion.slice(periodAfterUserId + 1);
if (userIdBase64.length <= 0 || sessionIdPlusPassword.length <= 0) {
return null;
}
const periodAfterSessionId = sessionIdPlusPassword.indexOf('.');
if (periodAfterSessionId < 0) {
return null;
}
const sessionIdBase64 = sessionIdPlusPassword.slice(0, periodAfterSessionId);
const passwordPlusExpireTime = sessionIdPlusPassword.slice(periodAfterSessionId + 1);
if (sessionIdBase64.length <= 0 || passwordPlusExpireTime.length <= 0) {
return null;
}
const periodAfterPassword = passwordPlusExpireTime.indexOf('.');
if (periodAfterPassword < 0) {
return null;
}
const passwordBase64 = passwordPlusExpireTime.slice(0, periodAfterPassword);
const expireTimeBase64 = passwordPlusExpireTime.slice(periodAfterPassword + 1);
if (passwordBase64.length <= 0 || expireTimeBase64.length <= 0) {
return null;
}
try {
const userId = fromBase64String(userIdBase64);
const sessionId = fromBase64String(sessionIdBase64);
const password = fromBase64String(passwordBase64);
const expireTime = parseInt(fromBase64String(expireTimeBase64));
return [userId, sessionId, password, expireTime];
}
catch (err) {
return null;
}
}
/**
* Formats the given OpenAI Key into a string that is detectable as an OpenAI Key.

@@ -116,2 +187,59 @@ * @param apiKey The API Key that should be formatted.

}
/**
* Generates a new connection token from the given key, connection ID, and device ID.
*
* Returns null if the key cannot be parsed.
* @param key The connection key that should be used to generate the token.
* @param connectionId The connection ID.
* @param deviceId The device ID.
* @param inst The ID of the instance that the connection is for.
*/
export function generateV1ConnectionToken(key, connectionId, recordName, inst) {
const parsed = parseConnectionKey(key);
if (!parsed) {
return null;
}
const [userId, sessionId, connectionSecret, expireTimeMs] = parsed;
const hashHex = v1ConnectionTokenHmac(connectionSecret, connectionId, recordName, inst);
return formatV1ConnectionToken(userId, sessionId, connectionId, recordName, inst, hashHex);
}
/**
* Calculates the SHA-256 HMAC of the given connection ID, record name, and inst using the given connection secret.
* @param connectionSecret The connection secret.
* @param connectionId The ID of the connection.
* @param recordName The name of the record.
* @param inst The inst.
*/
export function v1ConnectionTokenHmac(connectionSecret, connectionId, recordName, inst) {
const hash = hmac(sha256, toByteArray(connectionSecret), 'hex');
hash.update(connectionId);
hash.update(recordName);
hash.update(inst);
const hashHex = hash.digest('hex');
return hashHex;
}
/**
* Validates whether the given connection token is valid and was generated from the given connection key.
* @param connectionToken The connection token to validate.
* @param connectionSecret The secret for the connection.
*/
export function verifyConnectionToken(connectionToken, connectionSecret) {
if (!connectionToken || !connectionSecret) {
return false;
}
try {
const parsed = parseV1ConnectionToken(connectionToken);
if (parsed) {
const [userId, sessionId, connectionId, recordName, inst, hash] = parsed;
const expectedHash = v1ConnectionTokenHmac(connectionSecret, connectionId, recordName, inst);
return hash === expectedHash;
}
else {
return false;
}
}
catch (_a) {
return false;
}
}
//# sourceMappingURL=AuthUtils.js.map

@@ -1,2 +0,2 @@

import { NotAuthorizedError, NotLoggedInError, ServerError, SubscriptionLimitReached } from './Errors';
import { NotAuthorizedError, NotLoggedInError, ServerError, SubscriptionLimitReached } from '@casual-simulation/aux-common/Errors';
import { DataRecordsStore, EraseDataStoreResult, GetDataStoreResult, SetDataResult, UserPolicy, ListDataStoreFailure } from './DataRecordsStore';

@@ -3,0 +3,0 @@ import { ValidatePublicRecordKeyFailure } from './RecordsController';

@@ -1,2 +0,2 @@

import { ServerError } from './Errors';
import { ServerError } from '@casual-simulation/aux-common/Errors';
/**

@@ -3,0 +3,0 @@ * Defines an interface for objects that can store data records.

import { AuthorizeDenied, PolicyController } from './PolicyController';
import { NotLoggedInError, NotSupportedError, ServerError } from './Errors';
import { NotLoggedInError, NotSupportedError, ServerError } from '@casual-simulation/aux-common/Errors';
import { EventRecordsStore, AddEventCountStoreFailure, GetEventCountStoreFailure } from './EventRecordsStore';

@@ -4,0 +4,0 @@ import { ValidatePublicRecordKeyFailure } from './RecordsController';

@@ -1,2 +0,2 @@

import { ServerError } from './Errors';
import { ServerError } from '@casual-simulation/aux-common/Errors';
/**

@@ -3,0 +3,0 @@ * Defines an interface for objects that can store event records.

import { FileRecordsStore, AddFileFailure, MarkFileRecordAsUploadedFailure, EraseFileStoreResult, GetFileNameFromUrlResult, PresignFileReadFailure, GetFileRecordFailure } from './FileRecordsStore';
import { NotLoggedInError, NotSupportedError, ServerError, SubscriptionLimitReached } from './Errors';
import { NotLoggedInError, NotSupportedError, ServerError, SubscriptionLimitReached } from '@casual-simulation/aux-common/Errors';
import { ValidatePublicRecordKeyFailure } from './RecordsController';

@@ -4,0 +4,0 @@ import { AuthorizeDenied, PolicyController } from './PolicyController';

@@ -1,2 +0,2 @@

import { ServerError } from './Errors';
import { NotSupportedError, ServerError } from '@casual-simulation/aux-common/Errors';
/**

@@ -288,3 +288,3 @@ * Defines an interface for systems that are able to store info about file records.

success: false;
errorCode: ServerError;
errorCode: ServerError | NotSupportedError;
errorMessage: string;

@@ -291,0 +291,0 @@ }

@@ -13,3 +13,3 @@ export * from './AuthController';

export * from './LivekitEvents';
export * from './RecordsHttpServer';
export * from './RecordsServer';
export * from './SubscriptionController';

@@ -34,2 +34,3 @@ export * from './StripeInterface';

export * from './MemoryFileRecordsLookup';
export * from './websockets';
//# sourceMappingURL=index.d.ts.map

@@ -13,3 +13,3 @@ export * from './AuthController';

export * from './LivekitEvents';
export * from './RecordsHttpServer';
export * from './RecordsServer';
export * from './SubscriptionController';

@@ -34,2 +34,3 @@ export * from './StripeInterface';

export * from './MemoryFileRecordsLookup';
export * from './websockets';
//# sourceMappingURL=index.js.map

@@ -1,2 +0,2 @@

import { ServerError } from './Errors';
import { ServerError } from '@casual-simulation/aux-common/Errors';
export type IssueMeetTokenResult = IssueMeetTokenSuccess | IssueMeetTokenFailure;

@@ -3,0 +3,0 @@ /**

@@ -27,3 +27,3 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

totalHits: state.count,
resetTime: new Date(state.resetTimeMs),
resetTimeMs: state.resetTimeMs,
};

@@ -30,0 +30,0 @@ });

import { RegexRule } from './Utils';
import { AddressType, AuthInvoice, AuthLoginRequest, AuthSession, AuthStore, AuthSubscription, AuthSubscriptionPeriod, AuthUser, ListSessionsDataResult, SaveNewUserResult, UpdateSubscriptionInfoRequest, UpdateSubscriptionPeriodRequest } from './AuthStore';
import { ListStudioAssignmentFilters, ListedStudioAssignment, ListedUserAssignment, RecordsStore, Studio, Record, RecordKey, StudioAssignment, CountRecordsFilter, ListedRecord, ListedStudio } from './RecordsStore';
import { ListStudioAssignmentFilters, ListedStudioAssignment, ListedUserAssignment, RecordsStore, Studio, Record, RecordKey, StudioAssignment, CountRecordsFilter, ListedRecord, StoreListedStudio } from './RecordsStore';
import { DataRecordsStore, EraseDataStoreResult, GetDataStoreResult, ListDataStoreResult, SetDataResult, UserPolicy } from './DataRecordsStore';

@@ -86,3 +86,3 @@ import { AddFileResult, EraseFileStoreResult, FileRecordsStore, GetFileNameFromUrlResult, GetFileRecordResult, ListFilesStoreResult, MarkFileRecordAsUploadedResult, PresignFileReadRequest, PresignFileReadResult, PresignFileUploadRequest, PresignFileUploadResult, UpdateFileResult } from './FileRecordsStore';

getStudioByStripeCustomerId(customerId: string): Promise<Studio>;
listStudiosForUser(userId: string): Promise<ListedStudio[]>;
listStudiosForUser(userId: string): Promise<StoreListedStudio[]>;
addStudioAssignment(assignment: StudioAssignment): Promise<void>;

@@ -89,0 +89,0 @@ removeStudioAssignment(studioId: string, userId: string): Promise<void>;

@@ -209,2 +209,4 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

isPrimaryContact: s.isPrimaryContact,
subscriptionId: s.subscriptionId,
subscriptionStatus: s.subscriptionStatus,
}));

@@ -211,0 +213,0 @@ });

{
"name": "@casual-simulation/aux-records",
"version": "3.2.6",
"version": "3.2.7-alpha.6226622763",
"description": "Helpers and managers used by the CasualOS records system.",

@@ -40,5 +40,8 @@ "keywords": [],

"dependencies": {
"@casual-simulation/aux-common": "^3.2.7-alpha.6226622763",
"@casual-simulation/crypto": "^3.2.0",
"@casual-simulation/rate-limit-redis": "^3.1.29",
"@casual-simulation/rate-limit-redis": "^3.2.7-alpha.6226622763",
"@casual-simulation/timesync": "^3.1.28",
"axios": "0.25.0",
"hash.js": "1.1.7",
"livekit-server-sdk": "1.0.2",

@@ -48,3 +51,3 @@ "tweetnacl": "1.0.3",

},
"gitHead": "bfc299cdeafa6f67e821228c8b0af5ef1f83963d"
"gitHead": "90c8d333924255b93b9654dc100fc74181b6138b"
}
import { AuthController } from './AuthController';
import { RecordsController, ValidatePublicRecordKeyFailure, ValidatePublicRecordKeyResult } from './RecordsController';
import { NotSupportedError, ServerError, SubscriptionLimitReached } from './Errors';
import { NotSupportedError, ServerError, SubscriptionLimitReached } from '@casual-simulation/aux-common/Errors';
import { AvailablePermissions, PolicyDocument } from './PolicyPermissions';

@@ -5,0 +5,0 @@ import { ListedStudioAssignment, PublicRecordKeyPolicy } from './RecordsStore';

@@ -11,3 +11,3 @@ import { z } from 'zod';

*/
export type AvailablePermissions = CreateDataPermission | ReadDataPermission | UpdateDataPermission | DeleteDataPermission | ListDataPermission | CreateFilePermission | ReadFilePermission | ListFilePermission | UpdateFilePermission | DeleteFilePermission | IncrementEventPermission | CountEventPermission | UpdateEventPermission | ListEventPermission | ReadPolicyPermission | GrantPermissionToPolicyPermission | RevokePermissionFromPolicyPermission | ListPoliciesPermission | AssignPolicyPermission | UnassignPolicyPermission | GrantRolePermission | RevokeRolePermission | ReadRolePermission | ListRolesPermission | UpdateRolePermission | CreateRecordKeyPermission;
export type AvailablePermissions = CreateDataPermission | ReadDataPermission | UpdateDataPermission | DeleteDataPermission | ListDataPermission | CreateFilePermission | ReadFilePermission | ListFilePermission | UpdateFilePermission | DeleteFilePermission | IncrementEventPermission | CountEventPermission | UpdateEventPermission | ListEventPermission | ReadPolicyPermission | GrantPermissionToPolicyPermission | RevokePermissionFromPolicyPermission | ListPoliciesPermission | AssignPolicyPermission | UnassignPolicyPermission | GrantRolePermission | RevokeRolePermission | ReadRolePermission | ListRolesPermission | UpdateRolePermission | AvailableInstPermissions | CreateRecordKeyPermission;
export type AvailableDataPermissions = CreateDataPermission | ReadDataPermission | UpdateDataPermission | DeleteDataPermission | ListDataPermission;

@@ -18,2 +18,3 @@ export type AvailableFilePermissions = CreateFilePermission | ReadFilePermission | ListFilePermission | UpdateFilePermission | DeleteFilePermission;

export type AvailableRolePermissions = GrantRolePermission | RevokeRolePermission | ListRolesPermission | ReadRolePermission | UpdateRolePermission;
export type AvailableInstPermissions = CreateInstPermission | ReadInstPermission | DeleteInstPermission | UpdateInstPermission | UpdateDataInstPermission | ListInstPermission;
/**

@@ -747,2 +748,135 @@ * Defines an interface that describes common options for all permissions.

}>;
export interface InstPermission extends Permission {
/**
* The insts that this permission allows access to.
*
* If true, then all insts are allowed.
* If a string, then it should be a Regular Expression that matches only insts that are allowed to be manipulated.
*/
insts: string | true;
}
export declare const INST_VALIDATION: z.ZodObject<{
role: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
insts: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
}, "strip", z.ZodTypeAny, {
role?: string | true;
insts?: string | true;
}, {
role?: string | true;
insts?: string | true;
}>;
/**
* Defines an interface that describes a permission to create an inst.
*/
export interface CreateInstPermission extends InstPermission {
type: 'inst.create';
}
export declare const CREATE_INST_VALIDATION: z.ZodObject<{
role: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
insts: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
type: z.ZodLiteral<"inst.create">;
}, "strip", z.ZodTypeAny, {
role?: string | true;
insts?: string | true;
type?: "inst.create";
}, {
role?: string | true;
insts?: string | true;
type?: "inst.create";
}>;
/**
* Defines an interface that describes a permission to read data from an inst.
*/
export interface ReadInstPermission extends InstPermission {
type: 'inst.read';
}
export declare const READ_INST_VALIDATION: z.ZodObject<{
role: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
insts: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
type: z.ZodLiteral<"inst.read">;
}, "strip", z.ZodTypeAny, {
role?: string | true;
insts?: string | true;
type?: "inst.read";
}, {
role?: string | true;
insts?: string | true;
type?: "inst.read";
}>;
/**
* Defines an interface that describes a permission to update an inst.
*/
export interface UpdateInstPermission extends InstPermission {
type: 'inst.update';
}
export declare const UPDATE_INST_VALIDATION: z.ZodObject<{
role: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
insts: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
type: z.ZodLiteral<"inst.update">;
}, "strip", z.ZodTypeAny, {
role?: string | true;
insts?: string | true;
type?: "inst.update";
}, {
role?: string | true;
insts?: string | true;
type?: "inst.update";
}>;
/**
* Defines an interface that describes a permission to update data in an inst.
*/
export interface UpdateDataInstPermission extends InstPermission {
type: 'inst.updateData';
}
export declare const UPDATE_DATA_INST_VALIDATION: z.ZodObject<{
role: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
insts: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
type: z.ZodLiteral<"inst.updateData">;
}, "strip", z.ZodTypeAny, {
role?: string | true;
insts?: string | true;
type?: "inst.updateData";
}, {
role?: string | true;
insts?: string | true;
type?: "inst.updateData";
}>;
/**
* Defines an interface that describes a permission to delete an inst.
*/
export interface DeleteInstPermission extends InstPermission {
type: 'inst.delete';
}
export declare const DELETE_INST_VALIDATION: z.ZodObject<{
role: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
insts: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
type: z.ZodLiteral<"inst.delete">;
}, "strip", z.ZodTypeAny, {
role?: string | true;
insts?: string | true;
type?: "inst.delete";
}, {
role?: string | true;
insts?: string | true;
type?: "inst.delete";
}>;
/**
* Defines an interface that describes a permission to list insts.
*/
export interface ListInstPermission extends InstPermission {
type: 'inst.list';
}
export declare const LIST_INST_VALIDATION: z.ZodObject<{
role: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
insts: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
type: z.ZodLiteral<"inst.list">;
}, "strip", z.ZodTypeAny, {
role?: string | true;
insts?: string | true;
type?: "inst.list";
}, {
role?: string | true;
insts?: string | true;
type?: "inst.list";
}>;
export declare const AVAILABLE_PERMISSIONS_VALIDATION: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{

@@ -1042,2 +1176,74 @@ role: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;

type?: "role.list";
}>, z.ZodObject<{
role: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
insts: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
type: z.ZodLiteral<"inst.create">;
}, "strip", z.ZodTypeAny, {
role?: string | true;
insts?: string | true;
type?: "inst.create";
}, {
role?: string | true;
insts?: string | true;
type?: "inst.create";
}>, z.ZodObject<{
role: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
insts: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
type: z.ZodLiteral<"inst.read">;
}, "strip", z.ZodTypeAny, {
role?: string | true;
insts?: string | true;
type?: "inst.read";
}, {
role?: string | true;
insts?: string | true;
type?: "inst.read";
}>, z.ZodObject<{
role: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
insts: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
type: z.ZodLiteral<"inst.update">;
}, "strip", z.ZodTypeAny, {
role?: string | true;
insts?: string | true;
type?: "inst.update";
}, {
role?: string | true;
insts?: string | true;
type?: "inst.update";
}>, z.ZodObject<{
role: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
insts: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
type: z.ZodLiteral<"inst.updateData">;
}, "strip", z.ZodTypeAny, {
role?: string | true;
insts?: string | true;
type?: "inst.updateData";
}, {
role?: string | true;
insts?: string | true;
type?: "inst.updateData";
}>, z.ZodObject<{
role: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
insts: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
type: z.ZodLiteral<"inst.delete">;
}, "strip", z.ZodTypeAny, {
role?: string | true;
insts?: string | true;
type?: "inst.delete";
}, {
role?: string | true;
insts?: string | true;
type?: "inst.delete";
}>, z.ZodObject<{
role: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
insts: z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>;
type: z.ZodLiteral<"inst.list">;
}, "strip", z.ZodTypeAny, {
role?: string | true;
insts?: string | true;
type?: "inst.list";
}, {
role?: string | true;
insts?: string | true;
type?: "inst.list";
}>]>;

@@ -1086,2 +1292,7 @@ /**

/**
* The name of the "publicWrite" resource marker.
* Used by default for public insts.
*/
export declare const PUBLIC_WRITE_MARKER = "publicWrite";
/**
* The name of the "account" resource marker.

@@ -1088,0 +1299,0 @@ * Used by default for policy and role records.

@@ -103,2 +103,23 @@ import { z } from 'zod';

});
export const INST_VALIDATION = PERMISSION_VALIDATION.extend({
insts: z.union([z.literal(true), z.string()]),
});
export const CREATE_INST_VALIDATION = INST_VALIDATION.extend({
type: z.literal('inst.create'),
});
export const READ_INST_VALIDATION = INST_VALIDATION.extend({
type: z.literal('inst.read'),
});
export const UPDATE_INST_VALIDATION = INST_VALIDATION.extend({
type: z.literal('inst.update'),
});
export const UPDATE_DATA_INST_VALIDATION = INST_VALIDATION.extend({
type: z.literal('inst.updateData'),
});
export const DELETE_INST_VALIDATION = INST_VALIDATION.extend({
type: z.literal('inst.delete'),
});
export const LIST_INST_VALIDATION = INST_VALIDATION.extend({
type: z.literal('inst.list'),
});
export const AVAILABLE_PERMISSIONS_VALIDATION = z.discriminatedUnion('type', [

@@ -127,2 +148,8 @@ CREATE_DATA_VALIDATION,

LIST_ROLES_VALIDATION,
CREATE_INST_VALIDATION,
READ_INST_VALIDATION,
UPDATE_INST_VALIDATION,
UPDATE_DATA_INST_VALIDATION,
DELETE_INST_VALIDATION,
LIST_INST_VALIDATION,
]);

@@ -143,2 +170,7 @@ /**

/**
* The name of the "publicWrite" resource marker.
* Used by default for public insts.
*/
export const PUBLIC_WRITE_MARKER = 'publicWrite';
/**
* The name of the "account" resource marker.

@@ -278,2 +310,32 @@ * Used by default for policy and role records.

},
{
type: 'inst.create',
role: ADMIN_ROLE_NAME,
insts: true,
},
{
type: 'inst.read',
role: ADMIN_ROLE_NAME,
insts: true,
},
{
type: 'inst.delete',
role: ADMIN_ROLE_NAME,
insts: true,
},
{
type: 'inst.update',
role: ADMIN_ROLE_NAME,
insts: true,
},
{
type: 'inst.updateData',
role: ADMIN_ROLE_NAME,
insts: true,
},
{
type: 'inst.list',
role: ADMIN_ROLE_NAME,
insts: true,
},
// Record Owner Permissions

@@ -311,4 +373,9 @@ {

},
{
type: 'inst.read',
role: true,
insts: true,
},
],
};
//# sourceMappingURL=PolicyPermissions.js.map

@@ -1,2 +0,2 @@

import { ServerError } from './Errors';
import { ServerError } from '@casual-simulation/aux-common/Errors';
import { PolicyDocument } from './PolicyPermissions';

@@ -3,0 +3,0 @@ /**

import { RateLimiter } from '@casual-simulation/rate-limit-redis';
import { ServerError } from './Errors';
import { ServerError } from '@casual-simulation/aux-common/Errors';
/**

@@ -31,3 +31,5 @@ * Defines a controller that is able to handle rate limiting.

errorMessage: string;
retryAfterSeconds?: number;
totalHits?: number;
}
//# sourceMappingURL=RateLimitController.d.ts.map

@@ -36,2 +36,4 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

errorMessage: 'Rate limit exceeded.',
retryAfterSeconds: (hits.resetTimeMs - Date.now()) / 1000,
totalHits: hits.totalHits,
};

@@ -38,0 +40,0 @@ }

@@ -1,3 +0,3 @@

import { ListedRecord, ListedStudio, ListedStudioAssignment, PublicRecordKeyPolicy, RecordsStore, StudioAssignmentRole } from './RecordsStore';
import { NotAuthorizedError, NotLoggedInError, NotSupportedError, ServerError, SubscriptionLimitReached } from './Errors';
import { ListedRecord, ListedStudioAssignment, PublicRecordKeyPolicy, RecordsStore, StudioAssignmentRole } from './RecordsStore';
import { NotAuthorizedError, NotLoggedInError, NotSupportedError, ServerError, SubscriptionLimitReached } from '@casual-simulation/aux-common/Errors';
import type { ValidateSessionKeyFailure } from './AuthController';

@@ -314,2 +314,30 @@ import { AuthStore } from './AuthStore';

}
/**
* Defines an interface that represents a studio that has been listed.
*
* @dochash types/records/studios
* @docname ListedStudio
*/
export interface ListedStudio {
/**
* The ID of the studio.
*/
studioId: string;
/**
* The name of the studio.
*/
displayName: string;
/**
* The role that the user has in the studio.
*/
role: StudioAssignmentRole;
/**
* Whether the user is the primary contact for this studio.
*/
isPrimaryContact: boolean;
/**
* The tier of the studio's subscription.
*/
subscriptionTier: string;
}
export type ListStudioMembersResult = ListStudioMembersSuccess | ListStudioMembersFailure;

@@ -316,0 +344,0 @@ export interface ListStudioMembersSuccess {

@@ -10,3 +10,3 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

};
import { toBase64String, fromBase64String } from './Utils';
import { toBase64String, fromBase64String, } from '@casual-simulation/aux-common';
import { hashHighEntropyPasswordWithSalt, hashPasswordWithSalt, } from '@casual-simulation/crypto';

@@ -16,3 +16,3 @@ import { randomBytes } from 'tweetnacl';

import { v4 as uuid } from 'uuid';
import { getSubscriptionFeatures } from './SubscriptionConfiguration';
import { getSubscriptionFeatures, getSubscriptionTier, } from './SubscriptionConfiguration';
/**

@@ -670,10 +670,14 @@ * Defines a class that manages records and their keys.

const studios = yield this._store.listStudiosForUser(userId);
const config = yield this._config.getSubscriptionConfiguration();
return {
success: true,
studios: studios.map((s) => ({
studioId: s.studioId,
displayName: s.displayName,
role: s.role,
isPrimaryContact: s.isPrimaryContact,
})),
studios: studios.map((s) => {
return {
studioId: s.studioId,
displayName: s.displayName,
role: s.role,
isPrimaryContact: s.isPrimaryContact,
subscriptionTier: getSubscriptionTier(config, s.subscriptionStatus, s.subscriptionId),
};
}),
};

@@ -680,0 +684,0 @@ }

@@ -86,3 +86,3 @@ /**

*/
listStudiosForUser(userId: string): Promise<ListedStudio[]>;
listStudiosForUser(userId: string): Promise<StoreListedStudio[]>;
/**

@@ -198,3 +198,4 @@ * Adds the given studio assignment to the store.

/**
* The ID of the stripe subscription that this studio currently has.
* The ID of the purchasable subscription that the user has.
* Note that this is the ID of the subscription in the config, not the ID of the stripe subscription.
*/

@@ -310,7 +311,4 @@ subscriptionId?: string;

* Defines an interface that represents a studio that a user has access to.
*
* @dochash types/records/studios
* @docname ListedStudio
*/
export interface ListedStudio {
export interface StoreListedStudio {
/**

@@ -332,2 +330,10 @@ * The ID of the studio.

isPrimaryContact: boolean;
/**
* The ID of the studio's subscription.
*/
subscriptionId: string;
/**
* The current subscription status for this studio.
*/
subscriptionStatus: string;
}

@@ -334,0 +340,0 @@ export interface ListStudioAssignmentFilters {

@@ -42,5 +42,13 @@ import { z } from 'zod';

allowed: z.boolean(),
maxSquarePixelsPerPeriod: z.number().int().positive().optional(),
maxSkyboxesPerPeriod: z.number().int().positive().optional(),
}),
}),
insts: z
.object({
allowed: z.boolean(),
maxInsts: z.number().int().positive().optional(),
maxBytesPerInst: z.number().int().positive().optional(),
maxActiveConnectionsPerInst: z.number().int().positive().optional(),
})
.optional(),
});

@@ -84,2 +92,13 @@ export const subscriptionConfigSchema = z.object({

}),
tempInsts: z
.object({
allowed: z.boolean(),
maxBytesPerInst: z.number().int().positive().optional(),
maxActiveConnectionsPerInst: z
.number()
.int()
.positive()
.optional(),
})
.optional(),
})

@@ -125,2 +144,5 @@ .optional(),

},
insts: {
allowed: true,
},
};

@@ -143,2 +165,13 @@ }

}
export function getSubscriptionTier(config, subscriptionStatus, subId) {
var _a;
if (!config) {
return null;
}
if (!isActiveSubscription(subscriptionStatus)) {
return null;
}
const sub = config.subscriptions.find((s) => s.id === subId);
return (_a = sub === null || sub === void 0 ? void 0 : sub.tier) !== null && _a !== void 0 ? _a : null;
}
//# sourceMappingURL=SubscriptionConfiguration.js.map
import { AuthController, ValidateSessionKeyFailure } from './AuthController';
import { AuthStore } from './AuthStore';
import { StripeInterface } from './StripeInterface';
import { ServerError } from './Errors';
import { ServerError } from '@casual-simulation/aux-common/Errors';
import { SubscriptionConfiguration } from './SubscriptionConfiguration';

@@ -6,0 +6,0 @@ import { RecordsStore } from './RecordsStore';

@@ -25,2 +25,4 @@ import { AuthController } from './AuthController';

sessionKey: string;
connectionKey: string;
sessionId: string;
}>;

@@ -27,0 +29,0 @@ export declare function createTestRecordKey({ records }: TestServices, userId: string, recordName?: string, policy?: PublicRecordKeyPolicy): Promise<{

@@ -16,2 +16,3 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

import { MemoryStore } from './MemoryStore';
import { parseSessionKey } from './AuthUtils';
export function createTestSubConfiguration() {

@@ -82,2 +83,4 @@ return {

const sessionKey = loginResult.sessionKey;
const connectionKey = loginResult.connectionKey;
const [_, sessionId] = parseSessionKey(sessionKey);
return {

@@ -87,2 +90,4 @@ emailAddress,

sessionKey,
connectionKey,
sessionId,
};

@@ -89,0 +94,0 @@ });

/**
* Converts the given string into a base64 string.
* @param str The string to convert.
*/
export declare function toBase64String(str: string): string;
/**
* Converts the given string from a base64 string.
* @param base64
*/
export declare function fromBase64String(base64: string): string;
/**
* Signs the given request and adds the related headers to it.

@@ -13,0 +3,0 @@ * @param request The request to sign.

@@ -1,2 +0,1 @@

import { fromByteArray, toByteArray } from 'base64-js';
import { omitBy, padStart, sortBy } from 'lodash';

@@ -7,20 +6,2 @@ import { sha256, hmac } from 'hash.js';

/**
* Converts the given string into a base64 string.
* @param str The string to convert.
*/
export function toBase64String(str) {
const encoder = new TextEncoder();
const array = encoder.encode(str);
return fromByteArray(array);
}
/**
* Converts the given string from a base64 string.
* @param base64
*/
export function fromBase64String(base64) {
const decoder = new TextDecoder();
const array = toByteArray(base64);
return decoder.decode(array);
}
/**
* Signs the given request and adds the related headers to it.

@@ -27,0 +8,0 @@ * @param request The request to sign.

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc