@appgrowstack/app-auth 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # CHANGELOG
2
2
 
3
+ ## 0.7.0(2026-12-05)
4
+
5
+ - `hooks.onSessionIssued({ userId, installId, previousUserId }, env)`:セッションを出すたびに呼ぶ。答えの `{ person_id, merged }` をセッションの `appgrowstack` に載せる。フックが投げてもセッションは出す
6
+ - `sign_in_existing` で Bearer の人が匿名なら、その uid を `previousUserId` に渡す
7
+ - `issueSession` は6つ目の引数 `previousUserId`(既定 `null`)を受ける
8
+
9
+ アプリの側で要ること:`"@appgrowstack/app-auth": "^0.7.0"` にし、`onSessionIssued` で appgrowstack の `identify` を呼ぶ(README の「appgrowstack の人につなぐ」)
10
+
3
11
  ## 0.6.1(2026-12-05)
4
12
 
5
13
  - npmの`@appgrowstack/app-auth`で配る。アプリの`api/vendor/app-auth/`のコピーと`VENDORED.json`は消す
package/README.md CHANGED
@@ -86,6 +86,10 @@ const auth: AppAuthConfig<Bindings> = {
86
86
  // refreshTokenIdleTtlMs: 180 * 24 * 60 * 60 * 1000, // 既定。下の「使われない期間の期限」
87
87
  // anonymous: false, // 匿名のアカウントを作らないアプリだけ。下の「匿名を作らないアプリ」
88
88
  hooks: {
89
+ onSessionIssued: async ({ userId, installId, previousUserId }, env) => { // 下の「appgrowstack の人につなぐ」
90
+ const r = await env.APPGROWSTACK.identify({ project: "my-app", actor: { install_id: installId.toLowerCase(), uid: userId }, ...(previousUserId ? { previous_uid: previousUserId } : {}), at: Date.now() })
91
+ return { person_id: r.person_id, merged: r.merged_from !== null }
92
+ },
89
93
  onUserCreated: async (userId, env) => { /* アプリの表に行を足すなど */ },
90
94
  onIdentityLinked: async (userId, provider, env) => {},
91
95
  },
@@ -121,7 +125,7 @@ app.post("/v1/account/delete", async (c) => {
121
125
 
122
126
  ### issueSession
123
127
 
124
- `issueSession(config, env, userId, installId, at)`は、いる人(`auth_users`に生きた行がある人)に新しい端末の行を作り、`Session`を返す。アプリが自分で人を確かめた時(ストアの審査用のコードでテレビに入るなど)に使う。
128
+ `issueSession(config, env, userId, installId, at)`はいる人(`auth_users`に生きた行がある人)に新しい端末の行を作り、`Session`を返す。アプリが自分で人を確かめた時(ストアの審査用のコードでテレビに入るなど)に使う。
125
129
 
126
130
  ### deleteUser
127
131
 
@@ -170,7 +174,7 @@ type Session = {
170
174
  }
171
175
  ```
172
176
 
173
- - サービスの名前は`apple`・`google`・`anonymous`(iOSの`AuthProviderID`と同じ値)。`linkedProviders`は、apple・googleを1つもつないでいない人では`["anonymous"]`
177
+ - サービスの名前は`apple`・`google`・`anonymous`(iOSの`AuthProviderID`と同じ値)。`linkedProviders`はapple・googleを1つもつないでいない人では`["anonymous"]`
174
178
  - リフレッシュトークンは端末ごとに1つ(`<deviceId>.<秘密>`。D1には秘密のSHA-256だけ)。refreshのたびに替えない。中国の回線で返事が届かなかったとき、キーを失ってログアウトするのを避けるため。代わりに、180日使われない端末のリフレッシュトークンを断る(下の「使われない期間の期限」)
175
179
  - 匿名・Apple・Google・Firebaseのエンドポイントは、呼ぶたびに新しい端末の行を作る。前の端末のリフレッシュトークンは無効にしない(返事が届かなくてもログアウトしないため)
176
180
  - 409のとき、どちらの人を残すかは端末で本人が選ぶ。記録は合わせない
@@ -250,7 +254,7 @@ type DeviceStartResponse = {
250
254
 
251
255
  ### サインアウト
252
256
 
253
- `POST /v1/auth/sign-out`は、Bearerのアクセストークンに入っている端末ID(`did`。そのアクセストークンを発行したときの`auth_devices`の行)だけを無効にする。その端末のリフレッシュトークンも、その端末から出したアクセストークンも使えなくなる。同じ人のほかの端末と、同じ端末で後から作った別の端末の行はそのまま。
257
+ `POST /v1/auth/sign-out`はBearerのアクセストークンに入っている端末ID(`did`。そのアクセストークンを発行したときの`auth_devices`の行)だけを無効にする。その端末のリフレッシュトークンも、その端末から出したアクセストークンも使えなくなる。同じ人のほかの端末と、同じ端末で後から作った別の端末の行はそのまま。
254
258
 
255
259
  - 別の人に切り替えるとき(409の後の`sign_in_existing`など)、切り替える前のアクセストークンでサインアウトを呼べば、前の人の端末のキーだけが無効になる。切り替えた後のセッションには影響しない
256
260
  - 切り替えのエンドポイントは前の端末を自分では無効にしない(返事が届かなかったとき、前のキーまで失ってログアウトしないため)。無効にするかは端末が決める
@@ -319,3 +323,11 @@ bun install && cd packages/app-auth && bun run test && bun run typecheck
319
323
  単体(`test/unit`)・D1(`test/d1`)・HTTP(`test/http`)の層に分けてある。偽のD1とテストのキーは`test/support`。
320
324
 
321
325
  Apple・Google・Firebaseの公開キーは、テストで作ったキーのJWKSを渡して確かめる(本物に問い合わせない)。D1はbun:sqliteでD1の形をまねたフェイク(外部キーの制約を有効にする)。Appleの無効化・Identity Toolkit・securetokenはfetchのフェイク(securetokenは`config.fetch`で差し替える)。
326
+
327
+ ## appgrowstack の人につなぐ
328
+
329
+ `hooks.onSessionIssued` は、セッションを出すたびに(匿名で始めた・サインインした・TV でログインした)`{ userId, installId, previousUserId }` を渡す。アプリはこれを appgrowstack の `identify` に渡し、install_id と uid を同じ人につなぐ。答えの `{ person_id, merged }` を返すと、セッションの答えの `appgrowstack` に載り、端末は SDK の `adopt` に渡す。
330
+
331
+ - `previousUserId` は、匿名で始めた人がほかの端末で作ったアカウントに `sign_in_existing` でサインインした時の、前の匿名の uid(Bearer で来た物)。appgrowstack は `previous_uid` で受け、匿名の人をアカウントの人に寄せる。サインイン済みのアカウントからの切り替えでは `null`
332
+ - フックが投げても、セッションはそのまま出す(ログに `app_auth_session_hook_failed` を残す)
333
+ - 決まりの全体は [IDの一覧とつながり](../../docs/design/identity.md)
package/dist/config.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { JWTVerifyGetKey } from "jose";
2
- import type { LinkableProvider } from "./contract.js";
2
+ import type { LinkableProvider, SessionPerson } from "./contract.js";
3
3
  import type { D1Like } from "./d1.js";
4
4
  export type FromEnv<E, T> = T | ((env: E) => T);
5
5
  export type KeySource = string | JWTVerifyGetKey;
@@ -61,7 +61,13 @@ export interface RateLimitConfig {
61
61
  byUser?: RateLimiterLike;
62
62
  };
63
63
  }
64
+ export interface IssuedSession {
65
+ userId: string;
66
+ installId: string;
67
+ previousUserId: string | null;
68
+ }
64
69
  export interface AuthHooks<E> {
70
+ onSessionIssued?: (issued: IssuedSession, env: E) => SessionPerson | void | Promise<SessionPerson | void>;
65
71
  onUserCreated?: (userId: string, env: E) => void | Promise<void>;
66
72
  onIdentityLinked?: (userId: string, provider: LinkableProvider, env: E) => void | Promise<void>;
67
73
  }
@@ -7,11 +7,16 @@ export interface SessionUser {
7
7
  linkedProviders: ProviderId[];
8
8
  createdAt: EpochMs;
9
9
  }
10
+ export interface SessionPerson {
11
+ person_id: string;
12
+ merged: boolean;
13
+ }
10
14
  export interface Session {
11
15
  user: SessionUser;
12
16
  accessToken: string;
13
17
  accessTokenExpiresAt: EpochMs;
14
18
  refreshToken: string;
19
+ appgrowstack?: SessionPerson;
15
20
  }
16
21
  export interface AnonymousRequest {
17
22
  installId: string;
package/dist/routes.d.ts CHANGED
@@ -2,5 +2,5 @@ import { Hono } from "hono";
2
2
  import { type AuthEnv } from "./authenticate.js";
3
3
  import { type AppAuthConfig } from "./config.js";
4
4
  import type { Session } from "./contract.js";
5
- export declare function issueSession<E>(config: AppAuthConfig<E>, env: E, userId: string, installId: string, at: number): Promise<Session>;
5
+ export declare function issueSession<E>(config: AppAuthConfig<E>, env: E, userId: string, installId: string, at: number, previousUserId?: string | null): Promise<Session>;
6
6
  export declare function authRoutes<E extends object>(config: AppAuthConfig<E>): Hono<AuthEnv<E>>;
package/dist/routes.js CHANGED
@@ -45,11 +45,25 @@ function firebaseUnavailable(c) {
45
45
  return fail(c, 503, "firebase_unavailable", "could not exchange the Firebase refresh token now; keep it and retry later");
46
46
  }
47
47
  const nothingToConsume = async () => true;
48
- export async function issueSession(config, env, userId, installId, at) {
48
+ async function personFor(config, env, issued) {
49
+ const hook = config.hooks?.onSessionIssued;
50
+ if (!hook)
51
+ return null;
52
+ try {
53
+ return (await hook(issued, env)) ?? null;
54
+ }
55
+ catch (err) {
56
+ console.error(JSON.stringify({ msg: "app_auth_session_hook_failed", err: String(err).slice(0, 300) }));
57
+ return null;
58
+ }
59
+ }
60
+ export async function issueSession(config, env, userId, installId, at, previousUserId = null) {
49
61
  const db = config.db(env);
50
62
  const device = await registerDevice(db, userId, installId, at);
51
63
  const access = await signAccessToken(parseTokenSecrets(config.tokenSecrets(env)), config.app, { userId, deviceId: device.deviceId }, at, config.accessTokenTtlMs ?? DEFAULT_ACCESS_TOKEN_TTL_MS);
52
- return { user: await sessionUser(db, userId), ...access, refreshToken: device.refreshToken };
64
+ const session = { user: await sessionUser(db, userId), ...access, refreshToken: device.refreshToken };
65
+ const person = await personFor(config, env, { userId, installId, previousUserId: previousUserId === userId ? null : previousUserId });
66
+ return person === null ? session : { ...session, appgrowstack: person };
53
67
  }
54
68
  export function authRoutes(config) {
55
69
  const app = new Hono();
@@ -60,7 +74,17 @@ export function authRoutes(config) {
60
74
  async function accessFor(env, userId, deviceId, at) {
61
75
  return signAccessToken(keyring(env), config.app, { userId, deviceId }, at, ttl);
62
76
  }
63
- const newSession = (env, userId, installId, at) => issueSession(config, env, userId, installId, at);
77
+ const newSession = (env, userId, installId, at, previousUserId = null) => issueSession(config, env, userId, installId, at, previousUserId);
78
+ async function anonymousBearerUser(c, signedIn) {
79
+ const token = bearerToken(c);
80
+ if (!token)
81
+ return null;
82
+ const current = await resolveBearer(config, c.env, token, { allowLegacy: false });
83
+ if (!ownsAccount(current) || current.userId === signedIn)
84
+ return null;
85
+ const user = await sessionUser(config.db(c.env), current.userId);
86
+ return user.linkedProviders.includes("anonymous") ? current.userId : null;
87
+ }
64
88
  const anonymousEnabled = (env) => fromEnv(config.anonymous, env) ?? true;
65
89
  async function expectedNonce(env, value) {
66
90
  const raw = nonEmptyString(value, MAX_NONCE);
@@ -117,7 +141,7 @@ export function authRoutes(config) {
117
141
  return fail(c, 404, "account_not_found", `no account uses this ${provider} account`, { provider });
118
142
  if (!(await consume()))
119
143
  return codeAlreadyUsed();
120
- return c.json(await newSession(c.env, owner, installId, at));
144
+ return c.json(await newSession(c.env, owner, installId, at, await anonymousBearerUser(c, owner)));
121
145
  }
122
146
  const token = bearerToken(c);
123
147
  if (token) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@appgrowstack/app-auth",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "type": "module",
5
5
  "description": "アプリの Worker が自分で user_id を発行し、Apple・Google・古い Firebase のトークンを確かめてセッションを返す",
6
6
  "license": "MIT",