Val Townアカウントでのログイン認証が必要な場合に使用します。特定のルート(ページ)を認証でロック、現在のユーザーを特定する、ユーザー固有のダッシュボードを構築する場合などが該当します。 このスキルは、std/oauthの`oauthMiddleware`と`getOAuthUserData`、自動管理される`/auth/*`ルート、セッション(ユーザーの訪問状態を保持する機能)の動作を対象としています。 Google・GitHubなどの外部OAuth認証プロバイダー(他社の認証サービス)の統合については、代わりに`third-party-integrations`スキルを参照してください。
Use when a val needs to require login with a Val Town account — gating routes behind authentication, identifying the current user, building user-specific dashboards. Covers std/oauth's `oauthMiddleware` and `getOAuthUserData`, the auto-managed `/auth/*` routes, and session behavior. For third-party OAuth providers (Google, GitHub, etc.) see the `third-party-integrations` skill instead.
Val Town では、std/oauth を使って設定不要な「Val Town アカウントでログイン」機能を提供しています。データベースの準備も、ログインプロバイダー(認証サービス)の設定も必要ありません。Hono(ウェブアプリケーションフレームワーク)のハンドラーをラップするだけで、ログイン、ログアウト、セッション管理(利用者の状態管理)が自動的に働きます。セッションは暗号化されたクッキーに保存され、30日間有効です。
これは Val Town アカウントでのログインのみ対応 です。Google・GitHub・Slack などのサービスでのログインについては、third-party-integrations スキルをご覧ください。各サービスごとの手順が記載されています。
アプリをチーム内だけで使い、個別のログイン利用者を設ける必要がない場合は、val のアクセス権を制限する方が簡単です。プラットフォームがコード実行前にエンドポイント(接続先)を保護し、認証コードを書く必要がありません。restricted-access スキルをご覧ください。1 つの val に両方を適用しないでください。アクセス制限された val で oauthMiddleware を実行すると、訪問者が 2 回認証させられることになります。
import {
getOAuthUserData,
oauthMiddleware,
} from "https://esm.town/v/std/oauth/middleware.ts";
oauthMiddleware(handler) は Hono のハンドラーを受け取り、以下の 3 つのルート(接続先)を自動管理するラップされたハンドラーを返します:
GET /auth/login — ログイン処理を開始GET /auth/callback — ログイン処理を完了POST /auth/logout — セッションを削除ラップされたハンドラーを val のデフォルト出力として書き出します:
import { Hono } from "npm:hono";
import { oauthMiddleware } from "https://esm.town/v/std/oauth/middleware.ts";
const app = new Hono();
app.onError((err) => Promise.reject(err));
app.get("/", (c) => c.text("hello"));
export default oauthMiddleware(app.fetch);
/auth/* ルートは自分で実装しないでください。ミドルウェア(仲介プログラム)が追加します。自分のアプリでこれらの名前を使わないようにしてください。
任意のルートから getOAuthUserData(rawRequest) を呼び出します。Hono では rawRequest は c.req.raw です。リクエストが認証済みならセッションデータを返し、そうでなければ null を返します。
interface SessionData {
user: {
id: string;
username: string | null;
email: string | null;
bio: string | null;
tier: "free" | "pro" | null;
type: "user" | "org";
url: string;
links: {
self: string;
profileImageUrl: string | null;
};
};
accessToken: string; // Val Town API トークン(利用者の代わりに操作するための認証情報)
refreshToken?: string;
idToken?: string;
expiresAt: number; // Unix タイムスタンプ(ミリ秒単位)
isOrgMember?: boolean; // 利用者がこの val の組織に属している場合は true
}
app.get("/", async (c) => {
const session = await getOAuthUserData(c.req.raw);
if (session?.user) {
return c.html(
`<p>Logged in as ${session.user.username}</p>` +
`<form method="POST" action="/auth/logout"><button>Log out</button></form>`
);
}
return c.html(`<a href="/auth/login">Log in with Val Town</a>`);
});
ログイン必須ヘルパーは組み込まれていません。getOAuthUserData で確認し、セッションがない場合は 401 ステータス(認証失敗)を返すか /auth/login にリダイレクト(転送)してください:
app.get("/dashboard", async (c) => {
const session = await getOAuthUserData(c.req.raw);
if (!session?.user) return c.redirect("/auth/login");
return c.html(`<h1>Welcome ${session.user.username}</h1>`);
});
/auth/callback は自動接続OAuth を追加した後、アクセス制限されたルートで fetch_val_endpoint を呼び出し、認証なしでリダイレクトまたは 401 が返されることを確認してください。完全なログイン流れはブラウザセッションが必要で、fetch_val_endpoint だけでは確認できません。ライブ URL を共有して、実際にログインを試してもらってください。
Val Town provides zero-config "Log in with Val Town" via std/oauth. No database setup, no provider config — wrap your Hono fetch handler and you get login, logout, and session management for free. Sessions are stored in encrypted cookies and last 30 days.
This is for Val Town account login only. For Google / GitHub / Slack / etc. OAuth, see the third-party-integrations skill — those flows are documented per-service.
If the goal is to keep an app internal to a team rather than to give it its own logged-in users, restricting the val's app access is the simpler answer — the platform gates the endpoint before your code runs, and you write no auth code. See the restricted-access skill. Don't apply both to one val: a restricted val that also runs oauthMiddleware makes visitors authenticate twice.
import {
getOAuthUserData,
oauthMiddleware,
} from "https://esm.town/v/std/oauth/middleware.ts";
oauthMiddleware(handler) takes your Hono fetch handler and returns a wrapped handler that injects three auto-managed routes:
GET /auth/login — starts the login flowGET /auth/callback — completes the login flowPOST /auth/logout — clears the sessionExport the wrapped handler as the val's default:
import { Hono } from "npm:hono";
import { oauthMiddleware } from "https://esm.town/v/std/oauth/middleware.ts";
const app = new Hono();
app.onError((err) => Promise.reject(err));
app.get("/", (c) => c.text("hello"));
export default oauthMiddleware(app.fetch);
You don't write the /auth/* routes yourself — the middleware adds them. Don't shadow them in your own app.
Call getOAuthUserData(rawRequest) from any route. In Hono, rawRequest is c.req.raw. It returns the session data if the request is authenticated, or null otherwise.
interface SessionData {
user: {
id: string;
username: string | null;
email: string | null;
bio: string | null;
tier: "free" | "pro" | null;
type: "user" | "org";
url: string;
links: {
self: string;
profileImageUrl: string | null;
};
};
accessToken: string; // Val Town API token (act on behalf of the user)
refreshToken?: string;
idToken?: string;
expiresAt: number; // Unix timestamp (ms)
isOrgMember?: boolean; // true if user belongs to this val's org
}
app.get("/", async (c) => {
const session = await getOAuthUserData(c.req.raw);
if (session?.user) {
return c.html(
`<p>Logged in as ${session.user.username}</p>` +
`<form method="POST" action="/auth/logout"><button>Log out</button></form>`
);
}
return c.html(`<a href="/auth/login">Log in with Val Town</a>`);
});
There's no built-in "require login" helper — gate routes by checking getOAuthUserData and returning a 401 or redirecting to /auth/login when the session is missing:
app.get("/dashboard", async (c) => {
const session = await getOAuthUserData(c.req.raw);
if (!session?.user) return c.redirect("/auth/login");
return c.html(`<h1>Welcome ${session.user.username}</h1>`);
});
/auth/callback is wired automatically.After adding OAuth, call fetch_val_endpoint on a gated route to confirm it redirects or 401s when unauthenticated. The full login flow requires a real browser session and can't be exercised by fetch_val_endpoint alone — share the live URL and have the user try logging in.
原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。