firebase-functions
Version: 
Firebase SDK for Cloud Functions
245 lines (244 loc) • 8.77 kB
TypeScript
/// <reference types="node" />
import * as express from "express";
import { DecodedAppCheckToken } from "firebase-admin/app-check";
import { DecodedIdToken } from "firebase-admin/auth";
import { TaskContext } from "./tasks";
/** An express request with the wire format representation of the request body. */
export interface Request extends express.Request {
    /** The wire format representation of the request body. */
    rawBody: Buffer;
}
/**
 * The interface for AppCheck tokens verified in Callable functions
 */
export interface AppCheckData {
    /**
     * The app ID of a Firebase App attested by the App Check token.
     */
    appId: string;
    /**
     * Decoded App Check token.
     */
    token: DecodedAppCheckToken;
    /**
     * Indicates if the token has been consumed.
     *
     * @remarks
     * `false` value indicates that this is the first time the App Check service has seen this token and marked the
     * token as consumed for future use of the token.
     *
     * `true` value indicates the token has previously been marked as consumed by the App Check service. In this case,
     *  consider taking extra precautions, such as rejecting the request or requiring additional security checks.
     */
    alreadyConsumed?: boolean;
}
/**
 * The interface for Auth tokens verified in Callable functions
 */
export interface AuthData {
    /** The user's uid from the request's ID token. */
    uid: string;
    /** The decoded claims of the ID token after verification. */
    token: DecodedIdToken;
    /** The raw ID token as parsed from the header. */
    rawToken: string;
}
/**
 * The interface for metadata for the API as passed to the handler.
 */
export interface CallableContext {
    /**
     * The result of decoding and verifying a Firebase AppCheck token.
     */
    app?: AppCheckData;
    /**
     * The result of decoding and verifying a Firebase Auth ID token.
     */
    auth?: AuthData;
    /**
     * An unverified token for a Firebase Instance ID.
     */
    instanceIdToken?: string;
    /**
     * The raw request handled by the callable.
     */
    rawRequest: Request;
}
/**
 * The request used to call a callable function.
 */
export interface CallableRequest<T = any> {
    /**
     * The parameters used by a client when calling this function.
     */
    data: T;
    /**
     * The result of decoding and verifying a Firebase App Check token.
     */
    app?: AppCheckData;
    /**
     * The result of decoding and verifying a Firebase Auth ID token.
     */
    auth?: AuthData;
    /**
     * An unverified token for a Firebase Instance ID.
     */
    instanceIdToken?: string;
    /**
     * The raw request handled by the callable.
     */
    rawRequest: Request;
    /**
     * Whether this is a streaming request.
     * Code can be optimized by not trying to generate a stream of chunks to
     * call `response.sendChunk` if `request.acceptsStreaming` is false.
     * It is always safe, however, to call `response.sendChunk` as this will
     * noop if `acceptsStreaming` is false.
     */
    acceptsStreaming: boolean;
}
/**
 * `CallableProxyResponse` allows streaming response chunks and listening to signals
 * triggered in events such as a disconnect.
 */
