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

@aws-amplify/adapter-nextjs

Package Overview
Dependencies
Maintainers
0
Versions
534
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@aws-amplify/adapter-nextjs - npm Package Compare versions

Comparing version 1.4.4-unstable.289f3e8.0 to 1.4.4-websocket-event.29583bc.0

dist/cjs/auth/constant.js

3

dist/cjs/api/createServerRunnerForAPI.js

@@ -7,3 +7,3 @@ 'use strict';

exports.createServerRunnerForAPI = void 0;
const utils_1 = require("@aws-amplify/core/internals/utils");
const utils_1 = require("aws-amplify/utils");
const utils_2 = require("../utils");

@@ -15,2 +15,3 @@ const createServerRunnerForAPI = ({ config, }) => {

config: amplifyConfig,
globalSettings: utils_2.globalSettings,
}),

@@ -17,0 +18,0 @@ resourcesConfig: amplifyConfig,

@@ -7,6 +7,6 @@ 'use strict';

exports.generateServerClientUsingReqRes = exports.generateServerClientUsingCookies = void 0;
const internals_1 = require("@aws-amplify/api/internals");
const internals_1 = require("aws-amplify/api/internals");
const server_1 = require("aws-amplify/api/server");
const adapter_core_1 = require("@aws-amplify/core/internals/adapter-core");
const utils_1 = require("@aws-amplify/core/internals/utils");
const internals_2 = require("aws-amplify/adapter-core/internals");
const utils_1 = require("aws-amplify/utils");
const createServerRunnerForAPI_1 = require("./createServerRunnerForAPI");

