Supabase, 자체 웹 푸시, 설정 파일을 구성하여 TeamBro를 완벽하게 활용하세요.
TeamBro를 실행하기 전에 필수 설정 파일을 생성해야 합니다.
config 폴더를 생성하고 conf.info 파일을 만듭니다:
config/conf.info 파일 내용:
// ==================== TeamBro 설정 파일 ====================
// 이 파일에는 민감한 정보가 포함되어 있습니다.
// .gitignore에 추가하여 버전 관리에서 제외하는 것을 권장합니다.
const APP_CONFIG = {
// 운영 도메인
productionDomain: 'your-domain.com',
// Supabase 설정
supabase: {
url: 'https://your-project-id.supabase.co',
anonKey: 'your-supabase-anon-key'
},
// 푸시 알림 키는 여기에 넣지 않습니다(이 파일은 브라우저에 공개됨).
// VAPID 키·발송 비밀값은 서버의 api/push-config.php 에 둡니다(3. 웹 푸시 설정 참고).
// 슈퍼관리자 설정
superAdmin: {
id: 'superadmin' // super_admin 테이블의 id와 일치해야 함
}
};
config/conf.info 파일을 .gitignore에 추가하세요:
# .gitignore
config/conf.info
Supabase는 실시간 데이터베이스로 사용됩니다. 무료 플랜으로 시작할 수 있습니다.
supabase.com에서 계정을 만들고 새 프로젝트를 생성합니다.
프로젝트 이름과 데이터베이스 비밀번호를 설정하세요.
SQL Editor에서 다음 SQL을 실행하여 필요한 테이블을 생성합니다:
-- ==================== 기본 테이블 ====================
-- users 테이블
CREATE TABLE users (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
color TEXT DEFAULT '#4f8cff',
role TEXT DEFAULT 'member',
groups JSONB DEFAULT '[]'::jsonb,
password TEXT,
email TEXT,
push_token JSONB DEFAULT '[]'::jsonb,
"order" INTEGER DEFAULT 0,
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- tasks 테이블
CREATE TABLE tasks (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
description TEXT,
status TEXT DEFAULT 'todo',
priority TEXT DEFAULT 'medium',
assignees JSONB DEFAULT '[]'::jsonb,
managers JSONB DEFAULT '[]'::jsonb,
start_date DATE,
due_date DATE,
progress INTEGER DEFAULT 0,
created_by TEXT,
parent_id TEXT,
notion_url TEXT,
slide_url TEXT,
history JSONB DEFAULT '[]'::jsonb,
"order" INTEGER DEFAULT 0,
gantt_order INTEGER DEFAULT 0,
is_public BOOLEAN DEFAULT true,
followers JSONB DEFAULT '[]'::jsonb,
task_type TEXT DEFAULT 'general',
custom_fields JSONB DEFAULT '{}'::jsonb,
archived BOOLEAN DEFAULT false,
archived_at TIMESTAMPTZ,
completed_at TIMESTAMPTZ,
reactions JSONB DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- comments 테이블
CREATE TABLE comments (
id TEXT PRIMARY KEY,
task_id TEXT NOT NULL,
user_id TEXT NOT NULL,
content TEXT NOT NULL,
parent_id TEXT,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ,
reactions JSONB DEFAULT '{}'::jsonb
);
-- notifications 테이블
CREATE TABLE notifications (
id TEXT PRIMARY KEY,
type TEXT NOT NULL,
user_id TEXT NOT NULL,
from_user_id TEXT,
task_id TEXT,
task_title TEXT,
preview TEXT,
read BOOLEAN DEFAULT FALSE,
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- ==================== 태스크 종류 관리 ====================
-- task_types 테이블
CREATE TABLE task_types (
id TEXT PRIMARY KEY,
label TEXT NOT NULL,
description TEXT,
color TEXT DEFAULT '#4f8cff',
"order" INTEGER DEFAULT 0,
active BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- custom_field_definitions 테이블
CREATE TABLE custom_field_definitions (
id TEXT PRIMARY KEY,
field_key TEXT NOT NULL UNIQUE,
label TEXT NOT NULL,
field_type TEXT NOT NULL,
options JSONB DEFAULT '[]'::jsonb,
placeholder TEXT,
required BOOLEAN DEFAULT false,
"order" INTEGER DEFAULT 0,
active BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- task_type_fields 테이블 (매핑)
CREATE TABLE task_type_fields (
id TEXT PRIMARY KEY,
task_type_id TEXT NOT NULL REFERENCES task_types(id) ON DELETE CASCADE,
field_id TEXT NOT NULL REFERENCES custom_field_definitions(id) ON DELETE CASCADE,
"order" INTEGER DEFAULT 0,
required BOOLEAN DEFAULT false,
created_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(task_type_id, field_id)
);
-- 기본 태스크 종류 데이터
INSERT INTO task_types (id, label, description, color, "order") VALUES
('general', '일반', '일반적인 태스크', '#6366f1', 0),
('development', '개발', '개발 관련 태스크', '#22c55e', 1),
('design', '디자인', '디자인 작업', '#a855f7', 2),
('meeting', '회의', '회의 및 미팅', '#f59e0b', 3),
('bug', '버그', '버그 수정', '#ef4444', 4);
-- ==================== 권한 관리 ====================
-- role_permissions 테이블
CREATE TABLE role_permissions (
id TEXT PRIMARY KEY,
role TEXT NOT NULL UNIQUE,
can_manage_task_types BOOLEAN DEFAULT false,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
INSERT INTO role_permissions (id, role, can_manage_task_types) VALUES
('perm-admin', 'admin', true),
('perm-member', 'member', false),
('perm-viewer', 'viewer', false);
-- ==================== 슈퍼관리자 (별도 테이블) ====================
CREATE TABLE super_admin (
id TEXT PRIMARY KEY DEFAULT 'superadmin',
username TEXT NOT NULL UNIQUE,
password TEXT NOT NULL,
name TEXT DEFAULT '관리자',
color TEXT DEFAULT '#ef4444',
role TEXT DEFAULT 'admin',
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- 슈퍼관리자 계정 — 비밀번호는 설치하는 사람이 직접 정한다(기본값을 쓰지 말 것).
-- bcrypt 해시로 넣는다. 예: SELECT extensions.crypt('<직접 정한 긴 비밀번호>', extensions.gen_salt('bf', 10));
INSERT INTO super_admin (id, username, password, name, color, role) VALUES
('superadmin', 'superadmin', '<직접 정한 비밀번호의 bcrypt 해시>', '관리자', '#ef4444', 'admin');
-- ==================== 앱 설정 ====================
CREATE TABLE app_config (
id TEXT PRIMARY KEY DEFAULT 'main',
supabase_url TEXT,
supabase_anon_key TEXT,
default_task_public BOOLEAN DEFAULT true,
updated_at TIMESTAMPTZ DEFAULT NOW(),
updated_by TEXT
);
-- ==================== RLS 비활성화 ====================
ALTER TABLE users DISABLE ROW LEVEL SECURITY;
ALTER TABLE tasks DISABLE ROW LEVEL SECURITY;
ALTER TABLE comments DISABLE ROW LEVEL SECURITY;
ALTER TABLE notifications DISABLE ROW LEVEL SECURITY;
ALTER TABLE task_types DISABLE ROW LEVEL SECURITY;
ALTER TABLE custom_field_definitions DISABLE ROW LEVEL SECURITY;
ALTER TABLE task_type_fields DISABLE ROW LEVEL SECURITY;
ALTER TABLE role_permissions DISABLE ROW LEVEL SECURITY;
ALTER TABLE super_admin DISABLE ROW LEVEL SECURITY;
ALTER TABLE app_config DISABLE ROW LEVEL SECURITY;
RLS를 비활성화하면 Supabase 대시보드에 보안 경고가 표시됩니다. 이를 해결하려면:
-- 모든 테이블에 대해 RLS 활성화 + 전체 접근 허용 정책 추가
-- (보안 경고를 없애면서도 현재 동작 유지)
ALTER TABLE users ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Allow all access" ON users FOR ALL USING (true) WITH CHECK (true);
ALTER TABLE tasks ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Allow all access" ON tasks FOR ALL USING (true) WITH CHECK (true);
ALTER TABLE comments ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Allow all access" ON comments FOR ALL USING (true) WITH CHECK (true);
ALTER TABLE notifications ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Allow all access" ON notifications FOR ALL USING (true) WITH CHECK (true);
ALTER TABLE task_types ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Allow all access" ON task_types FOR ALL USING (true) WITH CHECK (true);
ALTER TABLE custom_field_definitions ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Allow all access" ON custom_field_definitions FOR ALL USING (true) WITH CHECK (true);
ALTER TABLE task_type_fields ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Allow all access" ON task_type_fields FOR ALL USING (true) WITH CHECK (true);
ALTER TABLE role_permissions ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Allow all access" ON role_permissions FOR ALL USING (true) WITH CHECK (true);
ALTER TABLE super_admin ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Allow all access" ON super_admin FOR ALL USING (true) WITH CHECK (true);
ALTER TABLE app_config ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Allow all access" ON app_config FOR ALL USING (true) WITH CHECK (true);
※ 위 정책은 "모든 접근 허용"이므로 기존 동작과 동일하지만, Supabase 보안 경고가 사라집니다.
Database > Replication 메뉴에서 각 테이블의 Realtime을 활성화합니다:
※ super_admin, app_config 테이블은 Realtime 불필요
Settings > API에서 다음 값을 확인하고 conf.info에 입력합니다:
| 항목 | 위치 | conf.info 설정 |
|---|---|---|
| Project URL | API Settings > URL | supabase.url |
| anon (public) key | API Settings > Project API keys | supabase.anonKey |
| Project Reference ID | Settings > General | Edge Function 배포 시 사용 |
TeamBro는 외부 푸시 서비스 없이 자체 웹 푸시(VAPID 표준)로 알림을 보냅니다. 브라우저는 서비스워커로 구독하고, 발송은 Supabase Edge Function이 웹 서버(cafe24)의 PHP 발송기를 불러 처리합니다. 안드로이드 앱(APK)은 FCM으로 받습니다.
[구독] 로그인 → js/pwa-push.js
→ /sw-push.js 등록('/' 스코프) + VAPID 공개키로 구독
→ api/push-sub.php (로그인 JWT 확인 후 저장, push-config.php 의 store 파일)
[발송] 알림 발생 → Edge Function send-push-notification (호출자 JWT 확인)
→ api/send-push.php (sendSecret 확인, VAPID 서명 + aes128gcm 암호화: api/push-lib.php)
→ 브라우저 푸시 서비스 → sw-push.js 가 알림 표시
→ 안드로이드 앱(APK)은 api/fcm-lib.php 로 FCM 발송
푸시 키는 conf.info가 아니라 서버의 api/push-config.php에 둡니다. 이 파일은 웹에 공개되지 않으며, 배포 스크립트도 이 파일은 올리지 않으므로 서버에서 직접 관리합니다.
| 키 | 설명 |
|---|---|
vapidPublic | VAPID 공개키(base64url). 브라우저가 api/push-sub.php?action=public으로 받아 구독에 사용 |
vapidPrivatePem | VAPID 비밀키(PEM). 발송 서명용, 서버 밖으로 내보내지 않음 |
subject | 연락처(예: mailto:admin@your-domain.com) |
sendSecret | 발송 비밀값. Edge Function 비밀값 PUSH_SEND_SECRET과 같아야 함 |
store | 구독 저장 파일 경로(예: api/_private/push-subs.json) |
<?php
// api/push-config.php (서버 전용)
return [
'vapidPublic' => '<VAPID 공개키 base64url>',
'vapidPrivatePem' => "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n",
'subject' => 'mailto:admin@your-domain.com',
'sendSecret' => '<길고 임의의 문자열>',
'store' => __DIR__ . '/_private/push-subs.json',
];
키는 api/push-lib.php의 vapid_generate()로 만들면 위 형식(공개키 + PEM 비밀키) 그대로 나옵니다:
php -r "require 'api/push-lib.php'; print_r(vapid_generate());"
※ webpush/generate-vapid.mjs(Node)도 키쌍을 만들지만 비밀키를 PEM이 아닌 값(JWK d)으로 저장하므로, push-config.php에는 PHP 방식이 간단합니다.
이미 등록된 구독이 모두 무효가 되어 사용자가 알림을 다시 켜야 합니다. 같은 서버를 옮길 때는 push-config.php와 구독 저장 파일을 그대로 옮기세요. api/_private/는 .htaccess(Require all denied)로 웹 접근이 막혀 있어야 합니다.
js/pwa-push.js가 로그인 때 /sw-push.js를 등록하므로 이 파일은 반드시 사이트 루트에 있어야 '/' 스코프 전체에서 알림을 받습니다. HTTPS에서만 동작합니다.
send-push-notification은 sendSecret을 붙여 PHP 발송기를 부릅니다. 비밀값은 브라우저에 노출되지 않습니다.
| 비밀값 | 값 |
|---|---|
PUSH_SEND_SECRET | push-config.php의 sendSecret과 같은 값 (필수) |
PUSH_SENDER_URL | PHP 발송기 주소 (선택, 기본 https://taskflow.mycafe24.com/api/send-push.php) |
supabase secrets set PUSH_SEND_SECRET=<push-config.php 의 sendSecret>
함수 배포는 4. Edge Function 배포를 참고하세요.
안드로이드 앱(APK)은 웹 푸시 대신 FCM으로 받습니다. Firebase 서비스계정 파일을 api/_private/fcm-service-account.json에 두면 api/fcm-lib.php가 발송하고, 앱 기기 토큰은 api/_private/fcm-tokens.json에 저장됩니다.
https://your-domain.com/push-test.html을 엽니다.| 증상 | 원인 | 해결 |
|---|---|---|
| 구독 자체가 안 됨 | HTTP 접속 또는 sw-push.js가 루트에 없음 |
HTTPS 주소인지, https://도메인/sw-push.js가 열리는지 확인 |
구독 실패 (no-vapid-key) |
push-config.php 없음 또는 vapidPublic 비어 있음 |
/api/push-sub.php?action=public이 publicKey를 돌려주는지 확인 |
구독 저장 401 (login-required) |
로그인 토큰 없음·만료 | 다시 로그인한 뒤 알림 켜기 |
| 발송 500 "PUSH_SEND_SECRET 미설정" | Edge Function 비밀값 없음 | PUSH_SEND_SECRET 설정 후 함수 재배포 |
| 발송 403 (unauthorized) | PUSH_SEND_SECRET ≠ sendSecret |
두 값을 똑같이 맞춤 |
| 알림 켜기를 눌러도 반응 없음 | 브라우저가 이 사이트 알림을 차단(denied) | 주소창 자물쇠 → 알림 → 허용 후 새로고침 |
sw-push.js가 루트에 있는지 확인api/push-config.php(VAPID 키·sendSecret·store)가 있는지 확인api/_private/가 웹에서 열리지 않는지 확인PUSH_SEND_SECRET = sendSecret인지 확인push-test.html에서 직접 발송·실제 경로 발송이 모두 도착하는지 확인푸시 알림 발송과 로그인에 쓰는 Supabase Edge Function을 배포합니다.
푸시 발송 함수는 저장소에 있는 코드를 그대로 배포합니다. 여러 파일로 나뉘어 있어 대시보드 에디터에 붙여넣는 방식은 쓰지 않습니다.
하는 일: 호출자 확인(사용자 로그인 JWT 또는 봇의 서비스 키) → 받는 사람·업무 열람 권한 확인 → sendSecret을 붙여 api/send-push.php 호출. 알림 링크는 같은 서비스 주소(코드의 ORIGIN)나 상대경로만 허용합니다.
3. 웹 푸시 설정의 PUSH_SEND_SECRET(필수)과 PUSH_SENDER_URL(선택)이 프로젝트 비밀값에 들어 있어야 합니다. 없으면 함수가 500("PUSH_SEND_SECRET 미설정")을 돌려줍니다.
Supabase CLI가 있으면:
supabase functions deploy send-push-notification --no-verify-jwt --project-ref your-project-ref
CLI가 없으면 Management API 배포 스크립트를 씁니다(루트 .env의 SUPABASE_ACCESS_TOKEN·SUPABASE_PROJECT_REF 사용):
node build/deploy-function.mjs send-push-notification
"Verify JWT"는 OFF입니다. 봇이 보내는 서비스 키까지 받아야 하므로 게이트웨이 검사 대신 함수가 직접 호출자를 확인합니다(익명 키만으로는 401).
배포 후 URL:
https://your-project-ref.supabase.co/functions/v1/send-push-notification
Supabase Dashboard에서 Edge Function을 생성합니다:
auth-login401 Unauthorized 또는 CORS 에러가 발생합니다. auth-login은 로그인 전에 호출되므로 JWT 검증을 비활성화해야 합니다.
// Edge Function: auth-login
// 로그인 시 비밀번호 검증 + Supabase Auth 세션 생성
import { serve } from "https://deno.land/std@0.168.0/http/server.ts"
import { createClient } from "https://esm.sh/@supabase/supabase-js@2"
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};
const SALT = 'kjhbond';
function decryptPassword(encryptedBase64: string): string {
const decoded = atob(encryptedBase64);
let decrypted = '';
for (let i = 0; i < decoded.length; i++) {
decrypted += String.fromCharCode(
decoded.charCodeAt(i) ^ SALT.charCodeAt(i % SALT.length)
);
}
return decrypted;
}
function verifyPassword(input: string, stored: string): boolean {
if (!stored) return false;
try {
const decrypted = decryptPassword(stored);
if (decrypted && decrypted !== stored) {
return input === decrypted;
}
} catch (_e) {}
return input === stored;
}
function snakeToCamel(obj: Record<string, any>): Record<string, any> {
const result: Record<string, any> = {};
for (const key of Object.keys(obj)) {
const camelKey = key.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
result[camelKey] = obj[key];
}
return result;
}
serve(async (req) => {
if (req.method === 'OPTIONS') {
return new Response('ok', { headers: corsHeaders });
}
try {
const { username, password } = await req.json();
if (!username || !password) {
return new Response(
JSON.stringify({ success: false, error: '아이디와 비밀번호를 입력해주세요.' }),
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 400 }
);
}
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const serviceRoleKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
const adminClient = createClient(supabaseUrl, serviceRoleKey, {
auth: { autoRefreshToken: false, persistSession: false }
});
let userId: string | null = null;
let authEmail: string = '';
let userRecord: Record<string, any> | null = null;
let isSuperAdmin = false;
// 1. super_admin 테이블 체크
const { data: superAdmins } = await adminClient
.from('super_admin').select('*').eq('username', username);
if (superAdmins && superAdmins.length > 0) {
const admin = superAdmins[0];
if (verifyPassword(password, admin.password)) {
userId = admin.id;
authEmail = `${admin.id}@taskflow.local`;
isSuperAdmin = true;
userRecord = {
id: admin.id, name: admin.name, username: admin.username,
color: admin.color || '#ef4444', role: admin.role || 'admin',
groups: ['관리자']
};
}
}
// 2. users 테이블 체크
if (!userId) {
const { data: users } = await adminClient
.from('users').select('*').eq('name', username);
if (users && users.length > 0) {
const matchedUser = users.find((u: any) => verifyPassword(password, u.password));
if (matchedUser) {
const camelUser = snakeToCamel(matchedUser);
userId = camelUser.id as string;
authEmail = `${userId}@taskflow.local`;
userRecord = camelUser;
}
}
}
if (!userId || !userRecord) {
return new Response(
JSON.stringify({ success: false, error: '아이디 또는 비밀번호가 올바르지 않습니다.' }),
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 401 }
);
}
// 3. Supabase Auth 세션 생성
const { data: quickSignIn } = await adminClient.auth.signInWithPassword({
email: authEmail, password: password
});
if (quickSignIn?.session) {
return new Response(
JSON.stringify({
success: true,
session: {
access_token: quickSignIn.session.access_token,
refresh_token: quickSignIn.session.refresh_token,
expires_in: quickSignIn.session.expires_in,
expires_at: quickSignIn.session.expires_at,
},
user: userRecord, isSuperAdmin
}),
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
);
}
// Auth 계정 생성 (첫 로그인)
const { data: createData, error: createError } = await adminClient.auth.admin.createUser({
email: authEmail, password: password,
email_confirm: true,
user_metadata: { taskflow_user_id: userId, is_super_admin: isSuperAdmin }
});
if (createData?.user) {
const { data: newSignIn } = await adminClient.auth.signInWithPassword({
email: authEmail, password: password
});
if (newSignIn?.session) {
return new Response(
JSON.stringify({
success: true,
session: {
access_token: newSignIn.session.access_token,
refresh_token: newSignIn.session.refresh_token,
expires_in: newSignIn.session.expires_in,
expires_at: newSignIn.session.expires_at,
},
user: userRecord, isSuperAdmin
}),
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
);
}
}
// 비밀번호 불일치로 계정이 이미 존재하는 경우
if (createError && createError.message?.includes('already been registered')) {
const { data: listData } = await adminClient.auth.admin.listUsers();
const existingAuthUser = listData?.users?.find((u: any) => u.email === authEmail);
if (existingAuthUser) {
await adminClient.auth.admin.updateUserById(existingAuthUser.id, { password: password });
const { data: retrySignIn, error: retryError } = await adminClient.auth.signInWithPassword({
email: authEmail, password: password
});
if (retrySignIn?.session) {
return new Response(
JSON.stringify({
success: true,
session: {
access_token: retrySignIn.session.access_token,
refresh_token: retrySignIn.session.refresh_token,
expires_in: retrySignIn.session.expires_in,
expires_at: retrySignIn.session.expires_at,
},
user: userRecord, isSuperAdmin
}),
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
);
}
return new Response(
JSON.stringify({ success: false, error: retryError?.message || '로그인에 실패했습니다.' }),
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 500 }
);
}
}
return new Response(
JSON.stringify({ success: false, error: 'Auth 계정 처리에 실패했습니다.' }),
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 500 }
);
} catch (error) {
console.error('auth-login ERROR:', error.message);
return new Response(
JSON.stringify({ success: false, error: error.message }),
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 500 }
);
}
});
Supabase Dashboard에서 두 번째 Edge Function을 생성합니다:
auth-update-password// Edge Function: auth-update-password
// 비밀번호 변경 시 Supabase Auth 동기화
import { serve } from "https://deno.land/std@0.168.0/http/server.ts"
import { createClient } from "https://esm.sh/@supabase/supabase-js@2"
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};
serve(async (req) => {
if (req.method === 'OPTIONS') {
return new Response('ok', { headers: corsHeaders });
}
try {
const { userId, newPassword } = await req.json();
if (!userId || !newPassword) {
return new Response(
JSON.stringify({ success: false, error: 'userId and newPassword are required' }),
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 400 }
);
}
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const serviceRoleKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
const adminClient = createClient(supabaseUrl, serviceRoleKey, {
auth: { autoRefreshToken: false, persistSession: false }
});
const authEmail = `${userId}@taskflow.local`;
const { data: listData } = await adminClient.auth.admin.listUsers();
const existingAuthUser = listData?.users?.find((u: any) => u.email === authEmail);
if (existingAuthUser) {
const { error: updateError } = await adminClient.auth.admin.updateUserById(
existingAuthUser.id, { password: newPassword }
);
if (updateError) {
return new Response(
JSON.stringify({ success: false, error: updateError.message }),
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 500 }
);
}
return new Response(
JSON.stringify({ success: true }),
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
);
}
return new Response(
JSON.stringify({ success: true, message: 'Auth user not found, will be created on next login' }),
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
);
} catch (error) {
console.error('auth-update-password ERROR:', error.message);
return new Response(
JSON.stringify({ success: false, error: error.message }),
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 500 }
);
}
});
| 함수명 | 용도 | Verify JWT |
|---|---|---|
send-push-notification | 푸시 발송(자체 웹푸시 중계) | OFF (함수가 직접 호출자 확인) |
auth-login | 로그인 시 Supabase Auth 세션 생성 | OFF (필수!) |
auth-update-password | 비밀번호 변경 시 Auth 동기화 | ON |
TeamBro는 자동으로 supabase.url + '/functions/v1/함수명' 형식으로 Edge Function을 호출합니다.
conf.info의 supabase.url만 올바르게 설정되면 됩니다.
PWA(Progressive Web App)로 설치 가능하도록 manifest 파일을 설정합니다.
프로젝트 루트에 manifest.json 파일을 생성합니다:
{
"name": "TeamBro",
"short_name": "TeamBro",
"description": "팀 프로젝트 관리 앱",
"start_url": "/m.html",
"display": "standalone",
"background_color": "#1a1a2e",
"theme_color": "#1a1a2e",
"orientation": "portrait-primary",
"icons": [
{
"src": "/icon.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any maskable"
},
{
"src": "/icon.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any maskable"
}
]
}
PC 버전을 위해 별도의 manifest-pc.json을 만들 수 있습니다:
{
"name": "TeamBro",
"short_name": "TeamBro",
"description": "팀 프로젝트 관리 앱",
"start_url": "/main.html",
"display": "standalone",
"background_color": "#1a1a2e",
"theme_color": "#1a1a2e",
"icons": [
{
"src": "/icon.png",
"sizes": "192x192",
"type": "image/png"
}
]
}
루트에 icon.png 파일이 필요합니다 (192x192 이상 권장):
https://로 시작하는지 확인PUSH_SEND_SECRET이 sendSecret과 같은지 확인push-test.html로 직접 발송·실제 경로 발송을 시험 (3. 웹 푸시 설정 참고)https://에서만 웹 푸시가 작동합니다 (localhost 제외)super_admin 테이블의 id 값과 conf.info의 superAdmin.id가 일치하는지 확인'superadmin'으로 설정supabase functions deploy send-push-notification --no-verify-jwt --project-ref your-project-ref
기존에 TeamBro를 사용 중이라면 아래 SQL을 실행하여 업그레이드하세요.
기존 id가 'user-admin'인 경우 'superadmin'으로 변경:
-- 기존 데이터 삭제 후 재삽입
DELETE FROM super_admin WHERE id = 'user-admin';
INSERT INTO super_admin (id, username, password, name, color, role) VALUES
('superadmin', 'superadmin', '<직접 정한 비밀번호의 bcrypt 해시>', '관리자', '#ef4444', 'admin')
ON CONFLICT (id) DO UPDATE SET
username = EXCLUDED.username,
name = EXCLUDED.name,
updated_at = NOW();
-- 기본 태스크 공개 여부 설정 컬럼 추가
ALTER TABLE app_config ADD COLUMN IF NOT EXISTS default_task_public BOOLEAN DEFAULT true;
-- 최근 추가된 컬럼들
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS notion_url TEXT;
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS archived BOOLEAN DEFAULT false;
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS archived_at TIMESTAMPTZ;
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS managers JSONB DEFAULT '[]'::jsonb;
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS completed_at TIMESTAMPTZ;
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS followers JSONB DEFAULT '[]'::jsonb;
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS is_public BOOLEAN DEFAULT true;
DB의 super_admin.id 값과 conf.info의 superAdmin.id 값이 반드시 일치해야 합니다.
기본값: 둘 다 'superadmin'
TeamBro를 다른 도메인에 추가 배포할 때 필요한 작업입니다.
| 서버명 | 도메인 | DB | 웹 푸시 |
|---|---|---|---|
| 경욱 | withwe22.mycafe24.com | 공유 or 분리 | 서버별 push-config.php |
| 정환 | taskflow.mycafe24.com | 공유 or 분리 | 서버별 push-config.php |
newtask.mycafe24.com)| DB 공유 (같은 Supabase) | DB 분리 (새 Supabase) | |
|---|---|---|
| 장점 | 설정 간단, 데이터 공유 | 완전 독립, 보안 분리 |
| 단점 | 모든 서버가 같은 데이터 접근 | 테이블/함수 모두 새로 생성 |
| conf.info | supabase 설정 동일 | 새 url, anonKey 필요 |
| Edge Function | 기존 함수 공유 가능* | 새로 배포 필요 |
* 단, Edge Function의 발송기 주소(PUSH_SENDER_URL)·비밀값(PUSH_SEND_SECRET)과 코드의 알림 링크 도메인(ORIGIN)이 서버마다 다르므로, DB를 공유해도 Edge Function은 서버별로 별도 배포가 필요할 수 있습니다.
super_admin 레코드 생성send-push-notification, auth-login, auth-update-password)웹 푸시 구독은 도메인(브라우저 출처)마다 따로 생기고, 구독 목록은 각 서버의 저장 파일에 쌓입니다. 새 서버에는 그 서버용 api/push-config.php가 있어야 하며, Edge Function도 그 서버의 발송기와 같은 sendSecret을 써야 합니다.
api/push-config.php와 구독 저장 파일(store 경로, 예: api/_private/push-subs.json)을 그대로 복사합니다. VAPID 키가 같아야 기존 구독이 유지됩니다.vapid_generate()로 새 VAPID 키를 만들고 새 sendSecret을 정해 push-config.php를 작성합니다(3. 웹 푸시 설정 참고).api/_private/에 .htaccess(Require all denied)가 있는지 확인합니다.api/_private/fcm-service-account.json도 옮깁니다.const APP_CONFIG = {
productionDomain: 'newtask.mycafe24.com', // ← 새 도메인
supabase: {
url: 'https://xxxx.supabase.co', // 공유 시 기존값 / 분리 시 새 프로젝트
anonKey: 'your-anon-key'
},
// 푸시 키는 conf.info 가 아니라 서버의 api/push-config.php 에 둡니다(Step 3).
superAdmin: {
id: 'superadmin'
}
};
manifest-{이름}.json (모바일용):
{
"name": "TeamBro Mobile",
"short_name": "TeamBro",
"description": "프로젝트 관리 시스템",
"start_url": "https://newtask.mycafe24.com/m.html",
"scope": "https://newtask.mycafe24.com/",
"display": "standalone",
"background_color": "#8a55f7",
"theme_color": "#8a55f7",
"orientation": "portrait",
"permissions": ["notifications"],
"icons": [
{ "src": "icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" },
{ "src": "icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "maskable" },
{ "src": "icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" },
{ "src": "icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
]
}
manifest-pc_{이름}.json (PC용):
{
"name": "TeamBro",
"short_name": "TeamBro",
"description": "프로젝트 관리 시스템",
"start_url": "https://newtask.mycafe24.com/main.html",
"scope": "https://newtask.mycafe24.com/",
"display": "standalone",
"background_color": "#1a1a2e",
"theme_color": "#1a1a2e",
"orientation": "any",
"icons": [
{ "src": "icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" },
{ "src": "icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "maskable" },
{ "src": "icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" },
{ "src": "icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
]
}
새 서버에 업로드할 HTML 파일에서 manifest 경로를 변경합니다:
<!-- m.html (모바일) -->
<link rel="manifest" href="manifest-{이름}.json">
<!-- main.html (PC) -->
<link rel="manifest" href="manifest-pc_{이름}.json">
DB를 공유하는 경우 기존 함수가 이미 있으므로, send-push-notification만 새 서버에 맞게 설정·배포하면 됩니다.
DB를 분리한 경우 3개 모두 새로 배포해야 합니다.
| 함수명 | Verify JWT | 수정 필요 사항 |
|---|---|---|
send-push-notification |
OFF (함수가 직접 호출자 확인) | 비밀값 PUSH_SEND_SECRET·PUSH_SENDER_URL 설정 + 코드의 ORIGIN 도메인 (섹션 4 참고) |
auth-login |
OFF (필수!) | 코드 변경 없음 (그대로 복사) |
auth-update-password |
ON | 코드 변경 없음 (그대로 복사) |
# 1. 발송 비밀값 → 새 서버 push-config.php 의 sendSecret 과 같은 값
supabase secrets set PUSH_SEND_SECRET=<새 서버 sendSecret>
# 2. PHP 발송기 주소 → 새 도메인 (기본값은 taskflow.mycafe24.com)
supabase secrets set PUSH_SENDER_URL=https://newtask.mycafe24.com/api/send-push.php
// 3. index.ts 의 알림 링크 도메인 → 새 도메인 (다른 주소의 링크는 막힘)
const ORIGIN = 'https://newtask.mycafe24.com';
알림 아이콘은 sw-push.js가 상대경로(/icon.png)로 쓰므로 바꿀 필요가 없습니다.
auth-login, auth-update-password의 전체 코드는 섹션 4를 참고하세요.
FTP로 새 서버에 업로드할 파일 목록:
| # | 항목 | 확인 |
|---|---|---|
| 1 | HTTPS(SSL) 인증서 적용됨 | |
| 2 | conf.info - productionDomain이 새 도메인 | |
| 3 | conf.info - Supabase 키 올바름 | |
| 4 | 서버에 api/push-config.php(VAPID 키·sendSecret·store) 있음 | |
| 5 | Edge Function 비밀값 PUSH_SEND_SECRET = push-config.php의 sendSecret | |
| 6 | Edge Function 비밀값 PUSH_SENDER_URL = 새 도메인의 api/send-push.php | |
| 7 | Edge Function 코드의 ORIGIN = 새 도메인 | |
| 8 | sw-push.js 루트에 존재 + push-test.html 시험 통과 | |
| 9 | manifest의 start_url, scope = 새 도메인 | |
| 10 | m.html, main.html의 manifest 경로 정확함 | |
| 11 | DB 분리 시: 테이블 생성 + super_admin 레코드 추가 | |
| 12 | DB 분리 시: RLS 정책 적용 (보안 경고 해결) | |
| 13 | DB 분리 시: Realtime 활성화 |
no-vapid-key). 같은 서버를 옮길 땐 기존 키·구독 파일을 그대로 옮겨야 구독이 유지됨!sendSecret과 같아야 함!Supabase Dashboard > SQL Editor에서 아래 SQL을 실행합니다:
-- 이메일 연동 설정 테이블
CREATE TABLE IF NOT EXISTS email_integration_config (
id TEXT PRIMARY KEY DEFAULT 'main',
enabled BOOLEAN DEFAULT false,
gmail_client_id TEXT,
gmail_client_secret TEXT,
gmail_refresh_token TEXT,
gmail_target_label TEXT DEFAULT 'INBOX',
aws_access_key_id TEXT,
aws_secret_access_key TEXT,
aws_bedrock_region TEXT DEFAULT 'us-east-1',
default_assignee_id TEXT,
default_status TEXT DEFAULT 'todo',
default_priority TEXT DEFAULT 'medium',
classification_prompt TEXT,
polling_interval_minutes INTEGER DEFAULT 5,
last_sync_at TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- 처리된 이메일 추적 테이블 (중복 방지)
CREATE TABLE IF NOT EXISTS processed_emails (
id TEXT PRIMARY KEY,
task_id TEXT,
gmail_thread_id TEXT,
subject TEXT,
sender TEXT,
processed_at TIMESTAMPTZ DEFAULT NOW(),
classification_result JSONB,
error TEXT
);
-- 동기화 로그 테이블
CREATE TABLE IF NOT EXISTS email_sync_log (
id SERIAL PRIMARY KEY,
run_at TIMESTAMPTZ DEFAULT NOW(),
emails_found INTEGER DEFAULT 0,
tasks_created INTEGER DEFAULT 0,
errors INTEGER DEFAULT 0,
details JSONB,
duration_ms INTEGER
);
-- RLS 비활성화
ALTER TABLE email_integration_config DISABLE ROW LEVEL SECURITY;
ALTER TABLE processed_emails DISABLE ROW LEVEL SECURITY;
ALTER TABLE email_sync_log DISABLE ROW LEVEL SECURITY;
Gmail API 검색 후 ENABLE| 설정 | 값 |
|---|---|
| User Type | External (또는 Internal) |
| App name | TeamBro |
| Scopes 추가 | https://www.googleapis.com/auth/gmail.modify |
| Test users | 사용할 Gmail 주소 추가 (External일 때 필수) |
| 설정 | 값 |
|---|---|
| Application type | Web application |
| 승인된 JavaScript 원본 | https://your-domain.com |
| 승인된 리디렉션 URI | https://your-domain.com (경로 없이, 슬래시 없이) |
"승인된 JavaScript 원본"과 "승인된 리디렉션 URI"는 별개입니다. 두 곳 모두에 도메인을 추가해야 합니다. 설정 반영까지 5분 정도 걸릴 수 있습니다.
이메일 분석에 AWS Bedrock의 Claude 모델을 사용합니다.
Anthropic Claude 모델 액세스 요청{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "bedrock:InvokeModel",
"Resource": "arn:aws:bedrock:us-east-1::foundation-model/anthropic.*"
}]
}
Supabase Dashboard > Edge Functions > Create a new function에서 배포합니다:
gmail-to-task// Supabase Edge Function: Gmail 이메일 → TeamBro Task 자동 생성
import { serve } from "https://deno.land/std@0.168.0/http/server.ts"
import { createClient } from "https://esm.sh/@supabase/supabase-js@2"
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};
// Gmail API 헬퍼
interface GmailTokenResponse { access_token: string; expires_in: number; token_type: string; }
interface GmailMessage { id: string; threadId: string; payload: { headers: Array<{ name: string; value: string }>; parts?: Array<{ mimeType: string; body: { data?: string; size: number }; }>; body?: { data?: string; size: number }; mimeType?: string; }; }
async function refreshGmailToken(clientId: string, clientSecret: string, refreshToken: string): Promise<string> {
const response = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ client_id: clientId, client_secret: clientSecret, refresh_token: refreshToken, grant_type: 'refresh_token' }),
});
if (!response.ok) { throw new Error(`Gmail 토큰 갱신 실패: ${await response.text()}`); }
const data: GmailTokenResponse = await response.json();
return data.access_token;
}
async function listUnreadMessages(accessToken: string, label: string, maxResults: number = 10) {
const query = encodeURIComponent(`is:unread label:${label}`);
const response = await fetch(`https://gmail.googleapis.com/gmail/v1/users/me/messages?q=${query}&maxResults=${maxResults}`, { headers: { 'Authorization': `Bearer ${accessToken}` } });
if (!response.ok) { throw new Error(`Gmail 메시지 목록 조회 실패: ${await response.text()}`); }
const data = await response.json();
return data.messages || [];
}
async function getMessage(accessToken: string, messageId: string): Promise<GmailMessage> {
const response = await fetch(`https://gmail.googleapis.com/gmail/v1/users/me/messages/${messageId}?format=full`, { headers: { 'Authorization': `Bearer ${accessToken}` } });
if (!response.ok) { throw new Error(`Gmail 메시지 조회 실패 (${messageId}): ${await response.text()}`); }
return await response.json();
}
async function markAsRead(accessToken: string, messageId: string): Promise<void> {
await fetch(`https://gmail.googleapis.com/gmail/v1/users/me/messages/${messageId}/modify`, {
method: 'POST', headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ removeLabelIds: ['UNREAD'] }),
});
}
function getHeader(message: GmailMessage, name: string): string {
const header = message.payload.headers.find(h => h.name.toLowerCase() === name.toLowerCase());
return header?.value || '';
}
function getBody(message: GmailMessage): string {
if (message.payload.body?.data) return decodeBase64Url(message.payload.body.data);
if (message.payload.parts) {
const textPart = message.payload.parts.find(p => p.mimeType === 'text/plain');
if (textPart?.body?.data) return decodeBase64Url(textPart.body.data);
const htmlPart = message.payload.parts.find(p => p.mimeType === 'text/html');
if (htmlPart?.body?.data) return stripHtml(decodeBase64Url(htmlPart.body.data));
}
return '';
}
function decodeBase64Url(data: string): string { return atob(data.replace(/-/g, '+').replace(/_/g, '/')); }
function stripHtml(html: string): string {
return html.replace(/<br\s*\/?>/gi, '\n').replace(/<\/p>/gi, '\n').replace(/<\/div>/gi, '\n')
.replace(/<[^>]*>/g, '').replace(/ /g, ' ').replace(/&/g, '&')
.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/\n{3,}/g, '\n\n').trim();
}
// AWS Bedrock API (SigV4 서명)
interface TaskClassification { title: string; description: string; priority: 'high' | 'medium' | 'low'; category: string; }
interface AwsCredentials { accessKeyId: string; secretAccessKey: string; region: string; }
const DEFAULT_CLASSIFICATION_PROMPT = `당신은 이메일을 프로젝트 관리 도구의 태스크로 변환하는 분류기입니다.
이메일을 분석하여 다음 정보를 추출하세요:
- title: 간결한 태스크 제목 (한국어, 50자 이내)
- description: 핵심 내용 요약 (한국어)
- priority: "high" (긴급/장애/버그), "medium" (일반 요청/문의), "low" (참고/보고)
- category: "요청", "버그", "문의", "보고", "기타" 중 하나
JSON만 반환하세요.`;
async function hmacSha256(key: ArrayBuffer | Uint8Array, message: string): Promise<ArrayBuffer> {
const keyBuffer = key instanceof ArrayBuffer ? key : (key as Uint8Array).buffer as ArrayBuffer;
const cryptoKey = await crypto.subtle.importKey('raw', keyBuffer, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
return await crypto.subtle.sign('HMAC', cryptoKey, new TextEncoder().encode(message));
}
async function sha256(data: string): Promise<string> {
const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(data));
return Array.from(new Uint8Array(hash)).map(b => b.toString(16).padStart(2, '0')).join('');
}
async function getSignatureKey(key: string, dateStamp: string, region: string, service: string) {
const kDate = await hmacSha256(new TextEncoder().encode('AWS4' + key), dateStamp);
const kRegion = await hmacSha256(kDate, region);
const kService = await hmacSha256(kRegion, service);
return await hmacSha256(kService, 'aws4_request');
}
async function invokeBedrockModel(credentials: AwsCredentials, modelId: string, requestBody: string): Promise<string> {
const service = 'bedrock';
const host = `bedrock-runtime.${credentials.region}.amazonaws.com`;
const endpoint = `https://${host}/model/${encodeURIComponent(modelId)}/invoke`;
const now = new Date();
const amzDate = now.toISOString().replace(/[:-]|\.\d{3}/g, '');
const dateStamp = amzDate.substring(0, 8);
const payloadHash = await sha256(requestBody);
const canonicalHeaders = `content-type:application/json\nhost:${host}\nx-amz-date:${amzDate}\n`;
const signedHeaders = 'content-type;host;x-amz-date';
const canonicalRequest = `POST\n/model/${encodeURIComponent(modelId)}/invoke\n\n${canonicalHeaders}\n${signedHeaders}\n${payloadHash}`;
const credentialScope = `${dateStamp}/${credentials.region}/${service}/aws4_request`;
const stringToSign = `AWS4-HMAC-SHA256\n${amzDate}\n${credentialScope}\n${await sha256(canonicalRequest)}`;
const signingKey = await getSignatureKey(credentials.secretAccessKey, dateStamp, credentials.region, service);
const signatureBuffer = await hmacSha256(signingKey, stringToSign);
const signature = Array.from(new Uint8Array(signatureBuffer)).map(b => b.toString(16).padStart(2, '0')).join('');
const authHeader = `AWS4-HMAC-SHA256 Credential=${credentials.accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
const response = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Host': host, 'X-Amz-Date': amzDate, 'Authorization': authHeader },
body: requestBody,
});
if (!response.ok) { throw new Error(`Bedrock API 호출 실패 (${response.status}): ${await response.text()}`); }
const result = await response.json();
return result.content?.[0]?.text || result.completion || '{}';
}
async function classifyEmail(awsCredentials: AwsCredentials, subject: string, sender: string, body: string, customPrompt?: string): Promise<TaskClassification> {
const systemPrompt = customPrompt || DEFAULT_CLASSIFICATION_PROMPT;
const truncatedBody = body.length > 3000 ? body.substring(0, 3000) + '\n...(이하 생략)' : body;
const requestBody = JSON.stringify({
anthropic_version: 'bedrock-2023-05-31', max_tokens: 500, system: systemPrompt,
messages: [{ role: 'user', content: `Subject: ${subject}\nFrom: ${sender}\n\n${truncatedBody}` }],
});
const text = await invokeBedrockModel(awsCredentials, 'anthropic.claude-sonnet-4-20250514-v1:0', requestBody);
const jsonMatch = text.match(/\{[\s\S]*\}/);
if (!jsonMatch) { throw new Error(`Bedrock 응답에서 JSON 추출 실패: ${text}`); }
const classification: TaskClassification = JSON.parse(jsonMatch[0]);
if (!classification.title) classification.title = subject || '(제목 없음)';
if (!classification.description) classification.description = '';
if (!['high', 'medium', 'low'].includes(classification.priority)) classification.priority = 'medium';
return classification;
}
// 메인 핸들러
serve(async (req) => {
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
const startTime = Date.now();
let emailsFound = 0, tasksCreated = 0, errors = 0;
const details: Array<{ emailId: string; subject: string; status: string; error?: string }> = [];
try {
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const serviceRoleKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
const adminClient = createClient(supabaseUrl, serviceRoleKey, { auth: { autoRefreshToken: false, persistSession: false } });
const { data: configData, error: configError } = await adminClient.from('email_integration_config').select('*').eq('id', 'main').single();
if (configError || !configData) return new Response(JSON.stringify({ success: false, error: '이메일 연동 설정이 없습니다.' }), { headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 400 });
if (!configData.enabled) return new Response(JSON.stringify({ success: true, message: '비활성화 상태', skipped: true }), { headers: { ...corsHeaders, 'Content-Type': 'application/json' } });
if (!configData.gmail_client_id || !configData.gmail_client_secret || !configData.gmail_refresh_token) return new Response(JSON.stringify({ success: false, error: 'Gmail OAuth2 자격증명 미설정' }), { headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 400 });
if (!configData.aws_access_key_id || !configData.aws_secret_access_key) return new Response(JSON.stringify({ success: false, error: 'AWS Bedrock 자격증명 미설정' }), { headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 400 });
const awsCredentials: AwsCredentials = { accessKeyId: configData.aws_access_key_id, secretAccessKey: configData.aws_secret_access_key, region: configData.aws_bedrock_region || 'us-east-1' };
let accessToken: string;
try { accessToken = await refreshGmailToken(configData.gmail_client_id, configData.gmail_client_secret, configData.gmail_refresh_token); }
catch (tokenError) { await adminClient.from('email_integration_config').update({ enabled: false, updated_at: new Date().toISOString() }).eq('id', 'main'); return new Response(JSON.stringify({ success: false, error: `Gmail 인증 실패: ${tokenError.message}` }), { headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 401 }); }
const messages = await listUnreadMessages(accessToken, configData.gmail_target_label || 'INBOX', 10);
emailsFound = messages.length;
if (messages.length === 0) { await adminClient.from('email_integration_config').update({ last_sync_at: new Date().toISOString() }).eq('id', 'main'); await adminClient.from('email_sync_log').insert({ emails_found: 0, tasks_created: 0, errors: 0, duration_ms: Date.now() - startTime }); return new Response(JSON.stringify({ success: true, message: '새 이메일 없음', emailsFound: 0 }), { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }); }
for (const msg of messages) {
try {
const { data: existing } = await adminClient.from('processed_emails').select('id').eq('id', msg.id).single();
if (existing) { await markAsRead(accessToken, msg.id); details.push({ emailId: msg.id, subject: '(이미 처리됨)', status: 'skipped' }); continue; }
const fullMessage = await getMessage(accessToken, msg.id);
const subject = getHeader(fullMessage, 'Subject'), sender = getHeader(fullMessage, 'From'), body = getBody(fullMessage);
const classification = await classifyEmail(awsCredentials, subject, sender, body, configData.classification_prompt);
const taskId = `TASK-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`, now = new Date().toISOString();
const newTask = { id: taskId, title: classification.title, description: `📧 이메일에서 자동 생성\n\n발신자: ${sender}\n제목: ${subject}\n분류: ${classification.category}\n\n${classification.description}`, status: configData.default_status || 'todo', priority: classification.priority || configData.default_priority || 'medium', assignees: configData.default_assignee_id ? [configData.default_assignee_id] : [], managers: [], progress: 0, order: 0, gantt_order: 0, created_by: 'email-integration', created_at: now, is_public: true, followers: configData.default_assignee_id ? [configData.default_assignee_id] : [], history: JSON.stringify([{ userId: 'email-integration', action: 'create', timestamp: now, detail: `Gmail에서 자동 생성 (${sender})` }]), custom_fields: JSON.stringify({ source: 'email', emailId: msg.id, emailSender: sender, emailSubject: subject, emailCategory: classification.category }) };
const { error: insertError } = await adminClient.from('tasks').insert(newTask);
if (insertError) throw new Error(`Task 삽입 실패: ${insertError.message}`);
await adminClient.from('processed_emails').insert({ id: msg.id, task_id: taskId, gmail_thread_id: msg.threadId, subject, sender, classification_result: classification });
await markAsRead(accessToken, msg.id);
if (configData.default_assignee_id) { await adminClient.from('notifications').insert({ id: `NOTIF-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`, type: 'task_assigned', user_id: configData.default_assignee_id, from_user_id: 'email-integration', task_id: taskId, task_title: classification.title, preview: `📧 이메일에서 자동 생성: ${subject}`, read: false, created_at: now }); }
tasksCreated++; details.push({ emailId: msg.id, subject, status: 'created' });
} catch (emailError) { errors++; const errorMsg = emailError instanceof Error ? emailError.message : String(emailError); details.push({ emailId: msg.id, subject: '', status: 'error', error: errorMsg }); await adminClient.from('processed_emails').upsert({ id: msg.id, gmail_thread_id: msg.threadId, error: errorMsg }).catch(() => {}); }
}
await adminClient.from('email_integration_config').update({ last_sync_at: new Date().toISOString() }).eq('id', 'main');
await adminClient.from('email_sync_log').insert({ emails_found: emailsFound, tasks_created: tasksCreated, errors, details, duration_ms: Date.now() - startTime });
return new Response(JSON.stringify({ success: true, emailsFound, tasksCreated, errors, details, durationMs: Date.now() - startTime }), { headers: { ...corsHeaders, 'Content-Type': 'application/json' } });
} catch (error) {
console.error('gmail-to-task ERROR:', error.message);
try { const supabaseUrl = Deno.env.get('SUPABASE_URL')!; const serviceRoleKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!; const adminClient = createClient(supabaseUrl, serviceRoleKey, { auth: { autoRefreshToken: false, persistSession: false } }); await adminClient.from('email_sync_log').insert({ emails_found: emailsFound, tasks_created: tasksCreated, errors: errors + 1, details: { fatalError: error.message, processedDetails: details }, duration_ms: Date.now() - startTime }); } catch (_) {}
return new Response(JSON.stringify({ success: false, error: error.message }), { headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 500 });
}
});
Gmail 연결 버튼으로 Refresh Token을 자동 발급하는 함수입니다.
gmail-oauth-callback// Supabase Edge Function: Gmail OAuth2 Callback
// Google 로그인 후 Refresh Token을 자동으로 DB에 저장
import { serve } from "https://deno.land/std@0.168.0/http/server.ts"
import { createClient } from "https://esm.sh/@supabase/supabase-js@2"
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};
serve(async (req) => {
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
try {
const { action, code, redirectUri } = await req.json();
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const serviceRoleKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
const adminClient = createClient(supabaseUrl, serviceRoleKey, { auth: { autoRefreshToken: false, persistSession: false } });
const { data: config } = await adminClient.from('email_integration_config').select('gmail_client_id, gmail_client_secret').eq('id', 'main').single();
if (!config?.gmail_client_id || !config?.gmail_client_secret) return new Response(JSON.stringify({ success: false, error: '먼저 Gmail Client ID와 Client Secret을 설정에서 저장하세요.' }), { headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 400 });
if (action === 'get_auth_url') {
const authUrl = 'https://accounts.google.com/o/oauth2/v2/auth?client_id=' + encodeURIComponent(config.gmail_client_id) + '&redirect_uri=' + encodeURIComponent(redirectUri) + '&response_type=code&scope=' + encodeURIComponent('https://www.googleapis.com/auth/gmail.modify') + '&access_type=offline&prompt=consent';
return new Response(JSON.stringify({ success: true, authUrl }), { headers: { ...corsHeaders, 'Content-Type': 'application/json' } });
}
if (action === 'exchange_token') {
if (!code) return new Response(JSON.stringify({ success: false, error: 'code가 없습니다.' }), { headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 400 });
const tokenResponse = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ code, client_id: config.gmail_client_id, client_secret: config.gmail_client_secret, redirect_uri: redirectUri, grant_type: 'authorization_code' }),
});
const tokenData = await tokenResponse.json();
if (!tokenData.refresh_token) return new Response(JSON.stringify({ success: false, error: 'Refresh Token 발급 실패: ' + JSON.stringify(tokenData) }), { headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 400 });
await adminClient.from('email_integration_config').update({ gmail_refresh_token: tokenData.refresh_token, updated_at: new Date().toISOString() }).eq('id', 'main');
return new Response(JSON.stringify({ success: true, message: 'Gmail 연결 완료! Refresh Token이 자동 저장되었습니다.' }), { headers: { ...corsHeaders, 'Content-Type': 'application/json' } });
}
return new Response(JSON.stringify({ success: false, error: '알 수 없는 action' }), { headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 400 });
} catch (error) {
return new Response(JSON.stringify({ success: false, error: error.message }), { headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 500 });
}
});
Supabase SQL Editor에서 실행합니다. Free 플랜에서는 이 단계를 건너뛰고 TeamBro 설정의 🔄 테스트 버튼으로 수동 실행할 수 있습니다.
Supabase Dashboard > Settings > API > service_role secret 키를 복사해서 넣으세요. (anon key가 아닙니다!)
CREATE EXTENSION IF NOT EXISTS pg_cron;
CREATE EXTENSION IF NOT EXISTS pg_net;
SELECT cron.schedule(
'gmail-to-task-sync',
'*/5 * * * *',
$$
SELECT net.http_post(
url := 'https://YOUR_PROJECT_REF.supabase.co/functions/v1/gmail-to-task',
headers := '{"Content-Type":"application/json","Authorization":"Bearer YOUR_SERVICE_ROLE_KEY"}'::jsonb,
body := '{"source":"pg_cron"}'::jsonb
);
$$
);
-- 스케줄 확인
SELECT * FROM cron.job;
-- 스케줄 삭제 (필요 시)
-- SELECT cron.unschedule('gmail-to-task-sync');
설정 > 관리자 설정 > 📧 이메일 연동 섹션에서:
좌측 메뉴 「전자결재」에서 문서 기안·결재·문서함을 관리합니다. DB는 자동 구성되어 별도 설치가 필요 없습니다. 결재선 종류는 결재·합의·재무합의·참조이며, 상태는 승인/반려/협의필요/확인입니다.
결재양식관리 → 신규등록에서 양식을 만듭니다. 「양식 본문(서식 디자인)」 에디터에 표·서식으로 양식을 디자인해 저장하면, 기안 작성 시 그 서식이 에디터에 그대로 불러와집니다. 작성자가 채울 칸은 빈칸으로 두세요. (문서종류 slug·제목·분류·노출순서·사용유무도 함께 설정)
결재선등록에서 자주 쓰는 결재선(결재·합의·재무합의·참조 + 결재자)을 저장합니다. 개인용 또는 전체 공용(관리자)을 선택할 수 있고, 기안 작성 시 「저장된 결재선」 드롭다운에서 불러옵니다.
기안작성(또는 기안중문서 → 등록하기)에서 ① 문서종류 선택(양식 자동 로드) ② 결재선 지정(직접 추가 또는 저장된 결재선) ③ 제목·내용 작성 ④ 첨부파일 첨부. 「기안하기」로 상신하거나 「임시저장」 후 나중에 이어서 작성합니다(임시저장은 기안중문서에서 다시 열어 편집).
결재자는 결재중문서 → 결재필요에서 문서를 열어 승인 / 반려 / 협의필요를 처리합니다(참조자는 「확인」). 승인하면 다음 결재자에게 넘어가고, 마지막 승인 시 문서가 완료됩니다. 반려 사유나 협의는 의견·댓글로 남길 수 있습니다.
기안중문서(내가 올린 문서 — 진행/반려/임시저장), 결재중문서(내가 결재할 문서 — 결재필요/예정/진행/참조), 문서보관함(완료된 문서)에서 상태별로 확인합니다. 제목·기안자·기안부서·문서번호·문서종류·기안일로 검색하고 페이지를 넘길 수 있습니다.