export interface CallableResponse<T = unknown> {
    /**
     * Writes a chunk of the response body to the client. This method can be called
     * multiple times to stream data progressively.
     * Returns a promise of whether the data was written. This can be false, for example,
     * if the request was not a streaming request. Rejects if there is a network error.
     */
    sendChunk: (chunk: T) => Promise<boolean>;
    /**
     * An `AbortSignal` that is triggered when the client disconnects or the
     * request is terminated prematurely.
     */
    signal: AbortSignal;
}
/**
 * The set of Firebase Functions status codes. The codes are the same at the
 * ones exposed by {@link https://github.com/grpc/grpc/blob/master/doc/statuscodes.md | gRPC}.
 *
 * @remarks
 * Possible values:
 *
 * - `cancelled`: The operation was cancelled (typically by the caller).
 *
 * - `unknown`: Unknown error or an error from a different error domain.
 *
 * - `invalid-argument`: Client specified an invalid argument. Note that this
 *   differs from `failed-precondition`. `invalid-argument` indicates
 *   arguments that are problematic regardless of the state of the system
 *   (e.g. an invalid field name).
 *
 * - `deadline-exceeded`: Deadline expired before operation could complete.
 *   For operations that change the state of the system, this error may be
 *   returned even if the operation has completed successfully. For example,
 *   a successful response from a server could have been delayed long enough
 *   for the deadline to expire.
 *
 * - `not-found`: Some requested document was not found.
 *
 * - `already-exists`: Some document that we attempted to create already
 *   exists.
 *
 * - `permission-denied`: The caller does not have permission to execute the
 *   specified operation.
 *
 * - `resource-exhausted`: Some resource has been exhausted, perhaps a
 *   per-user quota, or perhaps the entire file system is out of space.
 *
 * - `failed-precondition`: Operation was rejected because the system is not
 *   in a state required for the operation's execution.
 *
 * - `aborted`: The operation was aborted, typically due to a concurrency
 *   issue like transaction aborts, etc.
 *
 * - `out-of-range`: Operation was attempted past the valid range.
 *
 * - `unimplemented`: Operation is not implemented or not supported/enabled.
 *
 * - `internal`: Internal errors. Means some invariants expected by
 *   underlying system has been broken. If you see one of these errors,
 *   something is very broken.
 *
 * - `unavailable`: The service is currently unavailable. This is most likely
 *   a transient condition and may be corrected by retrying with a backoff.
 *
 * - `data-loss`: Unrecoverable data loss or corruption.
 *
 * - `unauthenticated`: The request does not have valid authentication
 *   credentials for the operation.
 */
export type FunctionsErrorCode = "ok" | "cancelled" | "unknown" | "invalid-argument" | "deadline-exceeded" | "not-found" | "already-exists" | "permission-denied" | "resource-exhausted" | "failed-precondition" | "aborted" | "out-of-range" | "unimplemented" | "internal" | "unavailable" | "data-loss" | "unauthenticated";
/** @hidden */
export type CanonicalErrorCodeName = "OK" | "CANCELLED" | "UNKNOWN" | "INVALID_ARGUMENT" | "DEADLINE_EXCEEDED" | "NOT_FOUND" | "ALREADY_EXISTS" | "PERMISSION_DENIED" | "UNAUTHENTICATED" | "RESOURCE_EXHAUSTED" | "FAILED_PRECONDITION" | "ABORTED" | "OUT_OF_RANGE" | "UNIMPLEMENTED" | "INTERNAL" | "UNAVAILABLE" | "DATA_LOSS";
/** @hidden */
interface HttpErrorCode {
    canonicalName: CanonicalErrorCodeName;
    status: number;
}
/** @hidden */
interface HttpErrorWireFormat {
    details?: unknown;
    message: string;
    status: CanonicalErrorCodeName;
}
/**
 * An explicit error that can be thrown from a handler to send an error to the
 * client that called the function.
 */
export declare class HttpsError extends Error {
    /**
     * A standard error code that will be returned to the client. This also
     * determines the HTTP status code of the response, as defined in code.proto.
     */
    readonly code: FunctionsErrorCode;
    /**
     * Extra data to be converted to JSON and included in the error response.
     */
    readonly details: unknown;
    /**
     * A wire format representation of a provided error code.
     *
     * @hidden
     */
    readonly httpErrorCode: HttpErrorCode;
    constructor(code: FunctionsErrorCode, message: string, details?: unknown);
    /**
     * Returns a JSON-serializable representation of this object.
     */
    toJSON(): HttpErrorWireFormat;
}
/** @hidden */
interface HttpRequest extends Request {
    body: {
        data: any;
    };
}
/** @hidden */
export declare function isValidRequest(req: Request): req is HttpRequest;
/**
 * Encodes arbitrary data in our special format for JSON.
 * This is exposed only for testing.
 */
/** @hidden */
export declare function encode(data: any): any;
/**
 * Decodes our special format for JSON into native types.
 * This is exposed only for testing.
 */
/** @hidden */
export declare function decode(data: any): any;
/**
 * Be careful when changing token status values.
 *
 * Users are encouraged to setup log-based metric based on these values, and
 * changing their values may cause their metrics to break.
 *
 */
/** @hidden */
type TokenStatus = "MISSING" | "VALID" | "INVALID";
/** @interanl */
export declare function checkAuthToken(req: Request, ctx: CallableContext | TaskContext): Promise<TokenStatus>;
export {};