@@ -24,3 +24,3 @@ /**

if (typeof options.cookies !== 'function') {
throw new adapter_core_1.AmplifyServerContextError({
throw new internals_2.AmplifyServerContextError({
message: 'generateServerClientUsingCookies is only compatible with the `cookies` Dynamic Function available in Server Components.',

@@ -37,3 +37,3 @@ // TODO: link to docs

nextServerContext: { cookies: options.cookies },
operation: contextSpec => fn((0, adapter_core_1.getAmplifyServerContext)(contextSpec).amplify),
operation: contextSpec => fn((0, internals_2.getAmplifyServerContext)(contextSpec).amplify),
});

@@ -40,0 +40,0 @@ const { cookies: _cookies, config: _config, ...params } = options;

@@ -7,5 +7,7 @@ 'use strict';

exports.createServerRunner = void 0;
const utils_1 = require("@aws-amplify/core/internals/utils");
const utils_1 = require("aws-amplify/utils");
const utils_2 = require("./utils");
const createTokenValidator_1 = require("./utils/createTokenValidator");
const auth_1 = require("./auth");
const utils_3 = require("./auth/utils");
/**

@@ -29,4 +31,11 @@ * Creates the `runWithAmplifyServerContext` function to run Amplify server side APIs in an isolated request context.

*/
const createServerRunner = ({ config, }) => {
const createServerRunner = ({ config, runtimeOptions, }) => {
const amplifyConfig = (0, utils_1.parseAmplifyConfig)(config);
const amplifyAppOrigin = process.env.AMPLIFY_APP_ORIGIN;
utils_2.globalSettings.setRuntimeOptions(runtimeOptions ?? {});
if ((0, utils_3.isValidOrigin)(amplifyAppOrigin)) {
utils_2.globalSettings.setIsSSLOrigin((0, utils_3.isSSLOrigin)(amplifyAppOrigin));
// update the isServerSideAuthEnabled flag of the globalSettings to true
utils_2.globalSettings.enableServerSideAuth();
}
let tokenValidator;

@@ -40,6 +49,14 @@ if (amplifyConfig?.Auth) {

}
const runWithAmplifyServerContext = (0, utils_2.createRunWithAmplifyServerContext)({
config: amplifyConfig,
tokenValidator,
globalSettings: utils_2.globalSettings,
});
return {
runWithAmplifyServerContext: (0, utils_2.createRunWithAmplifyServerContext)({
runWithAmplifyServerContext,
createAuthRouteHandlers: (0, auth_1.createAuthRouteHandlersFactory)({
config: amplifyConfig,
tokenValidator,
amplifyAppOrigin,
globalSettings: utils_2.globalSettings,
runWithAmplifyServerContext,
}),

@@ -46,0 +63,0 @@ };

@@ -8,5 +8,7 @@ 'use strict';

const server_js_1 = require("next/server.js");
const adapter_core_1 = require("@aws-amplify/core/internals/adapter-core");
const internals_1 = require("aws-amplify/adapter-core/internals");
const utils_1 = require("../auth/utils");
const cookie_1 = require("./cookie");
exports.DATE_IN_THE_PAST = new Date(0);
const createCookieStorageAdapterFromNextServerContext = async (context) => {
const createCookieStorageAdapterFromNextServerContext = async (context, ignoreNonServerSideCookies = false) => {
const { request: req, response: res } = context;

@@ -22,3 +24,3 @@ // When the server context is from `getServerSideProps`, the `req` is an instance

typeof res.setHeader === 'function') {
return createCookieStorageAdapterFromGetServerSidePropsContext(req, res);
return createCookieStorageAdapterFromGetServerSidePropsContext(req, res, ignoreNonServerSideCookies);
}

@@ -34,6 +36,6 @@ const { request, response } = context;

if (response instanceof server_js_1.NextResponse) {
return createCookieStorageAdapterFromNextRequestAndNextResponse(request, response);
return createCookieStorageAdapterFromNextRequestAndNextResponse(request, response, ignoreNonServerSideCookies);
}
else {
return createCookieStorageAdapterFromNextRequestAndHttpResponse(request, response);
return createCookieStorageAdapterFromNextRequestAndHttpResponse(request, response, ignoreNonServerSideCookies);
}

@@ -43,6 +45,6 @@ }

if (typeof cookies === 'function') {
return createCookieStorageAdapterFromNextCookies(cookies);
return createCookieStorageAdapterFromNextCookies(cookies, ignoreNonServerSideCookies);
}
// This should not happen normally.
throw new adapter_core_1.AmplifyServerContextError({
throw new internals_1.AmplifyServerContextError({
message: 'Attempted to create cookie storage adapter from an unsupported Next.js server context.',

@@ -52,3 +54,3 @@ });

exports.createCookieStorageAdapterFromNextServerContext = createCookieStorageAdapterFromNextServerContext;
const createCookieStorageAdapterFromNextRequestAndNextResponse = (request, response) => {
const createCookieStorageAdapterFromNextRequestAndNextResponse = (request, response, ignoreNonServerSideCookies) => {
const readonlyCookieStore = request.cookies;

@@ -58,19 +60,25 @@ const mutableCookieStore = response.cookies;

get(name) {
return readonlyCookieStore.get(ensureEncodedForJSCookie(name));
return readonlyCookieStore.get((0, cookie_1.ensureEncodedForJSCookie)(name));
},
getAll: readonlyCookieStore.getAll.bind(readonlyCookieStore),
set(name, value, options) {
mutableCookieStore.set(ensureEncodedForJSCookie(name), value, options);
if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {
return;
}
mutableCookieStore.set((0, cookie_1.ensureEncodedForJSCookie)(name), value, options);
},
delete(name) {
mutableCookieStore.delete(ensureEncodedForJSCookie(name));
if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {
return;
}
mutableCookieStore.delete((0, cookie_1.ensureEncodedForJSCookie)(name));
},
};
};
const createCookieStorageAdapterFromNextRequestAndHttpResponse = (request, response) => {
const createCookieStorageAdapterFromNextRequestAndHttpResponse = (request, response, ignoreNonServerSideCookies) => {
const readonlyCookieStore = request.cookies;
const mutableCookieStore = createMutableCookieStoreFromHeaders(response.headers);
const mutableCookieStore = createMutableCookieStoreFromHeaders(response.headers, ignoreNonServerSideCookies);
return {
get(name) {
return readonlyCookieStore.get(ensureEncodedForJSCookie(name));
return readonlyCookieStore.get((0, cookie_1.ensureEncodedForJSCookie)(name));
},

@@ -81,3 +89,3 @@ getAll: readonlyCookieStore.getAll.bind(readonlyCookieStore),

};
const createCookieStorageAdapterFromNextCookies = async (cookies) => {
const createCookieStorageAdapterFromNextCookies = async (cookies, ignoreNonServerSideCookies) => {
const cookieStore = await cookies();

@@ -90,4 +98,7 @@ // When Next cookies() is called in a server component, it returns a readonly

const setFunc = (name, value, options) => {
if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {
return;
}
try {
cookieStore.set(ensureEncodedForJSCookie(name), value, options);
cookieStore.set((0, cookie_1.ensureEncodedForJSCookie)(name), value, options);
}

@@ -99,4 +110,7 @@ catch {

const deleteFunc = name => {
if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {
return;
}
try {
cookieStore.delete(ensureEncodedForJSCookie(name));
cookieStore.delete((0, cookie_1.ensureEncodedForJSCookie)(name));
}

@@ -109,3 +123,3 @@ catch {

get(name) {
return cookieStore.get(ensureEncodedForJSCookie(name));
return cookieStore.get((0, cookie_1.ensureEncodedForJSCookie)(name));
},

@@ -117,3 +131,3 @@ getAll: cookieStore.getAll.bind(cookieStore),

};
const createCookieStorageAdapterFromGetServerSidePropsContext = (request, response) => {
const createCookieStorageAdapterFromGetServerSidePropsContext = (request, response, ignoreNonServerSideCookies) => {
const cookiesMap = { ...request.cookies };

@@ -126,3 +140,3 @@ const allCookies = Object.entries(cookiesMap).map(([name, value]) => ({

get(name) {
const value = cookiesMap[ensureEncodedForJSCookie(name)];
const value = cookiesMap[(0, cookie_1.ensureEncodedForJSCookie)(name)];
return value

@@ -139,3 +153,6 @@ ? {

set(name, value, options) {
const encodedName = ensureEncodedForJSCookie(name);
if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {
return;
}
const encodedName = (0, cookie_1.ensureEncodedForJSCookie)(name);
const existingValues = getExistingSetCookieValues(response.getHeader('Set-Cookie'));

@@ -147,6 +164,9 @@ // if the cookies have already been set, we don't need to set them again.

}
response.appendHeader('Set-Cookie', `${encodedName}=${value};${options ? serializeSetCookieOptions(options) : ''}`);
response.appendHeader('Set-Cookie', (0, cookie_1.serializeCookie)(encodedName, value, options));
},
delete(name) {
const encodedName = ensureEncodedForJSCookie(name);
if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {
return;
}
const encodedName = (0, cookie_1.ensureEncodedForJSCookie)(name);
const setCookieValue = `${encodedName}=;Expires=${exports.DATE_IN_THE_PAST.toUTCString()}`;

@@ -163,8 +183,14 @@ const existingValues = getExistingSetCookieValues(response.getHeader('Set-Cookie'));

};
const createMutableCookieStoreFromHeaders = (headers) => {
const createMutableCookieStoreFromHeaders = (headers, ignoreNonServerSideCookies) => {
const setFunc = (name, value, options) => {
headers.append('Set-Cookie', `${ensureEncodedForJSCookie(name)}=${value};${options ? serializeSetCookieOptions(options) : ''}`);
if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {
return;
}
headers.append('Set-Cookie', (0, cookie_1.serializeCookie)((0, cookie_1.ensureEncodedForJSCookie)(name), value, options));
};
const deleteFunc = name => {
headers.append('Set-Cookie', `${ensureEncodedForJSCookie(name)}=;Expires=${exports.DATE_IN_THE_PAST.toUTCString()}`);
if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {
return;
}
headers.append('Set-Cookie', `${(0, cookie_1.ensureEncodedForJSCookie)(name)}=;Expires=${exports.DATE_IN_THE_PAST.toUTCString()}`);
};

@@ -176,33 +202,4 @@ return {

};
const serializeSetCookieOptions = (options) => {
const { expires, domain, httpOnly, sameSite, secure, path } = options;
const serializedOptions = [];
if (domain) {
serializedOptions.push(`Domain=${domain}`);
}
if (expires) {
serializedOptions.push(`Expires=${expires.toUTCString()}`);
}
if (httpOnly) {
serializedOptions.push(`HttpOnly`);
}
if (sameSite) {
serializedOptions.push(`SameSite=${sameSite}`);
}
if (secure) {
serializedOptions.push(`Secure`);
}
if (path) {
serializedOptions.push(`Path=${path}`);
}
return serializedOptions.join(';');
};
// Ensures the cookie names are encoded in order to look up the cookie store
// that is manipulated by js-cookie on the client side.
// Details of the js-cookie encoding behavior see:
// https://github.com/js-cookie/js-cookie#encoding
// The implementation is borrowed from js-cookie without escaping `[()]` as
// we are not using those chars in the auth keys.
const ensureEncodedForJSCookie = (name) => encodeURIComponent(name).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent);
const getExistingSetCookieValues = (values) => values === undefined ? [] : Array.isArray(values) ? values : [String(values)];
const shouldIgnoreCookie = (ignoreNonServerSideCookies, cookieName) => ignoreNonServerSideCookies && !(0, utils_1.isServerSideAuthAllowedCookie)(cookieName);
//# sourceMappingURL=createCookieStorageAdapterFromNextServerContext.js.map

@@ -7,6 +7,23 @@ 'use strict';

exports.createRunWithAmplifyServerContext = void 0;
const core_1 = require("@aws-amplify/core");
const utils_1 = require("aws-amplify/utils");
const adapter_core_1 = require("aws-amplify/adapter-core");
const constant_1 = require("../auth/constant");
const createCookieStorageAdapterFromNextServerContext_1 = require("./createCookieStorageAdapterFromNextServerContext");
const createRunWithAmplifyServerContext = ({ config: resourcesConfig, tokenValidator, }) => {
const createRunWithAmplifyServerContext = ({ config: resourcesConfig, tokenValidator, globalSettings, }) => {
const isServerSideAuthEnabled = globalSettings.isServerSideAuthEnabled();
const isSSLOrigin = globalSettings.isSSLOrigin();
const setCookieOptions = globalSettings.getRuntimeOptions().cookies ?? {};
const mergedSetCookieOptions = {
// default options when not specified
...(isServerSideAuthEnabled && constant_1.DEFAULT_SERVER_SIDE_AUTH_SET_COOKIE_OPTIONS),
// user-specified options
...setCookieOptions,
// enforced options when server-side auth is enabled
...(isServerSideAuthEnabled && {
...constant_1.ENFORCED_SERVER_SIDE_AUTH_SET_COOKIE_OPTIONS,
secure: isSSLOrigin,
}),
// only support root path
path: '/',
};
const runWithAmplifyServerContext = async ({ nextServerContext, operation }) => {

@@ -22,4 +39,4 @@ // When the Auth config is presented, attempt to create a Amplify server

nextServerContext === null
? core_1.sharedInMemoryStorage
: (0, adapter_core_1.createKeyValueStorageFromCookieStorageAdapter)(await (0, createCookieStorageAdapterFromNextServerContext_1.createCookieStorageAdapterFromNextServerContext)(nextServerContext), tokenValidator);
? utils_1.sharedInMemoryStorage
: (0, adapter_core_1.createKeyValueStorageFromCookieStorageAdapter)(await (0, createCookieStorageAdapterFromNextServerContext_1.createCookieStorageAdapterFromNextServerContext)(nextServerContext, isServerSideAuthEnabled), tokenValidator, mergedSetCookieOptions);
const credentialsProvider = (0, adapter_core_1.createAWSCredentialsAndIdentityIdProvider)(resourcesConfig.Auth, keyValueStorage);

@@ -26,0 +43,0 @@ const tokenProvider = (0, adapter_core_1.createUserPoolsTokenProvider)(resourcesConfig.Auth, keyValueStorage);

@@ -6,3 +6,3 @@ 'use strict';

Object.defineProperty(exports, "__esModule", { value: true });
exports.isValidCognitoToken = exports.createRunWithAmplifyServerContext = void 0;
exports.globalSettings = exports.isValidCognitoToken = exports.createRunWithAmplifyServerContext = void 0;
var createRunWithAmplifyServerContext_1 = require("./createRunWithAmplifyServerContext");

@@ -12,2 +12,4 @@ Object.defineProperty(exports, "createRunWithAmplifyServerContext", { enumerable: true, get: function () { return createRunWithAmplifyServerContext_1.createRunWithAmplifyServerContext; } });

Object.defineProperty(exports, "isValidCognitoToken", { enumerable: true, get: function () { return isValidCognitoToken_1.isValidCognitoToken; } });
var globalSettings_1 = require("./globalSettings");
Object.defineProperty(exports, "globalSettings", { enumerable: true, get: function () { return globalSettings_1.globalSettings; } });
//# sourceMappingURL=index.js.map

@@ -1,5 +0,5 @@

import { ResourcesConfig } from '@aws-amplify/core';
import { ResourcesConfig } from 'aws-amplify';
import { NextServer } from '../types';
export declare const createServerRunnerForAPI: ({ config, }: NextServer.CreateServerRunnerInput) => NextServer.CreateServerRunnerOutput & {
export declare const createServerRunnerForAPI: ({ config, }: NextServer.CreateServerRunnerInput) => Omit<NextServer.CreateServerRunnerOutput, 'createAuthRouteHandlers'> & {
resourcesConfig: ResourcesConfig;
};

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

import { V6ClientSSRCookies, V6ClientSSRRequest } from '@aws-amplify/api-graphql';
import { CommonPublicClientOptions, DefaultCommonClientOptions } from '@aws-amplify/api-graphql/internals';
import { CommonPublicClientOptions, DefaultCommonClientOptions, V6ClientSSRCookies, V6ClientSSRRequest } from 'aws-amplify/api/internals';
import { NextServer } from '../types';

@@ -4,0 +3,0 @@ interface CookiesClientParams {

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

import { V6ClientSSRCookies, V6ClientSSRRequest } from '@aws-amplify/api-graphql';
import { V6ClientSSRCookies, V6ClientSSRRequest } from 'aws-amplify/api/internals';
export { generateServerClientUsingReqRes, generateServerClientUsingCookies, } from './generateServerClient';

@@ -3,0 +3,0 @@ type ClientUsingSSRCookies<T extends Record<any, any> = never> = V6ClientSSRCookies<T>;

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

/// <reference types="node" />
import { GetServerSidePropsContext as NextGetServerSidePropsContext } from 'next';

@@ -5,4 +6,5 @@ import { NextRequest, NextResponse } from 'next/server.js';

import { AmplifyOutputs, LegacyConfig } from 'aws-amplify/adapter-core';
import { AmplifyServer } from '@aws-amplify/core/internals/adapter-core';
import { ResourcesConfig } from '@aws-amplify/core';
import { AmplifyServer, CookieStorage } from 'aws-amplify/adapter-core/internals';
import { ResourcesConfig } from 'aws-amplify';
import { CreateAuthRouteHandlers } from '../auth/types';
export declare namespace NextServer {

@@ -57,9 +59,100 @@ /**

type RunOperationWithContext = <OperationResult>(input: RunWithContextInput<OperationResult>) => Promise<OperationResult>;
interface CreateServerRunnerRuntimeOptions {
cookies?: Pick<CookieStorage.SetCookieOptions, 'domain' | 'expires' | 'sameSite' | 'maxAge'>;
}
interface CreateServerRunnerInput {
config: ResourcesConfig | LegacyConfig | AmplifyOutputs;
runtimeOptions?: CreateServerRunnerRuntimeOptions;
}
interface CreateServerRunnerOutput {
/**
* The function to run an operation with the Amplify server context. The operation is a callback function that
* takes a context spec parameter which is used to call the Amplify-side server APIs. The result of the operation
* is returned as a promise.
*
* @example
* ```
* // In `src/amplifyUtils.ts`
* import { createServerRunner } from 'aws-amplify/adapter-nextjs';
* import outputs from '@/amplify_outputs.json';
*
* export const { runWithAmplifyServerContext } = createServerRunner({ config: outputs });
*
* // In `src/app/home/page.tsx` (App router)
* import { cookies } from 'next/headers';
* import { runWithAmplifyServerContext } from '@/amplifyUtils';
*
* export default async function HomePage() {
* const user = await runWithAmplifyServerContext({
* nextServerContext: { cookies },
* operation: (contextSpec) => getCurrentUser(contextSpec),
* });
*
* return <div>{`Hello, ${user.username}`}</div>;
* }
*
* // In `src/pages/home/index.tsx` (Pages router)
* import { runWithAmplifyServerContext } from '@/amplifyUtils';
*
* export const getServerSideProps = async ({ req, res }) => {
* const user = await runWithAmplifyServerContext({
* nextServerContext: { request: req, response: res },
* operation: (contextSpec) => getCurrentUser(contextSpec),
* });
*
* return {
* props: { user },
* }
* }
*
* export default function HomePage(props) {
* return <div>{`Hello, ${props.user.username}`}</div>;
* }
* ```
*/
runWithAmplifyServerContext: RunOperationWithContext;
/**
* The factory function to create the route handlers for the Amplify server-side authentication. You can call this
* function and export the result as the route handlers in the Next.js API routes, to authenticate your end users
* on the server side.
*
* Note: when enabling server-side authentication, Amplify APIs can no longer be used in the client-side.
* @experimental
*
* @example
* ```
* // In `src/amplifyUtils.ts`
* import { createServerRunner } from 'aws-amplify/adapter-nextjs';
* import outputs from '@/amplify_outputs.json';
*
* export const { createAuthRouteHandlers } = createServerRunner({ config: outputs });
*
* // In `src/app/api/auth/[slug]/route.tsx` (App router)
* import { createAuthRouteHandlers } from '@/amplifyUtils';
*
* export const GET = createAuthRouteHandlers({
* redirectOnSignInComplete: "/home",
* redirectOnSignOutComplete: "/sign-in",
* );
*
* // In `src/pages/api/auth/[slug].tsx` (Pages router)
* import { createAuthRouteHandlers } from '@/amplifyUtils';
*
* export default createAuthRouteHandlers({
* redirectOnSignInComplete: "/home",
* redirectOnSignOutComplete: "/sign-in",
* });
* ```
*/
createAuthRouteHandlers: CreateAuthRouteHandlers;
}
type CreateServerRunner = (input: CreateServerRunnerInput) => CreateServerRunnerOutput;
interface GlobalSettings {
isServerSideAuthEnabled(): boolean;
enableServerSideAuth(): void;
setRuntimeOptions(runtimeOptions: CreateServerRunnerRuntimeOptions): void;
getRuntimeOptions(): CreateServerRunnerRuntimeOptions;
setIsSSLOrigin(isSSLOrigin: boolean): void;
isSSLOrigin(): boolean;
}
}

@@ -1,4 +0,4 @@

import { CookieStorage } from '@aws-amplify/core/internals/adapter-core';
import { CookieStorage } from 'aws-amplify/adapter-core/internals';
import { NextServer } from '../types';
export declare const DATE_IN_THE_PAST: Date;
export declare const createCookieStorageAdapterFromNextServerContext: (context: NextServer.Context) => Promise<CookieStorage.Adapter>;
export declare const createCookieStorageAdapterFromNextServerContext: (context: NextServer.Context, ignoreNonServerSideCookies?: boolean) => Promise<CookieStorage.Adapter>;

@@ -1,7 +0,8 @@

import { ResourcesConfig } from '@aws-amplify/core';
import { KeyValueStorageMethodValidator } from '@aws-amplify/core/internals/adapter-core';
import { ResourcesConfig } from 'aws-amplify';
import { KeyValueStorageMethodValidator } from 'aws-amplify/adapter-core/internals';
import { NextServer } from '../types';
export declare const createRunWithAmplifyServerContext: ({ config: resourcesConfig, tokenValidator, }: {
export declare const createRunWithAmplifyServerContext: ({ config: resourcesConfig, tokenValidator, globalSettings, }: {
config: ResourcesConfig;
tokenValidator?: Partial<Record<keyof import("@aws-amplify/core").KeyValueStorageInterface, (...args: any[]) => Promise<boolean>>> | undefined;
tokenValidator?: Partial<Record<keyof import("aws-amplify/utils").KeyValueStorageInterface, (...args: any[]) => Promise<boolean>>> | undefined;
globalSettings: NextServer.GlobalSettings;
}) => NextServer.RunOperationWithContext;

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

import { KeyValueStorageMethodValidator } from '@aws-amplify/core/internals/adapter-core';
import { KeyValueStorageMethodValidator } from 'aws-amplify/adapter-core/internals';
interface CreateTokenValidatorInput {

@@ -3,0 +3,0 @@ userPoolId?: string;

export { createRunWithAmplifyServerContext } from './createRunWithAmplifyServerContext';
export { isValidCognitoToken } from './isValidCognitoToken';
export { globalSettings } from './globalSettings';
{
"author": "Amazon Web Services",
"name": "@aws-amplify/adapter-nextjs",
"version": "1.4.4-unstable.289f3e8.0+289f3e8",
"version": "1.4.4-websocket-event.29583bc.0+29583bc",
"description": "The adapter for the supporting of using Amplify APIs in Next.js.",
"peerDependencies": {
"aws-amplify": "6.12.4-unstable.289f3e8.0+289f3e8",
"aws-amplify": "6.12.4-websocket-event.29583bc.0+29583bc",
"next": ">=13.5.0 <16.0.0"

@@ -19,3 +19,3 @@ },

"@types/react-dom": "^18.2.6",
"aws-amplify": "6.12.4-unstable.289f3e8.0+289f3e8",
"aws-amplify": "6.12.4-websocket-event.29583bc.0+29583bc",
"jest-fetch-mock": "3.0.3",

@@ -75,3 +75,3 @@ "next": ">= 13.5.0 < 15.0.0",

},
"gitHead": "289f3e8d1bbf8c95abffb553b612699f43cdccb5"
"gitHead": "29583bc76371b116b2c715d0f93da0c76da2a92f"
}
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { ResourcesConfig } from '@aws-amplify/core';
import { parseAmplifyConfig } from '@aws-amplify/core/internals/utils';
import { ResourcesConfig } from 'aws-amplify';
import { parseAmplifyConfig } from 'aws-amplify/utils';
import { createRunWithAmplifyServerContext } from '../utils';
import { createRunWithAmplifyServerContext, globalSettings } from '../utils';
import { NextServer } from '../types';

@@ -12,3 +12,6 @@

config,
}: NextServer.CreateServerRunnerInput): NextServer.CreateServerRunnerOutput & {
}: NextServer.CreateServerRunnerInput): Omit<
NextServer.CreateServerRunnerOutput,
'createAuthRouteHandlers'
> & {
resourcesConfig: ResourcesConfig;

@@ -21,2 +24,3 @@ } => {

config: amplifyConfig,
globalSettings,
}),

@@ -23,0 +27,0 @@ resourcesConfig: amplifyConfig,

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { generateClientWithAmplifyInstance } from '@aws-amplify/api/internals';
import {
CommonPublicClientOptions,
DefaultCommonClientOptions,
V6ClientSSRCookies,
V6ClientSSRRequest,
generateClientWithAmplifyInstance,
} from 'aws-amplify/api/internals';
import { generateClient } from 'aws-amplify/api/server';

@@ -9,12 +15,4 @@ import {

getAmplifyServerContext,
} from '@aws-amplify/core/internals/adapter-core';
import {
V6ClientSSRCookies,
V6ClientSSRRequest,
} from '@aws-amplify/api-graphql';
import {
CommonPublicClientOptions,
DefaultCommonClientOptions,
} from '@aws-amplify/api-graphql/internals';
import { parseAmplifyConfig } from '@aws-amplify/core/internals/utils';
} from 'aws-amplify/adapter-core/internals';
import { parseAmplifyConfig } from 'aws-amplify/utils';

@@ -21,0 +19,0 @@ import { NextServer } from '../types';

@@ -7,3 +7,3 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.

V6ClientSSRRequest,
} from '@aws-amplify/api-graphql';
} from 'aws-amplify/api/internals';

@@ -10,0 +10,0 @@ export {

@@ -5,8 +5,10 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.

import { ResourcesConfig } from 'aws-amplify';
import { KeyValueStorageMethodValidator } from '@aws-amplify/core/internals/adapter-core';
import { parseAmplifyConfig } from '@aws-amplify/core/internals/utils';
import { KeyValueStorageMethodValidator } from 'aws-amplify/adapter-core/internals';
import { parseAmplifyConfig } from 'aws-amplify/utils';
import { createRunWithAmplifyServerContext } from './utils';
import { createRunWithAmplifyServerContext, globalSettings } from './utils';
import { NextServer } from './types';
import { createTokenValidator } from './utils/createTokenValidator';
import { createAuthRouteHandlersFactory } from './auth';
import { isSSLOrigin, isValidOrigin } from './auth/utils';

@@ -33,5 +35,16 @@ /**

config,
runtimeOptions,
}) => {
const amplifyConfig = parseAmplifyConfig(config);
const amplifyAppOrigin = process.env.AMPLIFY_APP_ORIGIN;
globalSettings.setRuntimeOptions(runtimeOptions ?? {});
if (isValidOrigin(amplifyAppOrigin)) {
globalSettings.setIsSSLOrigin(isSSLOrigin(amplifyAppOrigin));
// update the isServerSideAuthEnabled flag of the globalSettings to true
globalSettings.enableServerSideAuth();
}
let tokenValidator: KeyValueStorageMethodValidator | undefined;

@@ -46,8 +59,17 @@ if (amplifyConfig?.Auth) {

const runWithAmplifyServerContext = createRunWithAmplifyServerContext({
config: amplifyConfig,
tokenValidator,
globalSettings,
});
return {
runWithAmplifyServerContext: createRunWithAmplifyServerContext({
runWithAmplifyServerContext,
createAuthRouteHandlers: createAuthRouteHandlersFactory({
config: amplifyConfig,
tokenValidator,
amplifyAppOrigin,
globalSettings,
runWithAmplifyServerContext,
}),
};
};

@@ -8,5 +8,10 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.

import { AmplifyOutputs, LegacyConfig } from 'aws-amplify/adapter-core';
import { AmplifyServer } from '@aws-amplify/core/internals/adapter-core';
import { ResourcesConfig } from '@aws-amplify/core';
import {
AmplifyServer,
CookieStorage,
} from 'aws-amplify/adapter-core/internals';
import { ResourcesConfig } from 'aws-amplify';
import { CreateAuthRouteHandlers } from '../auth/types';
export declare namespace NextServer {

@@ -77,8 +82,95 @@ /**

export interface CreateServerRunnerRuntimeOptions {
cookies?: Pick<
CookieStorage.SetCookieOptions,
'domain' | 'expires' | 'sameSite' | 'maxAge'
>;
}
export interface CreateServerRunnerInput {
config: ResourcesConfig | LegacyConfig | AmplifyOutputs;
runtimeOptions?: CreateServerRunnerRuntimeOptions;
}
export interface CreateServerRunnerOutput {
/**
* The function to run an operation with the Amplify server context. The operation is a callback function that
* takes a context spec parameter which is used to call the Amplify-side server APIs. The result of the operation
* is returned as a promise.
*
* @example
* ```
* // In `src/amplifyUtils.ts`
* import { createServerRunner } from 'aws-amplify/adapter-nextjs';
* import outputs from '@/amplify_outputs.json';
*
* export const { runWithAmplifyServerContext } = createServerRunner({ config: outputs });
*
* // In `src/app/home/page.tsx` (App router)
* import { cookies } from 'next/headers';
* import { runWithAmplifyServerContext } from '@/amplifyUtils';
*
* export default async function HomePage() {
* const user = await runWithAmplifyServerContext({
* nextServerContext: { cookies },
* operation: (contextSpec) => getCurrentUser(contextSpec),
* });
*
* return <div>{`Hello, ${user.username}`}</div>;
* }
*
* // In `src/pages/home/index.tsx` (Pages router)
* import { runWithAmplifyServerContext } from '@/amplifyUtils';
*
* export const getServerSideProps = async ({ req, res }) => {
* const user = await runWithAmplifyServerContext({
* nextServerContext: { request: req, response: res },
* operation: (contextSpec) => getCurrentUser(contextSpec),
* });
*
* return {
* props: { user },
* }
* }
*
* export default function HomePage(props) {
* return <div>{`Hello, ${props.user.username}`}</div>;
* }
* ```
*/
runWithAmplifyServerContext: RunOperationWithContext;
/**
* The factory function to create the route handlers for the Amplify server-side authentication. You can call this
* function and export the result as the route handlers in the Next.js API routes, to authenticate your end users
* on the server side.
*
* Note: when enabling server-side authentication, Amplify APIs can no longer be used in the client-side.
* @experimental
*
* @example
* ```
* // In `src/amplifyUtils.ts`
* import { createServerRunner } from 'aws-amplify/adapter-nextjs';
* import outputs from '@/amplify_outputs.json';
*
* export const { createAuthRouteHandlers } = createServerRunner({ config: outputs });
*
* // In `src/app/api/auth/[slug]/route.tsx` (App router)
* import { createAuthRouteHandlers } from '@/amplifyUtils';
*
* export const GET = createAuthRouteHandlers({
* redirectOnSignInComplete: "/home",
* redirectOnSignOutComplete: "/sign-in",
* );
*
* // In `src/pages/api/auth/[slug].tsx` (Pages router)
* import { createAuthRouteHandlers } from '@/amplifyUtils';
*
* export default createAuthRouteHandlers({
* redirectOnSignInComplete: "/home",
* redirectOnSignOutComplete: "/sign-in",
* });
* ```
*/
createAuthRouteHandlers: CreateAuthRouteHandlers;
}

@@ -89,2 +181,11 @@

) => CreateServerRunnerOutput;
export interface GlobalSettings {
isServerSideAuthEnabled(): boolean;
enableServerSideAuth(): void;
setRuntimeOptions(runtimeOptions: CreateServerRunnerRuntimeOptions): void;
getRuntimeOptions(): CreateServerRunnerRuntimeOptions;
setIsSSLOrigin(isSSLOrigin: boolean): void;
isSSLOrigin(): boolean;
}
}

@@ -8,6 +8,9 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.

CookieStorage,
} from '@aws-amplify/core/internals/adapter-core';
} from 'aws-amplify/adapter-core/internals';
import { NextServer } from '../types';
import { isServerSideAuthAllowedCookie } from '../auth/utils';
import { ensureEncodedForJSCookie, serializeCookie } from './cookie';
export const DATE_IN_THE_PAST = new Date(0);

@@ -17,2 +20,3 @@

context: NextServer.Context,
ignoreNonServerSideCookies = false,
): Promise<CookieStorage.Adapter> => {

@@ -33,3 +37,7 @@ const { request: req, response: res } =

) {
return createCookieStorageAdapterFromGetServerSidePropsContext(req, res);
return createCookieStorageAdapterFromGetServerSidePropsContext(
req,
res,
ignoreNonServerSideCookies,
);
}

@@ -53,2 +61,3 @@

response,
ignoreNonServerSideCookies,
);

@@ -59,2 +68,3 @@ } else {

response,
ignoreNonServerSideCookies,
);

@@ -69,3 +79,6 @@ }

if (typeof cookies === 'function') {
return createCookieStorageAdapterFromNextCookies(cookies);
return createCookieStorageAdapterFromNextCookies(
cookies,
ignoreNonServerSideCookies,
);
}

@@ -83,2 +96,3 @@

response: NextResponse,
ignoreNonServerSideCookies: boolean,
): CookieStorage.Adapter => {

@@ -94,5 +108,11 @@ const readonlyCookieStore = request.cookies;

set(name, value, options) {
if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {
return;
}
mutableCookieStore.set(ensureEncodedForJSCookie(name), value, options);
},
delete(name) {
if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {
return;
}
mutableCookieStore.delete(ensureEncodedForJSCookie(name));

@@ -106,2 +126,3 @@ },

response: Response,
ignoreNonServerSideCookies: boolean,
): CookieStorage.Adapter => {

@@ -111,2 +132,3 @@ const readonlyCookieStore = request.cookies;

response.headers,
ignoreNonServerSideCookies,
);

@@ -125,2 +147,3 @@

cookies: NextServer.ServerComponentContext['cookies'],
ignoreNonServerSideCookies: boolean,
): Promise<CookieStorage.Adapter> => {

@@ -135,2 +158,6 @@ const cookieStore = await cookies();

const setFunc: CookieStorage.Adapter['set'] = (name, value, options) => {
if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {
return;
}
try {

@@ -144,2 +171,6 @@ cookieStore.set(ensureEncodedForJSCookie(name), value, options);

const deleteFunc: CookieStorage.Adapter['delete'] = name => {
if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {
return;
}
try {

@@ -165,2 +196,3 @@ cookieStore.delete(ensureEncodedForJSCookie(name));

response: NextServer.GetServerSidePropsContext['response'],
ignoreNonServerSideCookies: boolean,
): CookieStorage.Adapter => {

@@ -188,2 +220,5 @@ const cookiesMap = { ...request.cookies };

set(name, value, options) {
if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {
return;
}
const encodedName = ensureEncodedForJSCookie(name);

@@ -208,8 +243,10 @@

'Set-Cookie',
`${encodedName}=${value};${
options ? serializeSetCookieOptions(options) : ''
}`,
serializeCookie(encodedName, value, options),
);
},
delete(name) {
if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {
return;
}
const encodedName = ensureEncodedForJSCookie(name);

@@ -234,12 +271,19 @@ const setCookieValue = `${encodedName}=;Expires=${DATE_IN_THE_PAST.toUTCString()}`;

headers: Headers,
ignoreNonServerSideCookies: boolean,
): Pick<CookieStorage.Adapter, 'set' | 'delete'> => {
const setFunc: CookieStorage.Adapter['set'] = (name, value, options) => {
if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {
return;
}
headers.append(
'Set-Cookie',
`${ensureEncodedForJSCookie(name)}=${value};${
options ? serializeSetCookieOptions(options) : ''
}`,
serializeCookie(ensureEncodedForJSCookie(name), value, options),
);
};
const deleteFunc: CookieStorage.Adapter['delete'] = name => {
if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {
return;
}
headers.append(

@@ -259,38 +303,2 @@ 'Set-Cookie',

const serializeSetCookieOptions = (
options: CookieStorage.SetCookieOptions,
): string => {
const { expires, domain, httpOnly, sameSite, secure, path } = options;
const serializedOptions: string[] = [];
if (domain) {
serializedOptions.push(`Domain=${domain}`);
}
if (expires) {
serializedOptions.push(`Expires=${expires.toUTCString()}`);
}
if (httpOnly) {
serializedOptions.push(`HttpOnly`);
}
if (sameSite) {
serializedOptions.push(`SameSite=${sameSite}`);
}
if (secure) {
serializedOptions.push(`Secure`);
}
if (path) {
serializedOptions.push(`Path=${path}`);
}
return serializedOptions.join(';');
};
// Ensures the cookie names are encoded in order to look up the cookie store
// that is manipulated by js-cookie on the client side.
// Details of the js-cookie encoding behavior see:
// https://github.com/js-cookie/js-cookie#encoding
// The implementation is borrowed from js-cookie without escaping `[()]` as
// we are not using those chars in the auth keys.
const ensureEncodedForJSCookie = (name: string): string =>
encodeURIComponent(name).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent);
const getExistingSetCookieValues = (

@@ -300,1 +308,7 @@ values: number | string | string[] | undefined,

values === undefined ? [] : Array.isArray(values) ? values : [String(values)];
const shouldIgnoreCookie = (
ignoreNonServerSideCookies: boolean,
cookieName: string,
): boolean =>
ignoreNonServerSideCookies && !isServerSideAuthAllowedCookie(cookieName);
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { ResourcesConfig, sharedInMemoryStorage } from '@aws-amplify/core';
import { KeyValueStorageMethodValidator } from '@aws-amplify/core/internals/adapter-core';
import { ResourcesConfig } from 'aws-amplify';
import { sharedInMemoryStorage } from 'aws-amplify/utils';
import { KeyValueStorageMethodValidator } from 'aws-amplify/adapter-core/internals';
import {

@@ -14,2 +15,6 @@ createAWSCredentialsAndIdentityIdProvider,

import { NextServer } from '../types';
import {
DEFAULT_SERVER_SIDE_AUTH_SET_COOKIE_OPTIONS,
ENFORCED_SERVER_SIDE_AUTH_SET_COOKIE_OPTIONS,
} from '../auth/constant';

@@ -21,6 +26,26 @@ import { createCookieStorageAdapterFromNextServerContext } from './createCookieStorageAdapterFromNextServerContext';

tokenValidator,
globalSettings,
}: {
config: ResourcesConfig;
tokenValidator?: KeyValueStorageMethodValidator;
globalSettings: NextServer.GlobalSettings;
}) => {
const isServerSideAuthEnabled = globalSettings.isServerSideAuthEnabled();
const isSSLOrigin = globalSettings.isSSLOrigin();
const setCookieOptions = globalSettings.getRuntimeOptions().cookies ?? {};
const mergedSetCookieOptions = {
// default options when not specified
...(isServerSideAuthEnabled && DEFAULT_SERVER_SIDE_AUTH_SET_COOKIE_OPTIONS),
// user-specified options
...setCookieOptions,
// enforced options when server-side auth is enabled
...(isServerSideAuthEnabled && {
...ENFORCED_SERVER_SIDE_AUTH_SET_COOKIE_OPTIONS,
secure: isSSLOrigin,
}),
// only support root path
path: '/',
};
const runWithAmplifyServerContext: NextServer.RunOperationWithContext =

@@ -41,4 +66,6 @@ async ({ nextServerContext, operation }) => {

nextServerContext,
isServerSideAuthEnabled,
),
tokenValidator,
mergedSetCookieOptions,
);

@@ -45,0 +72,0 @@ const credentialsProvider = createAWSCredentialsAndIdentityIdProvider(

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { KeyValueStorageMethodValidator } from '@aws-amplify/core/internals/adapter-core';
import { KeyValueStorageMethodValidator } from 'aws-amplify/adapter-core/internals';
import { CognitoJwtVerifier } from 'aws-jwt-verify';

@@ -6,0 +6,0 @@

@@ -6,1 +6,2 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.

export { isValidCognitoToken } from './isValidCognitoToken';
export { globalSettings } from './globalSettings';

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 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

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