次のような場合に使用: Val Town アカウントでのログインが必要な場合。特定のルート(ページやAPI)をログイン済みユーザーのみに制限したり、現在のユーザーを特定したり、ユーザー個別のダッシュボードを作成したりする場面で活用できます。 このスキルでは、std/oauth の `oauthMiddleware`(認証を処理するツール)と `getOAuthUserData`(ユーザー情報を取得する機能)、自動管理される `/auth/*` ルート、セッション(ログイン状態の保持)の動作をカバーしています。 Google や GitHub などの外部の認証サービスを使う場合は、代わりに `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など他のサービスのOAuth認証については、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 による自動翻訳です。